Skip to content

Instantly share code, notes, and snippets.

@ValeryToda
Created January 24, 2017 20:30
Show Gist options
  • Save ValeryToda/fbf1de017f91c0ec3da04116c5ccf8b5 to your computer and use it in GitHub Desktop.
Save ValeryToda/fbf1de017f91c0ec3da04116c5ccf8b5 to your computer and use it in GitHub Desktop.
Random Integer generator (Typescript)
/**
* generate a random integer between min and max
* @param {Number} min
* @param {Number} max
* @return {Number} random generated integer
*/
randomInt(min, max){
return Math.floor(Math.random() * (max - min + 1)) + min;
}
@kdbanman
Copy link

For anyone curious, this samples a uniform distribution, and the bounds are inclusive:

var counts = {};
for (var i = 0; i < 100000; i++) {
  var c = randomInt(0, 4);
  counts[c] = (counts[c] == null ? 0 : counts[c]) + 1;
}
// counts == { '0': 20035, '1': 20061, '2': 19882, '3': 20019, '4': 20003 }

@darkhog
Copy link

darkhog commented Dec 1, 2018

Thanks, just what I needed for the game I'm making.

@rodrigograca31
Copy link

rodrigograca31 commented Jul 16, 2020

A better version:
(added types, made a better description)

https://gist.github.com/rodrigograca31/3c6cd8b95b7d7749cac96136211c5d78

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment