开发者

Making a random number that's a multiple of 10

开发者 https://www.devze.com 2023-02-14 12:51 出处:网络
I\'m looking to create a random number between two ranges that is a multiple of 10. For example, if I fed the function the parameters 0, 100 it would return one of these numbers:

I'm looking to create a random number between two ranges that is a multiple of 10.

For example, if I fed the function the parameters 0, 100 it would return one of these numbers:

0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100

but nothing like 63 or 55.

And yes I'm aware this defeats the point of true "randomness", but I just need a quick easy way to g开发者_StackOverflowet a number that's a multiple of 10 between two ranges.

Thanks. :)


I guess it can help:

var randomnumber=Math.floor(Math.random()*11)*10


it's just one line:

function rand_10(min, max){
    return Math.round((Math.random()*(max-min)+min)/10)*10;
}


var a = 67;
var b = 124;
var lo = a + 10 - (a % 10) 
var hi = b - (b % 10)
var r = lo + 10 * parseInt(Math.random() * ((hi - lo)/10 + 1));


function rand(maxNum, factorial) { 
    return Math.floor(Math.floor(Math.random() * (maxNum + factorial)) / factorial) * factorial; 
};

Takes two parameter

  • maxNum Maximum number to be generated in random
  • factorial The factorial/incremental number

    1. multiplies the random number generated to the maxNum.
    2. Rounds down the result.
    3. Divides by the factorial.
    4. Rounds down the result.
    5. then multiplies again by the factorial.


Use a normal random number function like this one:

function GetRandom( min, max ) {
    if( min > max ) {
        return( -1 );
    }
    if( min == max ) {
        return( min );
    }

    return( min + parseInt( Math.random() * ( max-min+1 ) ) );
}

As this will only return integers ("multiples of 1"), you can multiply by 10 and get only multiples of 10.

randomNumberMultipleOfTen = GetRandom(0,10) * 10;

Of course you can merge both into one function if you want to, I'll leave this as an exercise to you.


This seems to do the work

Math.floor(Math.random() * 10) * 10

If you modify that a little you can easily make it between any two numbers.


  1. Take the difference of the two parameters.
  2. Divide the difference by 10.
  3. Generate a random number from 0 to the result of the division.
  4. Multiply that by 10.
0

精彩评论

暂无评论...
验证码 换一张
取 消