Hone logo
Hone
Problems

Generate a Random Number Within a Specified Range in JavaScript

Generating random numbers is a fundamental task in programming, often used for simulations, games, and data sampling. This challenge asks you to write a JavaScript function that generates a random integer within a given range (inclusive of both the start and end values). This is a crucial skill for many programming applications.

Problem Description

You need to create a JavaScript function called getRandomNumber that accepts two arguments: min and max. The function should return a random integer that falls within the range defined by min and max, inclusive. The function should handle cases where min is equal to max correctly.

Key Requirements:

  • The function must return an integer.
  • The returned number must be greater than or equal to min.
  • The returned number must be less than or equal to max.
  • The function should work correctly regardless of whether min is greater than or less than max.

Expected Behavior:

The function should produce a different random integer each time it is called, within the specified range.

Edge Cases to Consider:

  • min and max are equal.
  • min and max are negative.
  • min and max are zero.
  • Large values for min and max (consider potential integer overflow, though this is less of a concern in JavaScript).

Examples

Example 1:

Input: min = 1, max = 5
Output: 3 (or any integer between 1 and 5, inclusive)
Explanation: The function should return a random integer between 1 and 5.

Example 2:

Input: min = -3, max = 3
Output: 0 (or any integer between -3 and 3, inclusive)
Explanation: The function should return a random integer between -3 and 3.

Example 3:

Input: min = 10, max = 10
Output: 10
Explanation: If min and max are the same, the function should return that value.

Constraints

  • min and max will be integers.
  • min and max will be within the safe integer range of JavaScript (approximately -2<sup>53</sup> to 2<sup>53</sup> - 1).
  • The function should execute efficiently for typical ranges of min and max.

Notes

Consider using Math.random() and Math.floor() to achieve the desired result. Remember that Math.random() returns a floating-point number between 0 (inclusive) and 1 (exclusive). Think about how to scale and shift this value to fit your desired range. The order of min and max doesn't matter; your function should handle either case.

Loading editor...
javascript