Search code examples
javascriptnode.jsmath

Why JavaScript Math.random() returns same number multiple times


I have an array with two items and I need to random a choice of this items but the most of times I get the same item from array...

See the code:

var numbers = Array(523,3452);
var choice = numbers[Math.floor(Math.random()*numbers.length)];
console.log("Choice:", choice);

How can I avoid this kind of behavior?


Solution

  • Random numbers can appear in streaks; that's part of being random. But over time the law of large numbers should take over and even out those streaks. You can test that easily enough by running this a bunch of times and counting:

    var numbers = Array(523,3452);
    let counts = [0,0]
    
    for (let i = 0; i < 10000; i++) {
        let choice = numbers[Math.floor(Math.random()*numbers.length)];
        if (choice ===  523) counts[0]++
        else if (choice == 3452) counts[1]++
    }
    
    // counts should be about even
    console.log(counts);