Created
January 11, 2019 05:03
-
-
Save brandonjyee/bfcb31025f005ac6449f3a0ee8028dbe to your computer and use it in GitHub Desktop.
Fisher-Yates Shuffle Algorithm
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
/** | |
* 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