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
Shuffling a pre-filled array would be a good solution:
// shuffle function taken from here
// http://stackoverflow.com/a/2450976/603003
alert( shuffle( [1,2,3,4] ) );
Another apporach consists in the following function:
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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments