Created
March 8, 2011 01:56
-
-
Save ddgromit/859699 to your computer and use it in GitHub Desktop.
CoffeeScript Implementation of the Fisher-Yates array sorting algorithm
This file contains 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
# Adapted from the javascript implementation at http://sedition.com/perl/javascript-fy.html | |
# Randomizes the order of elements in the passed in array in place. | |
fisherYates = (arr) -> | |
i = arr.length; | |
if i == 0 then return false | |
while --i | |
j = Math.floor(Math.random() * (i+1)) | |
tempi = arr[i] | |
tempj = arr[j] | |
arr[i] = tempj | |
arr[j] = tempi | |
return arr |
sntran
commented
Oct 19, 2011
Even more refactored:
shuffle = (a) ->
for i in [a.length-1..1]
j = Math.floor Math.random() * (i + 1)
[a[i], a[j]] = [a[j], a[i]]
a
Note, the above is probably too refactored, it's slower and creates bigger Javascript. This is the one you wanna go for:
shuffle = (a) ->
i = a.length
while --i > 0
j = ~~(Math.random() * (i + 1))
t = a[j]
a[j] = a[i]
a[i] = t
a
Now on NPM (as js): https://github.com/coolaj86/knuth-shuffle
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment