Skip to content

Instantly share code, notes, and snippets.

@nikcorg
Created March 15, 2012 11:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nikcorg/2043791 to your computer and use it in GitHub Desktop.
Save nikcorg/2043791 to your computer and use it in GitHub Desktop.
Fisher-Yates shuffle in JavaScript
var n = 100,
data = (function (l, r, i) { for (i = 0; i < l; r.push(i++)); return r;}(n, []));
// http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
function shuffle(arr) {
var i, n = arr.length, p;
for (i = n - 1; i > 0; i--) {
p = Math.floor(Math.random() * i);
arr.splice(i, 1, arr.splice(p, 1, arr[i]).pop());
}
return arr;
}
console.log(shuffle(data));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment