Hone logo
Hone
Problems

Generating Random Integers Within a Specified Range

This challenge focuses on a fundamental programming task: generating a random integer that falls within a given inclusive range. This skill is crucial for simulations, games, data generation, and many other applications where unpredictable yet controlled numerical output is needed.

Problem Description

Your task is to create a JavaScript function that accepts two integer arguments, min and max, and returns a random integer that is greater than or equal to min and less than or equal to max.

Requirements:

  • The function should be named getRandomIntInRange.
  • It must accept two integer parameters: min and max.
  • The returned value must be an integer.
  • The returned integer must be within the inclusive range [min, max]. This means both min and max are valid possible outputs.
  • The function should handle cases where min is greater than max.

Expected Behavior:

When getRandomIntInRange(min, max) is called, it should produce a random integer x such that min <= x <= max. Each integer within this range should have an equal probability of being generated over many calls.

Edge Cases to Consider:

  • min and max are equal.
  • min is greater than max.

Examples

Example 1:

Input: min = 1, max = 10
Output: A random integer between 1 and 10 (inclusive). For example, 5.
Explanation: The function should return any integer from 1 to 10.

Example 2:

Input: min = -5, max = 5
Output: A random integer between -5 and 5 (inclusive). For example, -2.
Explanation: The function should be able to handle negative numbers.

Example 3:

Input: min = 7, max = 7
Output: 7
Explanation: When min and max are the same, the function should always return that value.

Example 4:

Input: min = 10, max = 1
Output: A random integer between 1 and 10 (inclusive). For example, 3.
Explanation: If min is greater than max, the function should still generate a random integer within the absolute range defined by these two numbers, effectively swapping them internally.

Constraints

  • min and max will be integers.
  • The absolute difference between min and max will not exceed Number.MAX_SAFE_INTEGER.
  • The function should be reasonably efficient and not introduce significant overhead.

Notes

  • JavaScript's built-in Math.random() function generates a floating-point number between 0 (inclusive) and 1 (exclusive). You'll need to leverage this along with mathematical operations to scale and shift the output to fit your desired integer range.
  • Consider how to handle the case where min is greater than max. You could either throw an error, swap the values internally, or define a specific behavior. The examples suggest swapping them internally.
  • Ensure that the max value is inclusive in the output.
Loading editor...
javascript