Skip to content

Instantly share code, notes, and snippets.

@ddgromit
Created March 8, 2011 01:56
Show Gist options
  • Save ddgromit/859699 to your computer and use it in GitHub Desktop.
Save ddgromit/859699 to your computer and use it in GitHub Desktop.
CoffeeScript Implementation of the Fisher-Yates array sorting algorithm
# 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
Copy link

sntran commented Oct 19, 2011

# 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

@d8uv
Copy link

d8uv commented Feb 27, 2013

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

@coolaj86
Copy link

coolaj86 commented Dec 3, 2013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment