Created
April 22, 2021 05:14
Fisher–Yates shuffle
This file contains 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
// Great explanation https://bost.ocks.org/mike/shuffle/ | |
// This relies on mutation. Could the algorithm be recreated using immutable data? | |
function shuffle(array) { | |
var count = array.length | |
while (count) { | |
const current = count - 1 | |
// exchange current card with a random card below the current card | |
swapIndices(array, current, Math.floor(Math.random() * current)) | |
// decrement count | |
count = count - 1 | |
} | |
return array; | |
} | |
function swapIndices(array, i, j) { | |
const t = array[i] | |
array[i] = array[j] | |
array[j] = t | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment