用递归算法实现,数组长度为5且元素的随机数在2-32间不重复的值

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:

  1. Error Handling: The code now includes a check to ensure that the range between min and max is large enough to generate an array of the specified length without duplicates. This prevents infinite recursion.

  2. Recursive Helper Function: The recursiveHelper function is the core of the recursive logic. It takes the partially built array arr as an argument.

  3. Base Case: If arr.length equals the desired length, the function returns the completed array.

  4. Recursive Step:

    • It generates a random number num within the specified range.
    • It checks if num is already present in arr using arr.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 adds num to the array using the spread syntax ([...arr, num]) and calls itself with the new, extended array.
  5. Initial Call: The generateRandomArray function initiates the process by calling recursiveHelper([]) 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".

posted @ 2024-11-21 12:08  王铁柱6  阅读(10)  评论(0编辑  收藏  举报