Skip to content

Instantly share code, notes, and snippets.

@CyberSphinxxx
Created January 22, 2025 13:05
Show Gist options
  • Select an option

  • Save CyberSphinxxx/498ea626070c77a78e07bb542904a72e to your computer and use it in GitHub Desktop.

Select an option

Save CyberSphinxxx/498ea626070c77a78e07bb542904a72e to your computer and use it in GitHub Desktop.
Random Number Generator within a Range

Random Number Generator within a Range

This snippet generates a random integer between a specified minimum and maximum range (inclusive). It uses JavaScript's Math.random() function combined with Math.floor() for the random number generation.

// Define the range
const minNum = 1;
const maxNum = 100;

// Generate a random integer within the range
const answer = Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum;

// Output the random number
console.log(answer);

Explanation

  1. Math.random():

    • Generates a random decimal number between 0 (inclusive) and 1 (exclusive).
  2. Math.random() * (maxNum - minNum + 1):

    • Scales the random decimal to the size of the range.
  3. Math.floor():

    • Rounds down to the nearest whole number, ensuring the result is an integer.
  4. + minNum:

    • Offsets the range to start at minNum.

Example Calculation

If Math.random() generates 0.456, the calculation works as follows:

  1. 0.456 * (100 - 1 + 1) = 45.6
  2. Math.floor(45.6) = 45
  3. 45 + 1 = 46

The result would be: 46.


Use Cases

This logic is helpful for:

  • Random number games.
  • Generating IDs within a specific range.
  • Any functionality requiring a random integer within defined bounds.

Output

After running the code, the generated random number will appear in the console.

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