Skip to content

Instantly share code, notes, and snippets.

@matthieuprat
Last active June 13, 2018 06:58
Show Gist options
  • Select an option

  • Save matthieuprat/2423c3c501dad6d50803 to your computer and use it in GitHub Desktop.

Select an option

Save matthieuprat/2423c3c501dad6d50803 to your computer and use it in GitHub Desktop.
Shuffle a JavaScript array
const shuffle = arr =>
arr.reduce((arr, elt) => {
arr.splice(~~(Math.random() * (arr.length + 1)), 0, elt)
return arr
}, [])
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.
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