Reputation: 3347
Hi am trying to generate random multiples of 100 using javascript.
I would expect the following to generate a random number between 1000 and 4000. Then check to see if it is a multiple of 100 and if so return it. And if not try generating another number.
I expected that in the else section of the if loop, rand() would just call the function again.
function rand() {
num = Math.floor(Math.random() * 4000) + 1000;
if (num % 100 == 0) {
return num;
} else {
rand();
}
}
Plunker: https://plnkr.co/edit/7tSGNiGQBUAYJsdMVeEr?p=preview
For the distances I am getting undefined instead of multiples of 100
Upvotes: 1
Views: 1296
Reputation: 13196
Your method (generate any random number between 1000 and 4000 and only return multiples of 100) is 100 times slower than necessary and doing it recursively will probably crash the stack. Do a little elementary arithmetic:
function rand() { return 100 * Math.floor(30 * Math.random() + 10); }
You don't specify whether the 4000 is inclusive or not. If so, make that 30 above a 31.
Upvotes: 2
Reputation: 5648
Few things here 1, change your rand function to have a different range
num = Math.floor(Math.random() * (3000) + 1000);
Second, you are making a recursive function by calling it inside it self, for this you need to return the value to the past call function, if not the value stays on the last succesfull call.
else {
num = rand();
return num;
}
Hope this helps :>
function rand() {
let num = Math.floor(Math.random() * (3000) + 1000);
if (num % 100) {
num = rand();
}
return num;
}
console.log(rand());
Upvotes: 1
Reputation: 1075309
I would expect the following to generate a random number between 1000 and 4000. Then check to see if it is a multiple of 100 and if so return it. And if not try generating another number.
To do that, you'd have to return the result of the recursive call to rand
:
} else {
return rand();
}
But there's no need whatsoever to do that. To get random multiples of 100 in the range 1000 <= n < 4000:
return (Math.floor(Math.random() * 30 + 10)) * 100;
E.g., create a random number in the range 10 <= n < 40 and then multiply it by 100. :-)
Live Example:
function rand() {
return (Math.floor(Math.random() * 30 + 10)) * 100;
}
for (var n = 0; n < 100; ++n) {
console.log(rand());
}
.as-console-wrapper {
max-height: 100% !important;
}
Upvotes: 11
Reputation: 10096
You are simply missing a return statement, without it, the function is just run and when a match is found it's returned to nothing
function rand() {
num = Math.floor(Math.random() * 4000) + 1000;
if (num % 100 == 0) {
return num;
} else {
return rand(); //<-- here
}
}
console.log(rand())
Upvotes: 1