How to randomly generate numbers without repetition in javascript?
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);
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/
Here is embed demo:
$('button').click(function() {
$('.output').empty();
for (var a = [0, 1, 2, 3, 4], i = a.length; i--; ) {
var random = a.splice(Math.floor(Math.random() * (i + 1)), 1)[0];
$('.output').append('<span>' + random + '</span>');
}
}).click();
.output span {
display: inline-block;
background: #DDD;
padding: 5px;
margin: 5px;
width: 20px;
height: 20px;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="output"></div>
<button>Run</button>
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() );
}