Created
March 19, 2018 19:32
-
-
Save jmakeig/c74a44b3f6b52cc95849843482fed479 to your computer and use it in GitHub Desktop.
Create arrays of random length, sampled from a specified distribution
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
/** | |
* Generate an array from random length between `min` and `max`, calling `fct` | |
* to populate each item. | |
* | |
* @example Creates an array of random length sampled from a Poisson distribution of timestamp-text pair objects. | |
* several( | |
* () => ({ | |
* timestamp: f.date.recent(), | |
* text: f.lorem.sentence(), | |
* }), | |
* () => poisson(3) | |
* ) | |
* | |
* @param {function} fct - Function to apply to each element | |
* @param {function} dist - Distribution from which to sample, defaults to uniform [0–10] | |
* @return {Array} | |
*/ | |
function several(fct, dist = () => Math.random() * 10) { | |
const rand = dist(); | |
const length = Math.max(Math.floor(rand), 0); | |
// console.log(length); | |
const coll = []; | |
for (let i = 0; i < length; i++) { | |
coll.push(fct()); | |
} | |
return coll; | |
} | |
// https://github.com/robbrit/randgen/blob/master/lib/randgen.js#L21-L49 | |
// Generate normally-distributed random nubmers | |
// Algorithm adapted from: | |
// http://c-faq.com/lib/gaussian.html | |
function normal(mean = 0.0, stdev = 1.0) { | |
var u1, u2, v1, v2, s; | |
if (normal.v2 === undefined) { | |
do { | |
u1 = Math.random(); | |
u2 = Math.random(); | |
v1 = 2 * u1 - 1; | |
v2 = 2 * u2 - 1; | |
s = v1 * v1 + v2 * v2; | |
} while (s === 0 || s >= 1); | |
normal.v2 = v2 * Math.sqrt(-2 * Math.log(s) / s); | |
return stdev * v1 * Math.sqrt(-2 * Math.log(s) / s) + mean; | |
} | |
v2 = normal.v2; | |
normal.v2 = undefined; | |
return stdev * v2 + mean; | |
} | |
// https://github.com/robbrit/randgen/blob/master/lib/randgen.js#L67-L81 | |
function poisson(lambda = 1) { | |
var l = Math.exp(-lambda), | |
k = 0, | |
p = 1.0; | |
do { | |
k++; | |
p *= Math.random(); | |
} while (p > l); | |
return k - 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
can be simplified to