I want to generate each number between 0 to 4 randomly using javascript and each number can appear only once. So I wrote the code:
for(var l=0; l<5; l++) {
var randomNumber = Math.floor(Math.random()*5);
alert(randomNumber)
}
but this code is repeating the values. Please help.
Generate random numbers without any range
The answers given by Adil and Minko have a major problem (although Minko at least constrained it to a small set of numbers): They go over the same numbers over and over again.
In that sense, a better method would be to create the array containing the possible values, shuffle it and then just pop elements off of it. This will require the complexity of shuffling the array, but it will get rid of the problem mentioned above.
Generate a range of numbers:
And then shuffle it:
Appreciate all your help. But probably another way to generate random number in a given max range can be implemented as per below.
One more way to do it:
Don't know if it's even possible to make it more compact.
Tests: http://jsfiddle.net/2m3mS/1/
Here is embed demo: