qappleh / Interview

我是追梦赤子心,公众号「深圳湾码农」的作者,某上市集团公司高级前端开发,深耕前端领域多年,每天攻破一道题,带你从0到1系统构建web全栈完整的知识体系!
https://github.com/qappleh/Interview
1.14k stars 95 forks source link

Day380:实现一个randomString函数,返回一个数组, 该数组内有一千个字符串, 每串字符串为6位数0-9的随机验证码,不可重复? #383

Open qappleh opened 3 years ago

qappleh commented 3 years ago
/* 
 实现一个randomString函数,返回一个数组,
 该数组内有一千个字符串,
 每串字符串为6位数0-9的随机验证码,不可重复。
*/
function randomString() {
  //  write your code here
}
mosquitozzy commented 3 years ago
    /*
     @param {Number} len 返回的 randomString 数组长度
     @param {Number} strLen 随机验证码长度
     */
    function randomString(len, strLen) {
        let randomStr = []
        for (let i=0; i<len; i++) {
            setStr(randomStr, randomCode(strLen))
        }
        function setStr(arr, str) {
            if (arr.includes(str)) {
                setStr(arr, str)
            } else {
                arr.push(str)
                return
            }
        }
        function randomCode(strLen) {
            let randomCode =  Math.random().toString().split('.')[1].slice(0,6)
            return randomCode
        }
        return randomStr
    }
btea commented 3 years ago
function randomString() {
    let arr = [];
    let map = {};
    for (let i = 0; i < 1000; i++) {
        let v = Math.random().toString().slice(2, 8);
        while (map[v]) {
            v = Math.random().toString().slice(2, 8);
        }
        map[v] = true;
        arr.push(v);
    }
    return arr;
}
guanxc9876 commented 3 years ago
randomString() {
  let arrSize = 0
  let code = ''
  const arrSet = new Set()
  while (arrSize < 1000) {
    code = Math.floor(Math.random() * 1000000) + ''
    code.length === 6 ? arrSet.add(code) : code
    arrSet.size === arrSize ? arrSize : arrSize++
  }
  return [...arrSet]
},