Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

输出长度为5且内容不重复的数组 #1

Open
MY729 opened this issue Jul 18, 2019 · 0 comments
Open

输出长度为5且内容不重复的数组 #1

MY729 opened this issue Jul 18, 2019 · 0 comments

Comments

@MY729
Copy link
Owner

MY729 commented Jul 18, 2019

题目来源

题目

这道题目将考点拆分成4点,要求用递归算法实现,限制15行代码以内,限制时间10分钟

  1. 创建一个长度为5的空数组arr
  2. 生成一个2 ~ 32之间的随机整数 rand
  3. 把随机数rand插入到数组arr内,如果数组arr内已存在与rand相同的数字,则重新生成随机数rand并插入arr内【使用递归实现,不能使用for/while循环】
  4. 最终输出一个长度为5,且内容不重复的数组arr

分析

获取min ~ max 范围内的随机数

Math.floor(Math.random() * (max - min + 1) + min)

思路

  1. 给定一个变量 i,初始值为 0, 用来遍历初始化生成的空数组
  2. 当 i 小于数组长度,用 i 一直遍历数组并给arr[i]赋值生成的随机数,直到遍历完数组才返回arr的值
  3. 在第二步中,给arr[i]赋值时,如果数组中不存在生成的随机数,则给其赋值,并i++,否则循环调用该函数

答案

let arr = new Array(5)
let printArr = (arr, i = 0) => {
  let rand = Math.floor(Math.random() * 31 + 2)
  if (i < arr.length) {
    if (!arr.includes(rand)) {
      arr[i++] = rand
    }
    printArr(arr, i)
  }
  return arr
}

执行结果:

printArr(arr) // 调用
// 输出,每次执行输出结果都不一样
[27, 10, 26, 16, 2]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant