Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save todd-a-jacobs/959306 to your computer and use it in GitHub Desktop.
Save todd-a-jacobs/959306 to your computer and use it in GitHub Desktop.
durstenfeld array shuffle in coffeescript
# See http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm
# written as one-liners because my REPL didn't like multiline functions this morning
# tested on CoffeeScript v1.0.1
input = [0 .. 7]
swap = (input, x, y) -> [input[x], input[y]] = [input[y], input[x]]
rand = (x) -> Math.floor(Math.random() * x)
durst = (input) -> swap(input, i, rand(i)) for i in [input.length - 1 .. 1]
"""
coffee> input
0,1,2,3,4,5,6,7
coffee> durst input
4,7,1,6,0,5,3,7,2,7,6,7,5,7
coffee> input
7,5,6,2,3,0,1,4
coffee>
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment