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

📅 发布于 2026年3月 | 👤 作者:博主 | 🏷️ 标签:递归算法, 随机数, 数组去重, Set, JavaScript, Web开发, 前端, 面试

欢迎来到我的博客文章!所有文章都是满满的前端干货,文章简明扼要。

❌ 错误方案(不能保证不重复)

<script>
// ❌ 不能保证不重复
let arr = Array.from({length:5}, () => Math.floor(Math.random()*31) + 2)
</script>

问题:这种方法生成5个随机数,但无法保证它们不重复。

✅ 正确、简洁、现代方案(推荐)

使用 Set 数据结构自动去重,简洁高效。

<script>
function getRandomUniqueArray(count, min = 2, max = 32) {
  const set = new Set();
  while (set.size < count) {
    const num = Math.floor(Math.random() * (max - min + 1)) + min;
    set.add(num);
  }
  return Array.from(set); // 或 [...set]
}

const arr = getRandomUniqueArray(5);
console.log(arr);
</script>

优点:

✅ 递归实现方案

使用递归算法实现不重复的随机数数组。

<script>
let arr = [];
let random;

function getRandom() {
  random = Math.floor(Math.random() * 31) + 2; // ✅ [2, 32]
  
  if (arr.indexOf(random) === -1) {
    arr.push(random);
  }
  
  if (arr.length < 5) {
    getRandom();
  }
}

getRandom();
console.log(arr);
</script>

递归方案特点:

方案对比

Set 方案 vs 递归方案

Set 方案优势:

递归方案优势:

核心知识点

1. 随机数生成

// 生成 [min, max] 范围的随机整数
Math.floor(Math.random() * (max - min + 1)) + min

// 示例:[2, 32]
Math.floor(Math.random() * 31) + 2

2. Set 去重

const set = new Set();
set.add(1);
set.add(2);
set.add(1); // 重复值不会被添加
console.log(set.size); // 2

// 转换为数组
const arr = Array.from(set); // 或 [...set]

3. 递归终止条件

function getRandom() {
  // ... 处理逻辑
  
  if (arr.length < 5) {
    getRandom(); // 递归调用
  }
  // arr.length === 5 时自动停止
}

面试要点

注意事项:

核心总结

← 返回首页