Skip to content

Instantly share code, notes, and snippets.

@kleytonmr
Last active January 13, 2023 15:49
Show Gist options
  • Save kleytonmr/6bdac120026e68690be8a7516c8c0dd4 to your computer and use it in GitHub Desktop.
Save kleytonmr/6bdac120026e68690be8a7516c8c0dd4 to your computer and use it in GitHub Desktop.
Get random int excluding existing numbers
/**
* Returns a random integer between min (inclusive) and max (inclusive).
* Pass all values as an array, as 3rd argument which values shouldn't be generated by the function.
* 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) {
const minimum = Math.ceil(min);
const maximum = Math.floor(max);
return Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
}
// How to use this code?
// getRandomIntExcludingExistingNumbers(1, 5, [1])
function getRandomIntExcludingExistingNumbers(min, max, excludeArrayNumbers) {
let randomNumber;
if(!Array.isArray(excludeArrayNumbers)) {
randomNumber = getRandomInt(min, max);
return randomNumber;
}
do {
randomNumber = getRandomInt(min, max);
} while ((excludeArrayNumbers || []).includes(randomNumber));
return randomNumber;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment