Kazuto_Ute
Kazuto_Ute

Reputation: 797

How to generate a random multiple of a given number bounded to a given range?

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

Answers (3)

chrono pegasus
chrono pegasus

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

Karthikeyan
Karthikeyan

Reputation: 414

Below function will do that.. function generateMultiple(multipleOf, min, max) { return Math.floor(Math.random() * (max-min) + min) ) * multipleOf; }

Upvotes: 0

Unmitigated
Unmitigated

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

Related Questions