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

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

时间:2024-11-21 11:57:23浏览次数:1  
标签:function arr 递归 32 recursiveHelper length num 随机数 array

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".

标签:function,arr,递归,32,recursiveHelper,length,num,随机数,array
From: https://www.cnblogs.com/ai888/p/18560338

相关文章

  • 用递归算法实现,数组长度为5且元素的随机数在2-32间不重复的值
    functiongenerateRandomArray(length,min,max){if(max-min+1<length){thrownewError("Rangeistoosmalltogenerateanarraywithoutduplicates.");}functionrecursiveHelper(arr){if(arr.length===length){......
  • 在 Windows 操作系统中,W32Time 是 Windows 时间服务的配置和管理服务,用于确保系统时间
    在Windows操作系统中,W32Time是Windows时间服务的配置和管理服务,用于确保系统时间与网络时间保持同步。它使用"Windows时间协议"(NTP)或其他协议来校准系统的日期和时间。通过修改注册表项,用户可以配置W32Time服务的行为。你提到的注册表路径为:CopyCodeHKEY_LOCAL_MACHI......
  • STM32F103嵌套向量中断控制器
    一、STM32F103中断介绍1.1什么是中断中断:打断CPU执行正常的程序,转而处理紧急程序,然后返回原暂停的程序继续运行;举例:当你正在写作业时,做到一半又去吃饭,吃完饭后又回来接着原来的作业继续完成。对于单片机来说,中断是指CPU正在处理某个事件A,发生了另一件事件B,请求CPU迅速去处理......
  • 痞子衡嵌入式:利用i.MXRT10xx系列内部DCP引擎计算CRC32值时需注意数据长度对齐
    大家好,我是痞子衡,是正经搞技术的痞子。今天痞子衡给大家介绍的是利用i.MXRT10xx系列内部DCP引擎计算CRC32值时需注意数据长度对齐。MCU开发里常常需要CRC校验来检查数据完整性,CRC校验既可以纯软件实现也可以借助MCU片内外设硬件实现。大部分MCU里通常都会包含一......
  • 2024-2025-1 20241320 《计算机基础与程序设计》第九周学习总结
    2024-2025-120241320《计算机基础与程序设计》第九周学习总结作业信息https://edu.cnblogs.com/campus/besti/2024-2025-1-CFAP|这个作业属于哪个课程|https://www.cnblogs.com/rocedu/p/9577842.html|这个作业要求在哪里|https://www.cnblogs.com/rocedu/p/9577842.html#......
  • STM32(hal库)中HAL_ADC_PollForConversion 是 如何执行的?
    HAL_ADC_PollForConversion 是STM32HAL库中的一个函数,用于轮询(poll)ADC(模数转换器)的转换完成状态。这个函数会阻塞调用它的线程,直到ADC转换完成。以下是该函数的工作原理和执行步骤的详细解释:函数原型c复制代码HAL_StatusTypeDefHAL_ADC_PollForConversion(ADC_HandleT......
  • 递归函数(详细讲解版)
    递归函数就是在函数的定义中使用函数自身的方法。这种函数调用自身的方式可以将一个复杂的问题逐步简化为相同类型的较简单问题。 关键要素 1.终止条件 这是递归函数中最重要的部分。如果没有终止条件,函数会一直调用自身,导致栈溢出(程序运行时栈空间耗尽)。终止条件......
  • STM32 HAL 库硬件 I2C 驱动 MPU6050
    MPU6050简介驱动文件mpu6050.h#ifndefINC_MPU6050_H_#defineINC_MPU6050_H_#include"i2c.h"//I2C通道配置#definehI2C&hi2c2//设备地址配置#defineMPU6050_ADDRESS_Write 0xD0//0x68左移一位补0#defineMPU6050_ADDRESS_Read0xD1//0x68左移一位补1......
  • SQLServer数据库里的递归CTE详细说明
     SQLServer数据库里的递归CTE详细说明  用实例来说明:样例: --解释CTE递归的运算逻辑(代码不一定可用,但逻辑准确)WITHBOM_CTEAS(--基础层(B段):选择特定BOM物料编码的所有BOM条目,并设置层级为1SELECTBOMNOAS'TopBOM',COMPID,REQQTY,1AS......
  • 从0开始linux(32)——进程信号(1)信号发生
    欢迎来到博主的专栏:从0开始linux博主ID:代码小豪文章目录信号信号发生键盘发生的信号信号是如何发送给进程的?信号是如何发送给系统的?其他的信号发生由系统指令发生的信号由系统调用发生的信号由软件条件引发的信号由于进程异常引发的信号Core与Term默认行为的差别......