Skip to content

Instantly share code, notes, and snippets.

@jonelf
Created November 14, 2012 10:12
Show Gist options
  • Select an option

  • Save jonelf/4071349 to your computer and use it in GitHub Desktop.

Select an option

Save jonelf/4071349 to your computer and use it in GitHub Desktop.
Sort by random vs. Fisher-Yates shuffle
calculateDistribution = (results) ->
dict = {}
for res in results
prop = res.join('')
if dict.hasOwnProperty(prop) then dict[prop]++ else dict[prop]=1
for key, value of dict
console.log key+":"+value
console.log "Sort by random"
results = []
for i in [0..60000] by 1
arr = ['A', 'B', 'C']
arr.sort ->
0.5 - Math.random()
results.push(arr)
calculateDistribution results
# Fisher-Yates shuffle
console.log "Fisher-Yates shuffle"
fisherYates = (arr) ->
swapFrom = arr.length
if swapFrom == 0 then return false
while --swapFrom
swapTo = Math.floor(Math.random() * (swapFrom+1))
[arr[swapFrom], arr[swapTo]] = [arr[swapTo], arr[swapFrom]]
results = []
for i in [0..60000] by 1
arr = ['A', 'B', 'C']
fisherYates(arr)
results.push(arr)
calculateDistribution results
@jonelf
Copy link
Copy Markdown
Author

jonelf commented Nov 14, 2012

Output example:
Sort by random
BCA:7559
ABC:15217
BAC:14907
CAB:7410
ACB:7484
CBA:7424
Fisher-Yates shuffle
BAC:9960
BCA:10013
ABC:9973
CAB:9924
ACB:10111
CBA:10020

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