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且元素的随机数在2-32间不重复的值 #1

Open
Ray-56 opened this issue Aug 7, 2019 · 3 comments
Labels

Comments

@Ray-56
Copy link
Owner

Ray-56 commented Aug 7, 2019

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

可以拆解为四小项:

  • 生成一个长度为5的空数组 arr
  • 生成一个(2-32)之间的随机整数 rand
  • 把随机数 rand 插入到数组 arr 内,如果数组 arr 内已存在与 rand 相同的数字,则重新生成随机数 rand 并插入到 arr 内 [需要使用递归实现,不能使用 for/while 等循环]
  • 最终输出一个长度为5,且内容不重复的数组 arr
@Ray-56 Ray-56 added the 算法 label Aug 7, 2019
@Ray-56
Copy link
Owner Author

Ray-56 commented Aug 7, 2019

function getNum() {
    return Math.floor(Math.random() * 32 + 1);
}

function inset(cur, arr = []) {
    if (arr.length > 4) return arr;

    if (!arr.includes(cur)) {
        arr.push(cur);
    }
    return inset(getNum(), arr);
}

var res = inset(getNum());

console.log(res);

@MMmaXingXing
Copy link

MMmaXingXing commented Aug 9, 2019

function getRandom() {
    return Math.floor(Math.random() * 30 + 2);
}

let arryLen = 5;

function getArray(value, arr = []) {
  if (arr.length >= arryLen) return arr;

  if (!arr.includes(value)) {
    arr.push(value);
  }

  return getArray(getRandom(), arr);
}

const arrayVal = getArray(getRandom());
//console.log(arrayVal);

@GenXiaoLe
Copy link
Collaborator

GenXiaoLe commented Aug 9, 2019

function creatArray(arr = []) {
    if (arr.length > 4) return arr;

    var num = Math.floor(Math.random() * 30 + 2);
    if (!arr.includes(num)) {
       arr.push(num);
    }
    return creatArray(arr);
}

var reslut = creatArray();
console.log(reslut);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants