public
Last active

CoffeeScript Implementation of the Fisher-Yates array sorting algorithm

  • Download Gist
fisheryates.coffee
CoffeeScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# 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
# Refactored for swapping
fisherYates = (arr) ->
    i = arr.length
    if i is 0 then return false

    while --i
        j = Math.floor(Math.random() * (i+1))
        [arr[i], arr[j]] = [arr[j], arr[i]] # use pattern matching to swap

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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.