Generate N Random Numbers Between a Range & Pick the Greatest in JavaScript
Given n random numbers between a range, our task is to pick the greatest number and print it using JavaScript.
Example:
Input: arr[] = {4, 6, 8, -5, -4, 4}
Output: 8
Explanation: Maximum number is 8
Table of Content
- Using a loop
- Using Array methods
- Using reduce Method
Using a loop
In this approach, we use a loop to iteratively generate random numbers, and also while iterating it keeps track of the maximum number encountered so far and prints it.
Example: Implementation of a program to generate n random numbers between a range and pick the greatest using array methods
function genAndFindMax(n, min, max) {
let maxNum = Number.MIN_SAFE_INTEGER;
for (let i = 0; i < n; i++) {
let randNum = Math.floor(Math.random() * (max - min + 1)) + min;
maxNum = Math.max(maxNum, randNum);
}
return maxNum;
}
const n = 10;
const min = 1;
const max = 100;
console.log("Max Number:", genAndFindMax(n, min, max));
Output
Max Number: 100
Time Complexity: O(n)
Auxiliary Space: O(1)
Using Array methods
In this approach we use JavaScript’s Array methods to generate random numbers and find the maximum using spread operator and Math.max.
Example: Implementation of program to generate n random numbers between a range and pick the greatest using array methods
function genAndFindMax(n, min, max) {
const randomNums = Array.from({ length: n }, () =>
Math.floor(Math.random() * (max - min + 1)) + min);
return Math.max(...randomNums);
}
const n = 10;
const min = 1;
const max = 100;
console.log("Max Number:", genAndFindMax(n, min, max));
Output
Max Number: 93
Time Complexity: O(n)
Auxiliary Space: O(n)
Using reduce Method
In this approach, we use JavaScript’s Array.from method to generate an array of random numbers and then use the reduce method to find the maximum number.
Example: Implementation of a program to generate n random numbers between a range and pick the greatest using the reduce method
function genAndFindMax(n, min, max) {
const randomNums = Array.from({ length: n }, () =>
Math.floor(Math.random() * (max - min + 1)) + min);
return randomNums.reduce((maxNum, currentNum) =>
Math.max(maxNum, currentNum), Number.MIN_SAFE_INTEGER);
}
const n = 10;
const min = 1;
const max = 100;
console.log("Max Number:", genAndFindMax(n, min, max));
Output
Max Number: 95
Contact Us