Created
January 30, 2013 04:49
-
-
Save g-k/4670730 to your computer and use it in GitHub Desktop.
Fisher-Yates or Knuth Shuffle
This file contains hidden or 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 swap = function (list, i, j) { | |
// swap items at i-th and j-th entries of list | |
// console.log(swap(items, 0, 2)); == [3, 2, 1, 4, 5] | |
var tmp = list[i]; | |
list[i] = list[j]; | |
list[j] = tmp; | |
return list; | |
}; | |
var randomInt = function(max) { | |
// Return a random integer between zero and max | |
return Math.floor(Math.random() * max); | |
}; | |
var shuffle = function (items) { | |
var length = items.length; | |
var i = items.length; | |
while (--i) { | |
// Swap last unshuffled element at index i | |
// with a random element from the unshuffled section (up to i-1) | |
swap(items, i, randomInt(i-1)); | |
} | |
return items; | |
}; | |
var items = [1, 2, 3, 4, 5]; | |
for (var i = 0; i < 10; i++) { | |
console.log(shuffle(items)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment