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

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

Open
Easay opened this issue Apr 1, 2021 · 0 comments
Labels

Comments

@Easay
Copy link
Owner

Easay commented Apr 1, 2021

题目描述

a) 生成一个长度为5的空数组arr。
b) 生成一个(2-32)之间的随机整数rand。
c) 把随机数rand插入到数组arr内,如果数组arr内已存在与rand相同的数字,则重新生成随机数rand并插入到arr内[需要使用递归实现,不能使用for/while等循环]
d) 最终输出一个长度为5,且内容不重复的数组arr。

题目解答

function getRand(arr){
    if(arr.length==5) return arr;
    var randNum = Math.floor(Math.random()*31)+2; //2-32
    if(arr.indexOf(randNum)==-1){
        arr.push(randNum);
        return getRand(arr.slice());
    }else{
        return  getRand(arr.slice());
    }
}
console.log(getRand([]));

补充

JS中生成随机数:
Math.random() ; // 生成[0,1)的随机数,结果不是整数
Math.random()*31; //生成[0,31)的随机数
Math.floor(Math.random()*31); // 生成[0,31)的随机整数
Math.floor(Math.random()*31)+2; //生成[2,33)的随机整数,即[2,32]

@Easay Easay added the JS label Apr 1, 2021
@Easay Easay changed the title 题2.用递归算法实现,数组长度为5且元素的随机数在2-32间不重复的值 【JS】题2.用递归算法实现,数组长度为5且元素的随机数在2-32间不重复的值 Apr 1, 2021
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

1 participant