Created
August 30, 2013 00:04
-
-
Save danilobellini/6384872 to your computer and use it in GitHub Desktop.
Fisher–Yates Shuffle algorithm
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
| # | |
| # Fisher–Yates Shuffle algorithm | |
| # | |
| # Implementation by Danilo J. S. Bellini | |
| randInt = (k) -> # From 0 to k (i.e., sample space has k + 1 values) | |
| Math.round Math.random() * k | |
| shuffle = (data) -> | |
| for idx in [data.length-1..1] | |
| rnd = randInt idx | |
| [data[idx], data[rnd]] = [data[rnd], data[idx]] | |
| return data | |
| # An example | |
| console.log shuffle [0..5] | |
| # In the shell: | |
| # coffee shuffle.coffee | |
| # [ 3, 0, 4, 1, 5, 2 ] | |
| # | |
| # (Obviously the number ordering may vary...) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment