Skip to content

Instantly share code, notes, and snippets.

@danilobellini
Created August 30, 2013 00:04
Show Gist options
  • Select an option

  • Save danilobellini/6384872 to your computer and use it in GitHub Desktop.

Select an option

Save danilobellini/6384872 to your computer and use it in GitHub Desktop.
Fisher–Yates Shuffle algorithm
#
# Fisher–Yates Shuffle algorithm
#
# Implementation by Danilo J. S. Bellini
randInt = (k) -> # From 0 to k (i.e., sample space has k + 1 values)
Math.round Math.random() * k
shuffle = (data) ->
for idx in [data.length-1..1]
rnd = randInt idx
[data[idx], data[rnd]] = [data[rnd], data[idx]]
return data
# An example
console.log shuffle [0..5]
# In the shell:
# coffee shuffle.coffee
# [ 3, 0, 4, 1, 5, 2 ]
#
# (Obviously the number ordering may vary...)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment