Skip to content
Create a gist now

Instantly share code, notes, and snippets.

Embed URL


Subversion checkout URL

You can clone with
Download ZIP
CoffeeScript Implementation of the Fisher-Yates array sorting algorithm
# Adapted from the javascript implementation at
# 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]]

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.