Skip to content

Instantly share code, notes, and snippets.

@tbennett
Created March 30, 2022 22:56
Show Gist options
  • Save tbennett/f051e462b0c4d75780c3d51667bca754 to your computer and use it in GitHub Desktop.
Save tbennett/f051e462b0c4d75780c3d51667bca754 to your computer and use it in GitHub Desktop.
// two ways to get a random integer between zero and another (e.g. between 0 and 100)
// method 1
// Math.trunc (new ES6) truncates the floating point, converting the value to an integer.
const maxVal = 100;
const randomInt = Math.trunc(maxVal * Math.random());
// method 2
// the left shift operator (<<)
// Bitwise shifting any
// number x to the left by y bits yields x * 2 ** y.
// So e.g.: 9 << 3 translates to: 9 * (2 ** 3) = 9 * (8) = 72.
const maxVal = 100;
const randomInt = (maxVal * Math.random()) << 0;
// BONUS
//here is something from MDN for random numbers in a range
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1) + min); //The maximum is inclusive and the minimum is inclusive
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment