Skip to content

Instantly share code, notes, and snippets.

@Hlight
Created February 15, 2019 06:28
Show Gist options
  • Select an option

  • Save Hlight/45eab932c72ca0aef156bad446edddec to your computer and use it in GitHub Desktop.

Select an option

Save Hlight/45eab932c72ca0aef156bad446edddec to your computer and use it in GitHub Desktop.
Function that returns a random integer between min and max. Both inclusive and exclusive options.
// Generate random numbers
// https://stackoverflow.com/a/1527820
/**
* Returns a random number between min (inclusive) and max (exclusive)
*/
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
/**
* Returns a random integer between min (inclusive) and max (inclusive).
* The value is no lower than min (or the next integer greater than min
* if min isn't an integer) and no greater than max (or the next integer
* lower than max if max isn't an integer).
* Using Math.round() will give you a non-uniform distribution!
*/
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(getRandomInt(1,7))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment