How to get 2 random numbers divisible by each other? - javascript

I'm generating 2 random numbers:
1) The first number must be random from 1 to 30
2) The second number must be random from 1 to 10
I'm simply trying to have the first number divisible by the second number or vice-versa, and finally, alert the result. My question is how to get the result of the division of 2 random numbers? Can anyone point me in the right direction? Thanks a lot in advance!.
Note: the first number must be divisible by the second number.
Here's my code:
var arr = [];
for (var i = 0; i < 2; i++) {
do {
var firstRandomNumber = Math.floor(Math.random()*30) + 1;
var secondRandomNumber = Math.floor(Math.random()*10) + 1;
if(firstRandomNumber % secondRandomNumber === 0){
correctResult = result;
arr.push(correctResult);
}
} while ((firstRandomNumber % secondRandomNumber === 0));
}
console.log(arr);

I would suggest a more functional approach: create a function that creates two random numbers, and returns them if one is divisible by the other. Then, just call that function until you get a truthy result:
function tryGetDivisible() {
var firstRandomNumber = Math.floor(Math.random() * 30) + 1;
var secondRandomNumber = Math.floor(Math.random() * 10) + 1;
if (firstRandomNumber % secondRandomNumber === 0) {
console.log(firstRandomNumber, secondRandomNumber);
return firstRandomNumber / secondRandomNumber;
}
}
let result;
while (!result) result = tryGetDivisible();
const arr = [result];
console.log(arr);

Few things:
Your while loop should be looping until firstRandomNumber % secondRandomNumber === 0, so you want to just keep looping while it's not true.
result isn't set anywhere, so I added the result in the array
The if(firstRandomNumber % secondRandomNumber === 0){ is redundant. When the do/while loop completes, it will have the do numbers that matched. Simply move the arr.push() outside that loop.
var arr = [];
for (var i = 0; i < 2; i++) {
do {
var firstRandomNumber = Math.floor(Math.random()*30) + 1;
var secondRandomNumber = Math.floor(Math.random()*10) + 1;
} while ((firstRandomNumber % secondRandomNumber !== 0));
console.log('first', firstRandomNumber, 'second', secondRandomNumber);
arr.push(firstRandomNumber / secondRandomNumber);
}
console.log(arr);

A much simpler approach is to get the first random number, and then try getting the second random number until they are divisible. So here will be the code:
var firstRandomNumber = Math.floor(Math.random()*30) + 1;
while (firstRandomNumber % secondRandomNumber !== 0) {
var secondRandomNumber = Math.floor(Math.random()*10) + 1;
}
console.log(firstRandomNumber + "," + secondRandomNumber);

Since the first must be divisible by the second, my approach would be:
Generate the second number.
Determine the maximum multiple of the second number that is no more than 30 (e.g., Math.floor(30/firstNumber)).
Select a multiple at random and use that as the first number. You simply need to select a random number between 1 and the largest allowed multiplier (inclusive).
This way, there's no need to do a generate-and-test loop, which could go on an unbounded number of times before a successful pair is generated.

If you want to avoid the while loop, you can pick the first number, then assemble the possible second numbers in an array. Then randomly pick one of these:
let first = Math.floor(Math.random() * 10) + 1
// all possible divisible numbers
let factors = Array.from({length: 30}, (_, i) => i + 1)
.filter(i => first % i === 0 || i % first === 0)
//pick one
let second = factors[Math.floor(Math.random() * factors.length)]
console.log(first, second)

Related

Iterate over uneven array

So I have a dataset of 16 items, I want to loop through them every 5 items after the first set of 6 so the columns are 6 5 5.
Initially I tried something like this, but then I remembered I had that one orphaned item.
if(thisI <= 6) {
y = prevtitle.position[0];
} elseif(thisI % 5 == 0) {
y = prevtitle.position[0] + w + (p *3);
} else {
y = prevtitle.position[0];
}
Not sure if there is a simple way to do the first 6 and then the next ones in five without a bunch of nested if statements.
Using Array#splice:
const splitArr = (arr = []) => {
const array = [...arr];
const res = array.length ? [array.splice(0, 6)] : [];
while(array.length) res.push(array.splice(0, 5));
return res;
}
console.log( splitArr([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]) );
Would a simple ternary expression work for you?
let num = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
num.forEach((n,i) => {
y = (i<=6 || i % 5 == 0) ? prevtitle.position[0] : prevtitle.position[0] + w + (p *3) ;
})
I presume that you're skipping the first position, and jumps directly to the 6th position.
Just use a normal for loop.
Calculate the remainder for the number of steps that you will make. 16 % 5 results in 1 remainder.
step - countForZero + remainder sets the start point in the for loop.
i += step replaces the typical i++ in the for loop.
The method below can make any kind of leap, and it doesn't matter how many items there are in the array.
let num = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
function getEvery(step, arr) {
let newArr = [],
remainder = arr.length % step,
countForZero = 1;
for (let i = step - countForZero + remainder; i < arr.length; i += step) {
newArr.push(arr[i]);
}
return newArr;
}
console.log( getEvery(5, num) );

random number that always makes a total of 100 into array

Hi i am trying to create an array that always has a total of 100 based on random numbers. I get it to work when there is 2 or 3 rows but i can't get it to work if there are more as 4. Meaning i need to change the middle section. Here is simple code i made: (the length is the number of rows in the array)
var array = []
var length = 3; //4 , 5 , 6 ...
var number;
var calculate;
var totalProcessed;
for (i = 0; i < length; i++) {
// FIRST ONE
if(i == 0){
number = Math.floor(Math.random() * 100) + 1;
console.log(number);
totalProcessed = number;
array.push(number)
}
// MIDDLE SECTION
if(i > 0 && i == length-1){
if(length > 2){
calculate = 100 - number;
number = Math.floor(Math.random() * calculate) + 1
totalProcessed = totalProcessed + number;
console.log(number);
array.push(number)
}
}
// LAST ONE
if(i == length -1){
var lastOne = 100-totalProcessed;
console.log(lastOne);
array.push(lastOne)
}
}
console.log(array);
How should i change the middle section to be able to capture the numbers?
There are two errors in this code:
First:
You should change the == to < in order to be able to loop more then 3 times:
if(i > 0 && i == length-1)
Second:
I think your error occurs on the following line. You subtract number from 100 which is the previous generated number. You should instead generate a random number from everything that is left:
calculate = 100 - number;
So I think you should subtract the totalProcessed value instead.
calculate = 100 - totalProcessed;
Full working snippet:
var array = []
var length = 5; //4 , 5 , 6 ...
var number;
var calculate;
var totalProcessed;
for (i = 0; i < length; i++) {
// FIRST ONE
if(i == 0){
number = Math.floor(Math.random() * 100) + 1;
console.log(number);
totalProcessed = number;
array.push(number)
}
// MIDDLE SECTION
if(i > 0 && i < length-1){
if(length > 2){
calculate = 100 - totalProcessed;
number = Math.floor(Math.random() * calculate) + 1
totalProcessed = totalProcessed + number;
console.log(number);
array.push(number)
}
}
// LAST ONE
if(i == length -1){
var lastOne = 100-totalProcessed;
console.log(lastOne);
array.push(lastOne)
}
}
console.log(array);
let total = 0;
array.forEach(el => total += el)
console.log(total)
You should replace the "==" in the if statement of the middle section by "<".
I found your approach a bit hard to comprehend. Is the question setup same as what code is trying to do? Therefore I wrote an alternate example that solves the question (as currently explained):
let limit = 100;
const numbers = [...Array(limit)].map(() => {
const random = Math.floor(Math.random() * 100) + 1;
if (limit - random > 0) {
limit -= random;
return random;
}
return null;
}).concat(limit).filter((num) => num)
console.log(numbers);
It goes through 100 iterations (in case there would come only 1's :D) and then decreases the limit. And if next random number fits into limit, it's added to the result, otherwise it's a null.
And if it happens that after 100 iterations there are still limit left, it's concatenated to an existing array. Finally we filter out all the "nulls" (numbers that didn't fit in to limit) and voila.

Display number series with modulo in JavaScript

I'm currently trying to display number series (for 2, 3, 4, 5, 6 and 7) in JavaScript. I was looking for the smallest number (x), which results in modulo = 1, if divided by 2, 3, 4, 5 and 6. If the same number (x) is divided by 7, id should result in modulo = 0. I'm not quite sure, if I'm explaining it correct. It should be like this: x % 2 = 1, x % 3 = 1, x % 4 = 1, x % 5 = 1, x % 6 = 1, x % 7 = 0.
The result is 301. My code looks like this and it works fine:
var seven = 7;
var six;
var five;
var four;
var three;
var two;
while (six != 1 || five != 1|| four != 1|| three != 1|| two != 1)
{six = seven % 6;
five = seven % 5;
four = seven % 4;
three = seven % 3;
two = seven % 2;
console.log(seven);
seven += 7;}
It displays all the numbers in the seven-series, until 301. Now, I wanted some more while-loops for the other numbers (2-6), that work the same why and show all the different numbers/steps in each series, until 301. I'm new to JavaScript and I just don't get it. I tried to modify my code, so that it should work with the other number series, but it doesn't. Or is there any other (maybe a better) way to do this? With some nested loops/functions? It only should be possible to display every number in each number series, but not all at the same time (in the end, there should be buttons, which show (by clicking them) the different number series with all the numbers/steps until 301). Thank you soso much!
When doing this you should probably use a loop to simplify your life.
Start x at 0 and iterate to (for example) 100.000.
For every iteration, check to see if x % 2 / 3 / 4 / 5 / 6 is equal to 0. Then check to see if x % 7 === 1. If both these conditions are true, log the value and break the for loop.
The smallest value that answers this seems to be 120.
const numbers = [2,3,4,5,6]
const special = 7;
for(let x = 0; x < 100000; x++){
const isModulo0ForAllNumbers = numbers.every(n => (x % n) === 0);
const isModulo1ForSpecial = (x % special) === 1;
if(isModulo0ForAllNumbers && isModulo1ForSpecial){
console.log(`Smallest number found: ${x}`);
break;
}
}
Sometimes this is not possible to find such a number and you'll get infinite loop with unexpected behavior. This is a possible approach (see the comments inside):
// first define the greatest common divisor
// for two numbers - we'll need that later
let gcd = function(a, b) {
// classic 'Euclidean' method with recursion
if(a == 0) {
return b;
}
if(a > b) {
return gcd(b, a);
}
return gcd(b % a, a);
}
// define your series
let series = [2,3,4,5,6,7];
// now you need least common multiple for all numbers
// except for the last one
lcm = series[0];
for (let i = 1; i < series.length - 1; i++) {
lcm *= series[i] / gcd(lcm, series[i])
}
// the last number from series
let last = series[series.length - 1];
// exercise: you can research or think for smarter solution
// I will just loop until we get the result
if(gcd(lcm, last) == 1) {
let r = lcm + 1;
while(r % last) {
r += lcm;
}
console.log('number found: ', r);
} else {
// not possible
console.log('impossible to find the number');
}
You could take an array of values for the modulo calculation and use a function for getting a check of a value.
const f = x => [2, 3, 4, 5, 6].every(v => x % v === 1) && x % 7 === 0;
var value = 0;
while (!f(value)) value += 7;
console.log(value);

How to a count a specific digit in a number with javascript

I am trying to write a block of code which will separate digits (with modulus operator) in a number first and count how many digit "6" are there in the number.
I tried so many things but I think I have logic problem with the way I think.
output = [];
var count = 0;
while (a > 0){
output.push(a % 10);
a = Math.floor(a/10);
if(a == 6){
count++;
}
}
When I run this code on Safari, It shows the entered number as it is, but it shows "0" for the variable count.
Math.floor(a/10) doesn't give the current digit. a % 10 gives the current digit.
You have check if the current digit a % 10 is 6.
Live Example:
let output = [];
let count = 0;
let a = 1667;
while (a > 0) {
let digit = a % 10;
output.push(digit);
if (digit == 6) {
count++;
}
a = Math.floor(a / 10);
}
console.log(count);
You know the last digit, so you can subtract it and divide with 10, instead of using Math.floor.
let number = 1626364656; // has 5 sixes
let sixesCount = 0;
while (number > 0) {
const digit = number % 10;
if (digit === 6) {
sixesCount++;
}
number = (number - digit) / 10;
}
console.log('Found', sixesCount, 'sixes.'); // "Found 5 sixes."

Javascript - How to sum up all the first and last digit of a number until only two digits are left?

I am fairly new to programming, just knowing the basics in Javascript and Swift. I am trying to write a simple program which creates, from any entered number, a two digit number by summing up the first and last digit until only two digits are finally left.
Here is an example:
num = 1234567:
1+7 = 8
2+6 = 8
3+5 = 8
4 remains
So the first result is: 8884. Now everything is added again:
8+8 = 16
8+4 = 12
The result is 1612. Again everything is summed up:
1+2 = 3
6+1 = 7
The result is 37 - which is also the final result.
I am struggling with two things. First the while loop. I was thinking about casting num.toString() and then do a while loop like this in which I change the string to an int again:
num.toString()
while (num.length > 2) {
num = num.parseInt(num, 10);
...
}
But this doesn't work properly, plus it gets crazy complicated I guess because I would have to switch between string and int each new round, right?
I know how to add all digits together until I get a two digit number (it took me a while to figure this one out) and I am not even sure if this is a good way to do it:
var sum = num
.toString()
.split('')
.map(Number)
.reduce(function (a, b) {
return a + b;
}, 0);
But obviously I cannot use this here and I have no idea how to change the code so that the first and last digit are added together.
Slightly different approach:
function sum(num) {
var numString = num.toString();
var newString = "";
while (numString.length > 1) { // (1)
newString += (parseInt(numString[0]) + parseInt(numString[numString.length - 1])).toString(); // (2)
numString = numString.substring(1, numString.length - 1); // (3)
}
newString += numString; // (4)
if (newString.length > 2) { // (5)
console.log(newString)
return sum(newString);
} else {
return newString;
}
}
console.log(sum(1234567));
Outputs:
8884
1216
73
Brief explanation of what's going on:
(1) Your while loop will process the string until there's either 1 or
0 characters left
(2) Add the sum of your first and last character to
your newString
(3) Remove the first and last characters from your
numString now that they've been saved to the newString. Because
you're overwriting the value in numString and shrinking it, this
will eventually satisfy the while condition of a numString with
less than 2 characters
(4) Add the remaining characters to
newString, which will either be 1 or 0 characters depending on the
length of the original number
(5) if your newString is more than 2
characters, run this method again. Otherwise return your result
Try this buddy. Its just using simple for loop. Its loops upto half of number and add corresponding. The final result according to ur logic should be 73 not 37
function sum(num){
//if num is greater than or equal to 2 end the function and return final value
if(num.length <= 2) return num;
//converting the num to string beacuse first time input will be number
num = String(num);
let result = '';
//creating a loop upto half of length of the num
for(let i = 0;i<num.length/2;i++){
//if the number is not middle one
if(i !== num.length - 1 - i)
{
//adding the sum of corresponding numbers to result
result += parseInt(num[i]) + parseInt(num[num.length - 1 - i]);
}
//if the number is middle number just add it to result
else result += num[i]
}
return sum(result);
}
console.log(sum(1234567))
You could take a nested while loop and check the string length for the outer loop and the left and right indices for the inner loop
function add(n) {
var s = n.toString(),
l, r,
sum;
while (s.length > 2) {
l = 0;
r = s.length - 1;
sum = [];
while (l < r) {
sum.push(+s[l++] + +s[r--]);
}
if (l === r) sum.push(s[l]);
s = sum.join('');
}
return +s;
}
console.log(add(1234567));
The same but with a recursive function.
function add(n) {
var s = n.toString(),
l = 0, r = s.length - 1,
sum = [];
if (s.length <= 2) return n;
while (l < r) sum.push(+s[l++] + +s[r--]);
if (l === r) sum.push(s[l]);
return add(+sum.join(''));
}
console.log(add(1234567));

Categories

Resources