Skip to content

Instantly share code, notes, and snippets.

@g-k
Created January 30, 2013 04:49
Show Gist options
  • Save g-k/4670730 to your computer and use it in GitHub Desktop.
Save g-k/4670730 to your computer and use it in GitHub Desktop.
Fisher-Yates or Knuth Shuffle
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