Skip to content

Instantly share code, notes, and snippets.

@HiroAgustin
Created March 5, 2018 17:21
Show Gist options
  • Save HiroAgustin/584c4b855678bc285898300c309ff24e to your computer and use it in GitHub Desktop.
Save HiroAgustin/584c4b855678bc285898300c309ff24e to your computer and use it in GitHub Desktop.
function shuffle (array) {
let remaining = array.length
// While there remain elements to shuffle.
while (remaining) {
// Pick a remaining index.
let index = Math.floor(Math.random() * remaining--)
// And swap it with the current element.
let item = array[remaining]
array[remaining] = array[index]
array[index] = item
}
return array
}
@HiroAgustin
Copy link
Author

HiroAgustin commented Dec 13, 2018

Better? Worse? IDK, definitely messier.

function swap(array, a, b, item = array[b]) {
  array[b] = array[a]
  array[a] = item
}

function shuffle (array, remaining = array.length) {
  while (remaining)
    swap(array, Math.floor(Math.random() * remaining--), remaining)
  return array
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment