Last active
June 13, 2018 06:58
-
-
Save matthieuprat/2423c3c501dad6d50803 to your computer and use it in GitHub Desktop.
Shuffle a JavaScript array
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
| const shuffle = arr => | |
| arr.reduce((arr, elt) => { | |
| arr.splice(~~(Math.random() * (arr.length + 1)), 0, elt) | |
| return arr | |
| }, []) |
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
| const shuffle = arr => | |
| arr.reduce((arr, elt) => { | |
| arr.splice(~~(Math.random() * (arr.length + 1)), 0, elt) | |
| return arr | |
| }, []) | |
| /** | |
| * Calls the supplied function a number of times and computes the distribution | |
| * of return values. | |
| */ | |
| function distrib(fn, iterations) { | |
| iterations = ~~iterations || 1 << 20 | |
| const distrib = new Map() | |
| while (iterations--) { | |
| let r = fn().toString() | |
| distrib.set(r, 1 + distrib.get(r) || 0) | |
| } | |
| // Normalize distrib. | |
| const mag = Math.sqrt([...distrib.values()].reduce((mag, c) => mag + c * c, 0)) | |
| distrib.forEach((val, key) => distrib.set(key, val / mag)) | |
| return distrib | |
| } | |
| distrib(() => shuffle([1, 2, 3])) // Check that `shuffle` is un-biased. |
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
| const shuffle = a => a.reduce((a, e) => (a.splice(Math.random() * (a.length + 1), 0, e), a), []) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment