Skip to content

Instantly share code, notes, and snippets.

@gabefinch
Created April 22, 2021 05:14
Show Gist options
  • Save gabefinch/22c64bea707ed899e8aef44ada27b4ec to your computer and use it in GitHub Desktop.
Save gabefinch/22c64bea707ed899e8aef44ada27b4ec to your computer and use it in GitHub Desktop.
Fisher–Yates shuffle
// 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