Random numbers are random. There's no guarantee you won't get the same random number twice. In fact, when you convert the random numbers to a limited range of integers, it's quite likely you will get the same number twice.
You can fix this by copying the array and then each time you get a value from the array, remove it. Let's also break out the code that generates the random index as a separate function; it's handy in other situations too:
// Return a random integer >= 0 and < n
function randomInt( n ) {
return Math.floor( Math.random() * n );
}
var copy = elements.slice();
while( copy.length ) {
var index = randomInt( copy.length );
this.animateSymbol( copy[index] );
copy.splice( index, 1 );
}
And just for fun, here's another way you could code that loop:
var copy = elements.slice();
while( copy.length ) {
var index = randomInt( copy.length );
this.animateSymbol( copy.splice( index, 1 )[0] );
}
Either one does the same thing. I kind of like the step by step approach for clarity, but it can be quite handy that the .splice()
method returns an array of the element(s) you delete.
Here's a version of the code you can paste into the JavaScript console to test:
// Return a random integer >= 0 and < n
function randomInt( n ) {
return Math.floor( Math.random() * n );
}
var elements = [ 'a', 'b', 'c', 'd', 'e' ];
var copy = elements.slice();
while( copy.length ) {
var index = randomInt( copy.length );
console.log( copy.splice( index, 1 )[0] );
}
console.log( 'Done' );
It's also worth a look at Xotic750's answer. It uses the Fisher-Yates shuffle which randomizes an array in place. This would likely be more efficient for a very lengthy array.