Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
1  
Duplicate: stackoverflow.com/questions/15584716/… –  apelsinapa Mar 23 '13 at 9:33
add comment

4 Answers

Generate a range of numbers:

var numbers = [1, 2, 3, 4];

And then shuffle it:

function shuffle(o) {
    for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
};

var random = shuffle(numbers);
share|improve this answer
    
Posted this at the same time. +1 for a more stable method. –  Ingo Bürk Mar 23 '13 at 9:53
add comment

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.

var elements = [1, 2, 3, 4];
elements.shuffle(); // not a standard Javascript function, needs to be implemented

while( elements.length > 0 ) {
    console.log( elements.pop() );
}
share|improve this answer
    
+1, see stackoverflow.com/q/2450954/989121 for shuffle –  thg435 Mar 23 '13 at 10:12
add comment

If the range of random numbers is not very large you can use this:

var exists = [],
    randomNumber,
    max = 5;
for(var l = 0; l < max; l++) {
   do {
       randomNumber = Math.floor(Math.random() * max);  
   } while (exists[randomNumber]);
   exists[randomNumber] = true;
   alert(randomNumber)
}

DEMO

share|improve this answer
add comment

One more way to do it:

for (var a = [0, 1, 2, 3, 4], i = a.length; i--; ) {
    var random = a.splice(Math.floor(Math.random() * (i + 1)), 1)[0];
    console.log(random);
}

Don't know if it's even possible to make it more compact.

Tests: http://jsfiddle.net/2m3mS/1/

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.