Interview icon indicating copy to clipboard operation
Interview copied to clipboard

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

Open qappleh opened this issue 4 years ago • 3 comments

/* 
 实现一个randomString函数,返回一个数组,
 该数组内有一千个字符串,
 每串字符串为6位数0-9的随机验证码,不可重复。
*/
function randomString() {
  //  write your code here
}

qappleh avatar Aug 16 '21 03:08 qappleh

	/*
	 @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
	}

mosquitozzy avatar Aug 16 '21 06:08 mosquitozzy

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;
}

btea avatar Aug 17 '21 09:08 btea

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]
},

guanxc9876 avatar Aug 18 '21 09:08 guanxc9876