Skip to content

Instantly share code, notes, and snippets.

@fubar
Created October 10, 2019 23:30
Show Gist options
  • Select an option

  • Save fubar/56ecd6d5fa594e686530ca7622e87b8e to your computer and use it in GitHub Desktop.

Select an option

Save fubar/56ecd6d5fa594e686530ca7622e87b8e to your computer and use it in GitHub Desktop.
JS random integer in range (inclusive)
const randomInt = (min, max) => {
const diff = max - min;
const random = Math.floor(Math.random() * (diff + 1));
return min + random;
};
const distribution = {};
[...Array(10000)].forEach(() => {
const random = randomInt(1, 10);
const current = distribution[random] || 0;
distribution[random] = current + 1;
});
console.log(JSON.stringify(distribution, null, 2));
/*
11k iterations for 0..10:
{
"0": 1053,
"1": 1008,
"2": 952,
"3": 1012,
"4": 955,
"5": 1005,
"6": 991,
"7": 1021,
"8": 965,
"9": 1030,
"10": 1008
}
10k iterations for -5..4:
{
"0": 991,
"1": 1055,
"2": 976,
"3": 958,
"4": 969,
"-1": 1059,
"-3": 1017,
"-5": 1017,
"-4": 993,
"-2": 965
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment