Created
March 15, 2012 11:36
-
-
Save nikcorg/2043791 to your computer and use it in GitHub Desktop.
Fisher-Yates shuffle in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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