Last active
March 17, 2022 22:52
-
-
Save ironstrider/b120d78550444df57af77bfc6f123c12 to your computer and use it in GitHub Desktop.
Implementation of Fisher-Yates in Javascript to shuffle an array
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
function fisherYates(array) { | |
let i = array.length; | |
let temp, j; | |
while(i) { | |
j = (Math.random() * i--) | 0; // x | 0 gives floor(x) | |
// swap elements i & j | |
temp = array[i]; | |
array[i] = array[j]; | |
array[j] = temp; | |
} | |
} | |
// A note on the implementation: | |
// Although we want to start with the last element of the array (i.e. | |
// i = array.length - 1), by starting with i = array.length (not | |
// minus 1), we can randomly generate j without the need to perform an | |
// addition, thus saving an operation | |
function fisherYatesAlternative(array) { | |
let temp, j; | |
for (let i = array.length - 1; i >= 0; i--) { | |
j = Math.floor(Math.random() * i + 1); | |
// swap elements i & j | |
temp = array[i]; | |
array[i] = array[j]; | |
array[j] = temp; | |
} | |
} | |
nums = [1,2,3,4,5,6,7] | |
fisherYates(nums); | |
console.log(nums) | |
fisherYatesAlternative(nums); | |
console.log(nums) | |
// See: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment