Created
May 6, 2011 16:30
-
-
Save dpritchett/959295 to your computer and use it in GitHub Desktop.
durstenfeld array shuffle in coffeescript
This file contains hidden or 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
# 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