How to shuffle a List (or Array) in Javascript

[javascript]
/**
* Returns number starting from offset up to n-1
*/
function getRandomWithOffset(n,offset) {
return Math.floor(Math.random()*n+offset);
}

/**
* Returns random integer from 0 to n-1
*/
function getRandom(n) {
return getRandomWithOffset(n,0);
}

/** Fisher–Yates shuffle algorithm O(n) */
function shuffleList(list) {
for (var i=list.length-1; i>0; i–) {
var j = getRandom(i+1);
var buffer = list[i];
list[i]=list[j];
list[j]=buffer;
}
}

/** Usage example:
var myList = [1,2,3,4,5,6,7,8,9];
shuffleList(myList); //after this the list has been shuffled.
*/
[/javascript]

Note: This is a simple linear algorithm to shuffle. If you need to do some serious shuffling, say you’re creating a poker game or something where it’s crucial where nobody can predict the order of the cards DO NOT USE this algorithm, go for something more complex.

Leave a Reply

Your email address will not be published. Required fields are marked *