Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get unique numbers from Math.random in javascript?

Tags:

javascript

When I call this statement 4 times in a loop, it gives me duplicate random numbers.

var a = (parseInt(Math.random() * 4))+1

For example, sometimes it gives me 1,3,2,4 (fine!!), but sometimes it produes like 1, 3, 1,4 etc.

How I make sure that when my loop runs 4 times, I get unique set everytime


1 Answers

Shuffling a pre-filled array would be a good solution:

→ jsBin.com

// shuffle function taken from here
// http://stackoverflow.com/a/2450976/603003
alert( shuffle( [1,2,3,4] ) );

Another apporach consists in the following function:

→ jsFiddle

function gen4Numbers() {
    var numbers = [];
    while (numbers.length < 4) {
        var newNr = (parseInt(Math.random() * 4))+1;
        if (numbers.indexOf(newNr) == -1) {
            numbers.push(newNr);
        }
    }
    return numbers;
}
alert(gen4Numbers());

You should be warned that there is a very probability that this code will loop forever.

like image 156
ComFreek Avatar answered Nov 20 '25 20:11

ComFreek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!