Skip to content

Instantly share code, notes, and snippets.

@rusco
Created November 27, 2023 13:16
Show Gist options
  • Save rusco/7f9aafba86bf4dd89dfa8214c61f829e to your computer and use it in GitHub Desktop.
Save rusco/7f9aafba86bf4dd89dfa8214c61f829e to your computer and use it in GitHub Desktop.
use random numbers from 1 to 6 (dice) to simulate normal distribution in js, only for educational purposes
//purpose: use random numbers from 1 to 6 (dice) to simulate normal distribution in js, only for educational purposes
//author: jr
//date: 27.11.2023
const min = 1, max = 6;
let getRand = (countRand = 1) => {
let sumRand = 0;
for (let i = 0; i < countRand; i++)
sumRand += Math.floor(Math.random() * (max - min + 1)) + min;
let rand = Math.round(sumRand / countRand);
return rand;
}
//begin map1
{
let map = new Map();
for (let i = 0; i < 1_000_000; i++) { //oneLoop
//only 1 random number:
let rand = getRand(1);
let gotVal = map.get(rand) ?? 0;
let newVal = gotVal + 1;
map.set(rand, newVal);
}
let sum = [...map.values()].reduce((a, b) => a + b);
let map2 = new Map([...map.entries()].sort());
for (let [k, v] of map2) {
console.log("map1: ", k, " ", (v / sum * 100).toFixed(2))
}
console.log("-------------------------------------------------------------------------");
}
//begin map2
{
let map = new Map();
for (let i = 0; i < 1_000_000; i++) {
let rand = getRand(5); //increment 5 to other values: 8, 12, 15, 20 ...
let gotVal = map.get(rand) ?? 0;
let newVal = gotVal + 1;
map.set(rand, newVal);
}
let sum = [...map.values()].reduce((a, b) => a + b);
let map2 = new Map([...map.entries()].sort());
for (let [k, v] of map2) {
console.log("map2: ", k, " ", (v / sum * 100).toFixed(2))
}
console.log("-------------------------------------------------------------------------");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment