Skip to content

Instantly share code, notes, and snippets.

@WillsonSmith
Created May 26, 2013 17:37
Show Gist options
  • Save WillsonSmith/5653463 to your computer and use it in GitHub Desktop.
Save WillsonSmith/5653463 to your computer and use it in GitHub Desktop.
Fisher-Yates shuffle algorithm.
/*
* Add a shuffle function to Array object prototype
* Usage :
* var tmpArray = ["a", "b", "c", "d", "e"];
* tmpArray.shuffle();
*/
Array.prototype.shuffle = function (){
var i = this.length, j, temp;
if ( i == 0 ) return;
while ( --i ) {
j = Math.floor( Math.random() * ( i + 1 ) );
temp = this[i];
this[i] = this[j];
this[j] = temp;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment