Skip to content

Instantly share code, notes, and snippets.

@vvgomes
Last active March 26, 2021 19:55
Show Gist options
  • Save vvgomes/5067c23b820c05ee4263ed079fc14c51 to your computer and use it in GitHub Desktop.
Save vvgomes/5067c23b820c05ee4263ed079fc14c51 to your computer and use it in GitHub Desktop.
/*
Monte Carlo Simulation for 🎲 🎲
Example output for 1,000,000 simulations
2: ⬜⬜⬜
3: ⬜⬜⬜⬜⬜
4: ⬜⬜⬜⬜⬜⬜⬜
5: ⬜⬜⬜⬜⬜⬜⬜⬜⬜
6: ⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜
7: ⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜
8: ⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜⬜
9: ⬜⬜⬜⬜⬜⬜⬜⬜⬜
10: ⬜⬜⬜⬜⬜⬜⬜
11: ⬜⬜⬜⬜⬜
12: ⬜⬜⬜
*/
const { range, curry, inc, times, compose, toPairs } = require("ramda");
const { random, floor, ceil, min, max } = Math;
const { assign, values, keys } = Object;
const generateRandom = (minOutput, maxOutput) =>
floor(random() * (maxOutput - minOutput + 1) + minOutput);
const initHistogram = (minOutput, maxOutput) =>
range(minOutput, maxOutput + 1).reduce(initHistogramEntry, {});
const initHistogramEntry = (histogram, possibleOutput) =>
assign(histogram, { [possibleOutput]: 0 });
const computeResult = curry((histogram, result) =>
assign(histogram, { [result]: inc(histogram[result]) }));
const runRound = (histogram, generator) =>
compose(computeResult(histogram), generator);
const simulate = (minOutput, maxOutput, numOfRuns, generator) => {
const histogram = initHistogram(minOutput, maxOutput);
times(runRound(histogram, generator), numOfRuns);
return histogram;
}
const plotRow = curry((bucketSize, entry) => {
const bucket = ceil(entry[1] / bucketSize);
const formattedVal = Array(bucket).fill("⬜", 0).join("");
const formattedKey = entry[0].padStart(2, " ");
return [formattedKey, formattedVal].join(": ");
});
const plot = (histogram) => {
const frequencies = values(histogram);
const leastLikely = min(...frequencies);
const mostLikely = max(...frequencies);
const bucketSize = ceil((mostLikely - leastLikely) / frequencies.length);
return toPairs(histogram).map(plotRow(bucketSize)).join("\n");
}
// run dices example
const minOutput = 2;
const maxOutput = 12;
const numOfRuns = 100000;
const rollDices = () => generateRandom(1, 6) + generateRandom(1, 6);
const histogram = simulate(minOutput, maxOutput, numOfRuns, rollDices);
console.log(plot(histogram));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment