Reputation: 797
How can I generate a random number which is a multiple of a given number while also making sure the number is also within a specified range? If there are no such multiples, it should return NaN
.
const generateMultiple = (multipleOf, min, max) => {
//how to implement?
}
generateMultiple(4, -8, 5)
//should return either -8, -4, 0, 4
generateMultiple(2.1, 1, 5)
//should return either 2.1, 4.2
generateMultiple(7, 1, 5)
//should return NaN
Upvotes: 1
Views: 160
Reputation: 1
declare your min, max, multiple numbers like this
const multiple = 2;
const min = 1;
const max = 25;
use the below code to generate in a funtion and call when needed
(Math.floor(((Math.random()/multiple) * max) + min)) * multiple
Upvotes: 0
Reputation: 414
Below function will do that..
function generateMultiple(multipleOf, min, max) { return Math.floor(Math.random() * (max-min) + min) ) * multipleOf; }
Upvotes: 0
Reputation: 89304
You can normalize the range by dividing the endpoints by the number, generate a number in that range, and then multiply by the number to generate the multiple.
const generateMultiple = (multipleOf, min, max) => {
const low = Math.ceil(min / multipleOf), high = Math.floor(max / multipleOf);
return low <= high ?
(Math.floor(Math.random() * (high - low + 1)) + low) * multipleOf
: NaN;
}
Upvotes: 3