Skip to content

Instantly share code, notes, and snippets.

@brandonjyee
Created January 11, 2019 05:03
Show Gist options
  • Save brandonjyee/bfcb31025f005ac6449f3a0ee8028dbe to your computer and use it in GitHub Desktop.
Save brandonjyee/bfcb31025f005ac6449f3a0ee8028dbe to your computer and use it in GitHub Desktop.
Fisher-Yates Shuffle Algorithm
/**
* Shuffles array in place. Fisher-Yates algo.
* @param {Array} a items An array containing the items.
*/
const shuffle = function(arr) {
// Start i from the last element and move left. Swap with a random element to the left of i
for (let i = arr.length - 1; i > 0; i--) {
// j is a random element to the left of i
const j = Math.floor(Math.random() * (i + 1));
// Swap elements at i and j
const temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
return arr;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment