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] 第1天 用递归算法实现,数组长度为5且元素的随机数在2-32间不重复的值 #3

Open
haizhilin2013 opened this issue Apr 17, 2019 · 459 comments
Labels
js JavaScript

Comments

@haizhilin2013
Copy link
Collaborator

haizhilin2013 commented Apr 17, 2019

这一题是起源题

描述:

  1. 这是一道大题目,把考点拆成了4个小项;需要侯选人用递归算法实现(限制15行代码以内实现;限制时间10分钟内完成):
    a) 生成一个长度为5的空数组arr。
    b) 生成一个(2-32)之间的随机整数rand。
    c) 把随机数rand插入到数组arr内,如果数组arr内已存在与rand相同的数字,则重新生成随机数rand并插入到arr内[需要使用递归实现,不能使用for/while等循环]
    d) 最终输出一个长度为5,且内容不重复的数组arr。
@yxkhaha
Copy link

yxkhaha commented Apr 17, 2019

    var arr = new Array(5);
    var num = randomNumber();
    var i = 0;
    randomArr(arr,num);
    function randomArr(arr,num) {
        if (arr.indexOf(num)< 0){
            arr[i] = num;
            i++;
        } else {
            num = randomNumber();
        }
        if (i>=arr.length){
            console.log(arr);
            return;
        }else{
            randomArr(arr,num)
        }
    }
    function randomNumber() {
        return Math.floor(Math.random()*31 + 2)
    }

@qingleizhang123
Copy link

var arr=new Array(5);
var randomNum=2+Math.floor(Math.random()*30);
var i=0;
function ArrPushItem(arr,randomNum)
{
if(arr.indexOf(randomNum)>-1)
{
randomNum=2+Math.floor(Math.random()*30);
}
else{arr[i]=randomNum;
i++;
randomNum=2+Math.floor(Math.random()*30);}
if(i==arr.length)
{return arr;}
else
{ArrPushItem(arr,randomNum)}
}
ArrPushItem(arr,randomNum)

@haizhilin2013
Copy link
Collaborator Author

点评:
知识点:递归、随机数
难点:1颗星
这道题主要是想考递归的用法,同时顺带考了生成指定范围的随机数方法。
@yxkhaha @qingleizhang123

@haizhilin2013 haizhilin2013 added the js JavaScript label Apr 18, 2019
@qq674785876
Copy link

var arr = []; //数组
var num = 2 + Math.floor(Math.random() * 30); //生成 2-32 内的随机数
var n = 0; //记录数回调次数
var setArr = function(num){ //生成数组长度为5且元素的随机数在2-32间不重复的值
if(arr.length === 5){ //数组长度为5便跳出循环
return console.log(arr);
}
if(arr.every((v) => (v !== num))){ //判断数组中是否没有该值
arr.push(num);
}
n++;
setArr (Math.floor(Math.random()*(31)+2));
}
setArr (num);

@hellojackhui
Copy link

var arr = new Array(5);
var num = Math.floor(Math.random()* (31) + 2);
function numsInterative(num) {
  if (arr.length == 5) {
    console.log(arr);
  }
  if (!arr.includes(num)) {
    arr.push(num)
  }
  numsInterative(Math.floor(Math.random()* (31) + 2))
}
numsInterative(num)

@shulandmimi
Copy link

    var arr = new Array(5),
          len = arr.length;
    function arPush() {
        if( len != 0 ) {
            len --;
            let n = Math.floor((Math.random() * 31) + 2);
            each(n, len) ? (arr[len] = n) : len ++;
            arPush();
        }
    }
    function each(index, i) {
        if( i > arr.length - 1) return true; 
        return arr[i] == index ? false : (each(index,i + 1));
    }
    arPush()

@IronManSuper
Copy link

var arr = new Array(5);
var i= 0;
function randomHandle () {
var num = 2 + Math.floor(Math.random() * 30);
if (arr.indexOf(num) < 0) {
arr[i] = num;
i ++;
}
(i < 5) && randomHandle();
}
randomHandle();

@linghucq1
Copy link

linghucq1 commented May 8, 2019

考虑一下扩展性

function insertArr(arr, i = 0, min = 2, max = 32) {
  const num = Math.max(min, Math.ceil(Math.random() * max))
  if (!arr[arr.length - 1]) {
    if (!arr.includes(num)) { 
      arr[i++] = num
    }
    return insertArr(arr, i) 
  }
  return arr 
}
const arr = new Array(5);
const result = insertArr(arr)

这里的随机数算法是有问题的,具体参见下面 @likeke1997 的答案。另外用四舍五入也是不对的,因为最小值和最大值只有其它值概率的一半。

仔细一看,虽然自定义了最大最小参数,但是递归的时候没有传入,所以并没有卵用。i 参数的初衷是自定义从哪里开始插入,实用性也没有 @likeke1997 的 length 参数来的好。

@Magty
Copy link

Magty commented May 8, 2019

function getUNumber(arr, min, max) {
var rand = Math.floor(Math.random() * (max - 1)) + min;
if (arr.indexOf(rand) === -1) {
return rand;
} else {
return getUNumber(arr, min, max);
}
}

function getRandomArrayByLength(len) {
    if (len === 1) {
        return [getUNumber([], 2, 32)];
    } else {
        var arr = getRandomArrayByLength(len - 1);
        var rand = getUNumber(arr, 2, 32);
        arr.push(rand);
        return arr;
    }
}

var newArray = new Array(5);
console.log(getRandomArrayByLength(newArray.length));

@iCharlesZ
Copy link

iCharlesZ commented May 8, 2019

var arr = new Array(5);
function insertRandom(n) {
  if (n < 0) return
  let tmp = Math.floor(Math.random() * 31 + 2)
  if (arr.indexOf(tmp) !== -1) return insertRandom(n)
  arr[n] = tmp
  return insertRandom(n - 1)
}
insertRandom(arr.length - 1)

@lqwzjay
Copy link

lqwzjay commented May 10, 2019

  function getRandomArr(arr, len,) {
    if (arr.length === len) { return arr }
    let rndNum = Math.floor(Math.random() * (32 - 2 + 1) + 2)
    if (arr.indexOf(rndNum) > -1) return getRandomArr(arr, len)
    else {
      arr.push(rndNum)
      return getRandomArr(arr, len)
    }
  }
  console.log(getRandomArr([], 5))

@Lucas-Lulululu
Copy link

function createArr(arr) {
let res = arr || [];
let num = parseInt(Math.random() * (32 - 2) + 2);
if (!res.includes(num)) res.push(num);
if (res.length < 5) createArr(res)
return res
}
let b = createArr()

@hcxowe
Copy link

hcxowe commented May 10, 2019

function foo(arr) {
	arr = arr || []

	if (arr.length >= 5) {
		return arr
	}

	var n = 2 + Math.floor(Math.random() * 31)

	if (arr.indexOf(n) == -1) {
		arr.push(n)
	}

	return foo(arr)
}

@qianchenY
Copy link

qianchenY commented May 11, 2019

function randomNum(){
    return Math.floor(Math.random() * 32 + 2)
}
function arrFunc(arr, num){
    if(arr.length >= 5) return arr;
    if(!arr.includes(num)){
	arr.push(num);
    }
    return arrFunc(arr, randomNum())
}
arrFunc(arr, randomNum())

@ouyinheng
Copy link

ouyinheng commented May 14, 2019

function setArr(arr) {
      if(arr.length==5) return;
      const num = parseInt((Math.random())*31+2);
      if(arr.indexOf(num) === -1) arr.push(num)
      return setArr(arr);
}

@tzjoke
Copy link

tzjoke commented May 16, 2019

function buildArray(arr, length, min, max) {
    if (!Array.isArray(arr)) arr = []
    if (length < 1) return []
    if (arr.length === length) return arr
    const random = Math.random() * (+max - +min) + +min
    if (!arr.includes(random)) arr.push(random)
    return buildArray(arr, length, min, max)
}

buildArray([], 5, 2, 32)

@hbxywdk
Copy link

hbxywdk commented May 17, 2019

function createArray(len, minNum, maxNum) {
  var createRandom = (min, max) => { return (Math.round((max - min) * Math.random()) + min)};
  var arr = new Array(len), count = 0;
  function run() {
    var num = createRandom(minNum, maxNum);
    (!arr.includes(num)) && (arr[count] = num, count++);
    (count < len) && (run());
  }
  run(); return arr;
}
console.log(createArray(5, 2, 32));

@readream
Copy link

readream commented May 19, 2019

var arr = []
var num 
console.log(num)
function newArr(arr, num) {
  if (arr.length >= 5) {
    return
  } else {
    num = Math.floor(Math.random() * 30) + 2
    return arr.push(num) + newArr(arr, num)
  }
}
newArr(arr, num)
console.log(arr)

@ghost
Copy link

ghost commented May 23, 2019

function returnRandomArr(max, min, length, arr = []) {
  arr.push(Math.floor(Math.random() * (max - min)) + min);
  arr = Array.from(new Set(arr))
  return arr.length < length ? returnRandomArr(max, min, length, arr) : arr
}
let arr = returnRandomArr(32, 2, 5)
console.log(arr)

@yangchunboy
Copy link

const arr = []
const getRandom = () => {
	const num = parseInt(Math.random() * 100, 10) + 2
	if (arr.length >= 5) return arr
	if (num <= 32 && arr.indexOf(num) === -1){
		arr.push(num)
		getRandom()
	} else {
		getRandom()
	}
}
getRandom()
console.log(arr)

@yangchunboy
Copy link

const arr = []
const getRandom = () => {
	const num = parseInt(Math.random() * 100, 10) + 2
	if (arr.length >= 5) return arr
	if (num <= 32 && arr.indexOf(num) === -1){
		arr.push(num)
	}
	getRandom()
}
getRandom()
console.log(arr)

@sunbigshan
Copy link

sunbigshan commented May 28, 2019

// 尾递归
function randomArr(count, arr = []) {
  if(count === 0) return arr;
  let num = Math.floor(Math.random() * 31) + 2;
  if(!arr.includes(num)) {
    arr.push(num);
    count--;
  }
  return randomArr(count, arr);
}

console.log(randomArr(5))

@likeke1997
Copy link

likeke1997 commented Jun 5, 2019

// 6 行写完
function buildArray(arr, length, min, max) {
    var num = Math.floor(Math.random() * (max - min + 1)) + min;
    if (!arr.includes(num)) { arr.push(num); }
    return arr.length === length ? arr : buildArray(arr, length, min, max);
}
var result = buildArray([], 5, 2, 32);
console.table(result);

补充:
题目要求”生成一个(2-32)之间的随机整数rand“,既然是随机,我觉得意为取值到区间内各数的概率应该是相等的。所以像这样的写法是不严谨的:

// 在 2 - 5 区间内生成随机数
var min = 2, max = 5;
var result = Math.max(min, Math.ceil(Math.random() * max));
// 参数一 param1 恒等于 2
// 参数二 param2 在 [0, 5] 之间等概取值
// 可能性见下
// param1 2 2 2 2 2 2
// param2 0 1 2 3 4 5
// result 2 2 2 3 4 5

可见 result 取到 2 的概率大于 3/4/5。 @linghucq1

@abin-jb
Copy link

abin-jb commented Jun 12, 2019

为啥要 return insertArr(arr, i) ,把return去掉也可以

@leisurele
Copy link

    let randomArr = [];
    function recursiveNumber(randomArr, currentLoop,min, max) {
        if (currentLoop <= 0) return;
        const curRandomNumber = min + parseInt(Math.round(Math.random() * (max -min)));
        if (randomArr.filter(res => res === curRandomNumber).length) {
            recursiveNumber(randomArr, currentLoop, min, max);
        } else {
            randomArr.push(curRandomNumber);
            recursiveNumber(randomArr, currentLoop - 1, min, max);
        }
    };
    recursiveNumber(randomArr, 5, 2, 32);

这是我的答案,大家可以参考下

@Damon99999
Copy link

Damon99999 commented Jun 17, 2019

function outPut() {
	var num = Math.random()*10+2;
	if(set.size <= 5) {
		set.add(Math.round(num));
		outPut();
	} else {
	        console.log([...set]);
	}
}
var set = new Set();
outPut();

@AricZhu
Copy link

AricZhu commented Jun 18, 2019

function gen(arr, n) {
if (n <= 0) {
return;
}
let randomItem = 2 + 30 * Math.random();
if (arr.indexOf(randomItem) !== -1) {
return gen(arr, n);
} else {
arr.push(randomItem);
return gen(arr, n-1);
}
}

@FEJiuL
Copy link

FEJiuL commented Jun 20, 2019

`
function main(len = 5){

let list = [];

for(let i = 2; i <= 32; i++){   // 这里生成取值范围列表

	list.push(i);

}

function getRandom(start, end){

	let rang = end - start;

	return Math.floor(Math.random() * rang) + start;

}

function recursion(arr = []){

	let index = getRandom(0, list.length);

	let val = list.splice(index, 1).join();  //随机到后移除出列表(可避免随机到重复值)

	arr.push(val);

	return arr.length >= len ? arr : recursion(arr);  //根据结束条件去递归

}

return recursion();

}
`

@persist-xyz
Copy link

persist-xyz commented Jun 26, 2019

function buildArray2 () {
        // Set实现
        function createRandom () {
            return Math.floor(Math.random() * 30 + 2)
        }
        let arr = new Set()
        function arrayRandom () {
            if (arr.size < 5) {
                arr.add(createRandom())
                arrayRandom()
            } else {
                arr = [...arr]
                console.log('---' + arr)
            }
        }
        arrayRandom()
    }

@lfz9527
Copy link

lfz9527 commented Aug 10, 2023 via email

@gavawu
Copy link

gavawu commented Sep 7, 2023

const arr = []
const pushItem = function(arr){
  if(arr.length<5){
     const randomNum = Math.floor(Math.random()*31 + 2)
     if(!arr.includes(randomNum)){
        arr.push(randomNum)
        pushItem(arr)
        return
     }else{
        pushItem(arr)
     }
  }
 
}

@13714273163
Copy link

13714273163 commented Sep 7, 2023 via email

@lfz9527
Copy link

lfz9527 commented Sep 7, 2023 via email

@0726m
Copy link

0726m commented Sep 22, 2023

// 生成指定范围的随机数
function getRandomNumber(min,max){
    return Math.floor(Math.random() * (max - min + 1)) +min;
}
// 检查数组中是否有重复的数
function hasDuplicates(array,num){
    return array.includes(num);
}
// 生成指定长度且元素不重复的随机数数组
function generateUniqueRandomArray(array,length){
    if(array.length === length){
        return array;
    }
    const randomNum = getRandomNumber(2,32);
// 如果生成的随机数在数组中已存在,则重新生成
    if(hasDuplicates(array.randomNum)){
        return generateUniqueRandomArray(array,length);
    }
    array.push(randomNum);
    return generateUniqueRandomArray(array,length);
}
const resultArray = generateUniqueRandomArray([],5);
console.log(resultArray);

@lfz9527
Copy link

lfz9527 commented Sep 22, 2023 via email

@Maureen-Lee
Copy link

你好 邮件已收到

@lfz9527
Copy link

lfz9527 commented Nov 7, 2023 via email

@zzyouyou
Copy link

zzyouyou commented Nov 7, 2023

const insert=(arr)=>{
const val = Math.floor(Math.random()*31)+2;
    if(!arr.includes(val)){
        arr.push(val);
    }
    if(arr.length<6) insert(arr);
}

let val=[];
insert(val);

@caiwuu
Copy link

caiwuu commented Jan 9, 2024

function genArr(res=[]) {
  const value =  Math.floor(Math.random()*31 + 2)
  if(res.indexOf(value)<0) return (res.push(value)<5 && genArr(res),res)
  return genArr(res) 
}

@13714273163
Copy link

13714273163 commented Jan 9, 2024 via email

@lxt-ing
Copy link

lxt-ing commented Jan 9, 2024 via email

@lfz9527
Copy link

lfz9527 commented Jan 9, 2024 via email

@angrybird233
Copy link

function getUniqueRandomNumbers(arr, n) {
if (arr.length === n) {
return arr;
} else {
let num = Math.floor(Math.random() * 31) + 2; // 生成2-32之间的随机数
if (!arr.includes(num)) {
arr.push(num);
}
return getUniqueRandomNumbers(arr, n);
}
}

const result = getUniqueRandomNumbers([],5);
console.log(result)

@lfz9527
Copy link

lfz9527 commented Feb 26, 2024 via email

@usercci
Copy link

usercci commented Mar 5, 2024

const createRandomNum = () => { return Math.floor(Math.random(0, 1) * 31) + 2; }; const createRandomArray = (array, num, i) => { if (!array.includes(num)) { array[i] = num; i++; } else { num = createRandomNum(); } if (i >= array.length) { console.log(array); return; } else { createRandomArray(array, num, i); } }; createRandomArray(new Array(5), createRandomNum(), 0);

@usercci
Copy link

usercci commented Mar 5, 2024

const createRandomNum = () => {
      return Math.floor(Math.random(0, 1) * 31) + 2;
    };
    const createRandomArray = (array, num, i) => {
      if (!array.includes(num)) {
        array[i] = num;
        i++;
      } else {
        num = createRandomNum();
      }
      if (i >= array.length) {
        console.log(array);
        return;
      } else {
        createRandomArray(array, num, i);
      }
    };
    createRandomArray(new Array(5), createRandomNum(), 0);

@pengshaowu
Copy link

pengshaowu commented Jul 2, 2024

let arr = [];
function pushArr() {
   if (arr.length == 5) return console.log(arr);
   let num = Math.floor(Math.random() * (31 - 2) + 2);
   if (arr.indexOf(num) == -1) arr.push(num);
   pushArr();
}
pushArr();

@13714273163
Copy link

13714273163 commented Jul 2, 2024 via email

@lfz9527
Copy link

lfz9527 commented Jul 2, 2024 via email

@erpao7
Copy link

erpao7 commented Jul 23, 2024

function foo(length, min, max) {
let result = [];
function bar() {
if (result.length === length) {
return;
}

      let randomNum = Math.floor(Math.random() * (max - min + 1));

      if (!result.includes(randomNum)) {
        result.push(randomNum);
      }
    }

    bar();
    return result;
  }
  const length = 5;
  const min = 2;
  const max = 32;
  const res = foo(length, min, max);

@13714273163
Copy link

13714273163 commented Jul 23, 2024 via email

@lfz9527
Copy link

lfz9527 commented Jul 23, 2024 via email

@pengsir120
Copy link

function fn(set = new Set()) {
if(set.size === 5) return Array.from(set)
set.add(Math.floor(Math.random() * 31) + 2)
return fn(set)
}

@13714273163
Copy link

13714273163 commented Sep 1, 2024 via email

@lfz9527
Copy link

lfz9527 commented Sep 1, 2024 via email

@msdlisper
Copy link

msdlisper commented Sep 6, 2024

const radomNum = () => {
  return Math.floor(Math.random() * 31 + 2)
}



const createArr = (arr) => {
  if (arr.length >= 5) {
    return arr;
  }
  const num = radomNum();
  if (arr.includes(num)){
    createArr(arr);
  } else {
    arr.push(num);
    createArr(arr)
  }
}


const res = createArr([])
console.log(res)

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

No branches or pull requests