Created
November 14, 2012 10:12
-
-
Save jonelf/4071349 to your computer and use it in GitHub Desktop.
Sort by random vs. Fisher-Yates shuffle
This file contains hidden or 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
| 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 |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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