function generateRandomArray(length, min, max) {
if (max - min + 1 < length) {
throw new Error("Range is too small to generate an array without duplicates.");
}
function recursiveHelper(arr) {
if (arr.length === length) {
return arr;
}
let num = Math.floor(Math.random() * (max - min + 1)) + min;
if (arr.includes(num)) {
return recursiveHelper(arr); // Try again if duplicate
} else {
return recursiveHelper([...arr, num]); // Add unique number
}
}
return recursiveHelper([]);
}
const arr = generateRandomArray(5, 2, 32);
console.log(arr);
Explanation and Improvements:
-
Error Handling: The code now includes a check to ensure that the range between
min
andmax
is large enough to generate an array of the specifiedlength
without duplicates. This prevents infinite recursion. -
Recursive Helper Function: The
recursiveHelper
function is the core of the recursive logic. It takes the partially built arrayarr
as an argument. -
Base Case: If
arr.length
equals the desiredlength
, the function returns the completed array. -
Recursive Step:
- It generates a random number
num
within the specified range. - It checks if
num
is already present inarr
usingarr.includes(num)
. - If
num
is a duplicate, the function calls itself (recursiveHelper(arr)
) to try again. This is the key recursive step. - If
num
is unique, it addsnum
to the array using the spread syntax ([...arr, num]
) and calls itself with the new, extended array.
- It generates a random number
-
Initial Call: The
generateRandomArray
function initiates the process by callingrecursiveHelper([])
with an empty array.
Why this is better than a loop-based approach (for this specific problem):
While a loop-based solution is often more efficient for generating random arrays without duplicates, the recursive approach is a good exercise in understanding recursion. It clearly demonstrates the base case and recursive step concepts. In real-world scenarios, for larger arrays and ranges, a loop and a Set (for efficient duplicate checking) would be the preferred method.
How to use it in a frontend context:
This code can be directly used in a <script>
tag in your HTML file or within a JavaScript module in a modern frontend framework. The console.log(arr)
will print the generated array to the browser's console. You can then use this arr
in your frontend code as needed (e.g., display it on the page, use it in calculations, etc.).
For example, to display the array on a web page:
<!DOCTYPE html>
<html>
<head>
<title>Random Array</title>
</head>
<body>
<div id="output"></div>
<script>
// ... (the generateRandomArray function from above) ...
const arr = generateRandomArray(5, 2, 32);
document.getElementById("output").textContent = arr.join(", ");
</script>
</body>
</html>
This will display the generated array in the div
with the id "output".