Comments (449)
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)
}
from fe-interview.
// 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
from fe-interview.
考虑一下扩展性
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 参数来的好。
from fe-interview.
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);
from fe-interview.
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)
from fe-interview.
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)
from fe-interview.
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)
from fe-interview.
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)
from fe-interview.
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)
}
from fe-interview.
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)
from fe-interview.
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();
from fe-interview.
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);
}
from fe-interview.
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)
from fe-interview.
// 尾递归
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))
from fe-interview.
为啥要 return insertArr(arr, i)
,把return去掉也可以
from fe-interview.
7行搞定 Set去重是真好用
let arr = [];
(function insertNumber() {
if (arr.length === 5) return;
arr.push(Math.floor(Math.random() * 31 + 2));
arr = [...new Set(arr)];
insertNumber();
})()
console.log(arr);
from fe-interview.
/***
* 性能达到最优》考虑时间复杂度(避免使用Math.random去随机到不重复数字)
* 最终优化,当如果取随机数为30个的时候,那么最后面几个数会很小几率随机到,优化思路,将随机
* 数初始时放置数组,取值后剔除
*/
function getRandom1(n, min = 2, max = 32) {
//如果取值数量大于最大随机数,将最随机数最大值提高
if (n > (max - min)) {
max += n - (max - min);
}
//使用创建的指定数量空数组 keys 下标直接填充,避免 for循环填充
var initArray = Array.from(new Array(max + 1).keys()).splice(min);
return function insert(resArrayRandom) {
if (resArrayRandom.length == n) {
return resArrayRandom;
}
//获取剩余数组随机下标
var indexRandom = parseInt(Math.random() * initArray.length);
resArrayRandom.push(initArray[indexRandom]);
initArray.splice(indexRandom, 1);
return insert(resArrayRandom);
}([])
}
let beginTime2 = new Date().getTime();
getRandom1(1000)
console.log("优化取随机数 后耗时:", new Date().getTime() - beginTime2)
from fe-interview.
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));
from fe-interview.
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));
from fe-interview.
只需要 6 行代码:
function getFiveRandomSet(arr) {
if(arr.length >= 5) return arr
const randomNumber = ~~ (Math.random() * 30 + 2)
const newArr = Array.from(new Set(arr.concat(randomNumber)))
return getFiveRamdomSet(newArr)
}
getFiveRandomSet([])
from fe-interview.
function randomArray(length: number, min: number, max: number, cache?: {[key:number]: boolean}): number[] {
cache = cache || {}
const randomNum = Math.floor(Math.random() * (max - min + 1) + min)
if (!cache[randomNum]) {
length -= 1
cache[randomNum] = true
}
return length ? randomArray(length, min, max, cache) : Object.keys(cache).map(Number)
}
randomArray(5, 2, 32)
补充一下 Object
跟 Array.prototype.includes
去重性能对比代码:
const arr = []
const obj = {}
const len = 100000
for (let i = 0; i <= len; i++) {
arr.push(i)
obj[i] = true
}
console.time('Array.includes')
for (let i = 0; i <= len; i++) {
arr.includes(i)
}
console.timeEnd('Array.includes')
console.time('Obnject.keys')
for (let i = 0; i <= len; i++) {
obj[i]
if (i === len) {
Object.keys(obj).map(Number)
}
}
console.timeEnd('Obnject.keys')
Array.prototype.includes 规范,我们可以看出 includes
是通过遍历去查询是否存在 searchElement
元素的,这也是其速度不及 对象索引 快的原因了
from fe-interview.
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()
from fe-interview.
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()
from fe-interview.
`
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();
}
`
from fe-interview.
- 照顾通用性的解法
function randNumbers(n, lb, rb, arr = []) {
if (arr.length === n) return arr
const rand = Math.round(Math.random() * (rb - lb)) + lb
if (arr.includes(rand)) return randNumbers(n, lb, rb, arr)
else return randNumbers(n, lb, rb, arr.concat(rand))
}
console.log(randNumbers(5, 2, 32))
- 稍短一些的解法
function randNumbers(arr = []) {
if (arr.length === 5) return arr
const rand = Math.round(Math.random() * 30) + 2
if (arr.includes(rand)) return randNumbers(arr)
else return randNumbers(arr.concat(rand))
}
console.log(randNumbers())
from fe-interview.
只需要 6 行代码:
function getFiveRamdomSet(arr) { if(arr.length >= 5) return arr const randomNumber = ~~ (Math.random() * 30 + 2) const newArr = Array.from(new Set(arr.concat(randomNumber))) return getFiveRamdomSet(newArr) } getFiveRamdomSet([])
step1 就跪了, 6行代码, 呵呵了.
from fe-interview.
const randomArr = (arr = new Array(5), i = 0) => {
if (i >= arr.length) {
return arr
}
let num = Math.floor((Math.random() * 31)) + 2
if (arr.indexOf(num) === -1) {
arr[i++] = num
}
return randomArr(arr, i)
}
console.log(randomArr())
10 行代码,封装成函数,调用 randomArr 即可生成一个符合要求的数组,使用递归的方式。
还可以为函数提供随机数生成范围,数组长度等参数,进一步封装。
from fe-interview.
感觉ES6比较简洁,投机取巧一下。好久没写ts整两句。~~~很菜
// let sets: any = new Set([...Array(5)]);
// sets.delete(undefined);
// 前两行 等同于第四行。不明白 a目的何在
let sets: any = new Set();
!function getNum(sets): any {
let rand = Math.floor(Math.random() * 31 + 2);
return !sets.has(rand) || sets.size < 5 ? (sets.size < 5 ? getNum(sets.add(rand)) : sets) : sets;
}(sets);
console.log(sets);
// 如有错误 可以指正哈
from fe-interview.
let arr = [];
// 指定范围随机整数
let getRandomNum = (min, max) => { return min + Math.round((max - min) * Math.random())};
(function addArr (num) {
if (arr.length === 5) return
// 重复数据检测
if (!arr.includes(num)) arr[arr.length] = num
// 递归执行
addArr(getRandomNum(2, 32))
})(getRandomNum(2, 32))
console.log(arr = arr.sort((a, b) => a-b))
from fe-interview.
function generateArray(arr, length, max, min) {
if (arr.length === length) {
return arr
}
const rand = Math.ceil(Math.random()*(max - min)) + min
if (arr.indexOf(rand) === -1) {
arr.push(rand)
}
return generateArray(arr, length, max, min)
}
generatorArray([], 5, 32, 2)
from fe-interview.
function numerrandom() {
return Math.floor(Math.random()*31 + 2)
}
function test(arr, num) {
if (arr.length === 5) {
return arr
} else if (arr.indexOf(num) >-1) {
return test(arr, numerrandom())
}
else {
arr.push(num)
return test(arr, numerrandom())
}
}
from fe-interview.
function getArr(arr = []) {
if (arr.length === 5) {
return arr;
}
const ran = Math.floor(Math.random() * 31) + 2;
if (!arr.includes(ran)) {
arr.push(ran);
}
return getArr(arr);
}
console.log(getArr());
from fe-interview.
点评:
知识点:递归、随机数
难点:1颗星
这道题主要是想考递归的用法,同时顺带考了生成指定范围的随机数方法。
@yxkhaha @qingleizhang123
from fe-interview.
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))
from fe-interview.
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())
from fe-interview.
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)
from fe-interview.
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)
from fe-interview.
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);
这是我的答案,大家可以参考下
from fe-interview.
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();
from fe-interview.
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);
}
}
from fe-interview.
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()
}
from fe-interview.
答案超过15行代码的 好意思留答案吗?
from fe-interview.
// 9行
var set = new Set();
addRandom();
function addRandom(){
if(set.size<5){
let random = Math.floor(Math.random()*30+2);
set.add(random)
addRandom();
}
}
from fe-interview.
const arr = [];
let idx = 0;
function filter() {
const num = Math.floor(Math.random() * 31 + 2);
while (idx < 5) {
if (!arr.includes(num)) {
arr.push(num);
idx++;
}
filter();
}
}
from fe-interview.
const getRandomNumber = (min = 2, max = 32) =>
parseInt(Math.random() * (max - min + 1) + min, 10);
const arr = new Array(5);
const getUniqNumber = (arr, index, num, limit = 5) => {
if (index >= limit) {
return arr;
}
if (arr.includes(num)) {
getUniqNumber(arr, index, getRandomNumber(), limit);
} else {
arr[index] = num;
getUniqNumber(arr, index + 1, getRandomNumber(), limit);
}
};
getUniqNumber(arr, 0, getRandomNumber());
console.log(arr);
from fe-interview.
function fn (arr, size) {
if (arr.length === size) return arr
var num = Math.floor(Math.random() * 30) + 2
if (!arr.includes(num)) arr.push(num)
return fn(arr, size)
}
fn([], 6)
from fe-interview.
const arr = new Array(5).fill(null);
const rand = () => Math.floor(Math.random() * 30 + 2);
function insertToArr(arr) {
if (arr.filter(Boolean).length >= 5) return arr;
const randVal = rand();
~arr.indexOf(randVal) ? null :arr[arr.filter(Boolean).length] = randVal;
return insertToArr(arr);
}
console.log(insertToArr(arr))
from fe-interview.
const arr = new Array(5);
const funcRandomValue = () => {
return Math.floor((Math.random() * 31) + 2);
};
let a = 0;
const func1 = (cont) => {
if (arr.indexOf(cont) === -1) {
arr[a] = cont;
a = a + 1;
if (a !== 5) func1(funcRandomValue());
} else {
func1(funcRandomValue());
}
}
func1(funcRandomValue());
from fe-interview.
function randArr(arr,randNum){
var rand = Math.floor(Math.random()*30 + 2);
if(arr.length < 5){
if(arr.some(i=>{i === randNum})){
randArr(arr,rand)
}else{
arr.push(randNum)
randArr(arr,rand)
}
}else{
console.log(arr)
}
}
randArr([],Math.floor(Math.random()*32 + 2))
from fe-interview.
let getRandomArr = function(e){
let arr = e ? e : []
let randomNum = getRandomNum()
if(!arr.includes(randomNum)){
arr.push(randomNum)
}
return arr.length === 5 ? arr : getRandomArr(arr)
}
let getRandomNum = function(){
return Math.floor(Math.random()*31+2)
}
from fe-interview.
看问题,我还以为要自己实现随机数算法,结果进来大家都用 Math.random
from fe-interview.
function randomNumArr(min, max, len, arr: number[] = []) {
if (arr.length === len) {
return arr;
}
let num = randomNum(min, max);
while (arr.includes(num)) {
num = randomNum(min, max);
}
arr.push(num);
return randomNumArr(min, max, len, arr);
}
function randomNum(min, max) {
return min + Math.round(Math.random() * (max - min));
}
from fe-interview.
var arr =[];
var rand;
var i = 0;
function getArr(arr){
rand = Math.floor(Math.random()*31+2);
if(arr.length==5) {
console.log(arr);
i=0;
arr =[];
return;}
if(arr.length==0 || arr.every((item)=>(item!=rand)))
{ arr[i] = rand; i++; }
getArr(arr) }
getArr(arr)
from fe-interview.
function randArr(arr=[]){
let rand = Math.ceil(Math.random()*30+2);
if(arr.indexOf(rand)===-1&&arr.length<5){
arr.push(rand)
return randArr(arr)
}else{
return arr;
}
}
from fe-interview.
function result () {
let arr = new Array(5).fill(undefined)
const fill = () => {
let number = 2 + Math.floor(Math.random()*30)
let index = arr.findIndex(item => item === undefined || item === number);
if ( index !== -1) {
arr.splice(index, 1, number);
fill()
}
}
fill()
return arr
}
console.log(result())
from fe-interview.
function padArray(arr, i, min, max) {
const length = arr.length
if (arr[length - 1]) return arr
const random = Math.min(Math.ceil(Math.random() * max + min), max - 1)
if (!arr.includes(random)) arr[i++] = random
return padArray(arr, i, min, max)
}
console.log(padArray(new Array(5), 0, 2, 32))
from fe-interview.
function randomArr(count, min, max, arr = []) {
if (arr.length === count) return arr
let randomNumber = ~~(Math.random() * (max - min + 1) + min)
return randomArr(count, min, max, [...new Set([...arr, randomNumber])])
}
randomArr(5, 2, 32)
缺点:函数的执行与函数名 randomArr 耦合在了一起
优化:给内部函数命名
function randomArr(count, min, max, arr = []) {
return (function fn(count, min, max, arr = []) {
if (arr.length === count) return arr
let randomNumber = ~~(Math.random() * (max - min + 1) + min)
return fn(count, min, max, [...new Set([...arr, randomNumber])])
})(count, min, max, arr = [])
}
from fe-interview.
const arr = new Array(5);
const randNum = () => 2 + Math.floor( Math.random() * 30 );
let i = 0;
const randFun = () => {
if( i == arr.length ) return
!arr.includes( randNum() ) && (arr[i] = randNum() ) && i++;
randFun()
}
randFun();
from fe-interview.
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);
step1就跪了. 生成一个长度为5的空数组arr。
const arr = [];
arr.length = 5;
const createNum = () => parseInt(Math.random() * 31) + 2;
pushNum = () => {
if(arr[4]) return;
let num = createNum();
if(!arr.includes(num)) {
arr.splice(arr.findIndex(item => !item), 1, num);
}
pushNum();
}
pushNum();
from fe-interview.
只需要 6 行代码:
function getFiveRamdomSet(arr) { if(arr.length >= 5) return arr const randomNumber = ~~ (Math.random() * 30 + 2) const newArr = Array.from(new Set(arr.concat(randomNumber))) return getFiveRamdomSet(newArr) } getFiveRamdomSet([])
step1 就跪了, 6行代码, 呵呵了.
from fe-interview.
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);step1就跪了. 生成一个长度为5的空数组arr。
const arr = [];
arr.length = 5;
const createNum = () => parseInt(Math.random() * 31) + 2;
pushNum = () => {
if(arr[4]) return;
let num = createNum();
if(!arr.includes(num)) {
arr.splice(arr.findIndex(item => !item), 1, num);
}
pushNum();
}
pushNum();
第一:学会格式化代码
第二:学会合理使用表情
第三:学会使用 markdown
都 9012 年了还不会学 es6 ?
from fe-interview.
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);step1就跪了. 生成一个长度为5的空数组arr。
const arr = [];
arr.length = 5;
const createNum = () => parseInt(Math.random() * 31) + 2;
pushNum = () => {
if(arr[4]) return;
let num = createNum();
if(!arr.includes(num)) {
arr.splice(arr.findIndex(item => !item), 1, num);
}
pushNum();
}
pushNum();第一:学会格式化代码
第二:学会合理使用表情
第三:学会使用 markdown
都 9012 年了还不会学 es6 ?
戾气太重, 格式化代码确实是我没注意, 直接在评论里写了,而且我接下来的回复也没打算用什么格式化, 另外md经常使用,还需要提醒我学吗? 表情有问题? 表情不就是用来自嘲或者嘲讽别人的吗? 没看出来我代码里哪里必须要使用es6的地方啊? 你可以指出来.
我说的step1 跪了, 难道错了吗? 你自己看, 要求是: a) 生成一个长度为5的空数组arr。你生成了吗? 偷奸耍滑, 直接用空数组push了, 虽然能得到正确结果, 但是没有按要求来. a步骤并不是多余的, 其中影藏一个考点是不使用for,等循环语句, 来判断是否达到5个正确的值了, 以及当前产生的数字要放到数组的那个位置, 也还有就是生成 空数组的技巧. const arr = Array(5); 或者 const arr = new Array(5); 或者 const arr = []; arr.length = 5; 这几种方式都能生成空的, 长度为5的数组. 你的代码直接跳过了这个要求, 我指出来的不对吗?我的代码有问题, 你可以指出来(要具体), 可以嘲讽, 但是请不要人身攻击.
from fe-interview.
let arr=[ ];
function fn(arr){
if(arr.length>=5) return arr;
let ramdom=Math.floor(Math.random()*31+2);
if(arr.includes(ramdom)){ return fn(arr);}
else {return fn([...arr,ramdom]);}
}
console.log(fn(arr))
from fe-interview.
看问题,我还以为要自己实现随机数算法,结果进来大家都用
Math.random
启动编辑器的一瞬间,我的脑海中随机出现了 1 3 5 7 9五个数字,和算法生成随机数一样,所以不用再生成了。
from fe-interview.
var arr = [];
toarr();
function toarr() {
var num = randomNum();
if (arr.length < 5) {
if (arr.indexOf(num) < 0) {
arr.push(num);
toarr();
} else {
toarr();
}
} else {
console.log(arr);
}
}
function randomNum() {
return Math.floor(Math.random() * (32 - 2)) + 2;
}
from fe-interview.
var array = new Array(5);
function insert(array, index) {
if (array.length === index) {
return array;
}
var number = parseInt(Math.random() * (32 - 2 + 1) + 2, 10);
if (array.includes(number)) {
return insert(array, index);
} else {
array[index] = number;
return insert(array, ++index);
}
}
console.log(insert(array, 0));
from fe-interview.
九行代码
var arr = new Array(5),index=0;
function create () {
var rand = Math.floor(Math.random()*31 + 2);
if (arr.indexOf(rand) === -1 && index <5){
arr[index] = rand;
++index;
create();
} else if(index===6) return;
}
from fe-interview.
8 行
function randarr(arr) {
let rand = parseInt((Math.random()*30+2).toFixed(0))
if (arr.length === 5) { console.log(arr);return }
arr.indexOf(rand) === -1 ? arr.push(rand) && randarr(arr) : randarr(arr)
}
let arr = []
randarr(arr)
from fe-interview.
const random = (min, max)=> () => Math.random() * (max - min) + min
let random2to32 = random(2,32)
function createRandomNum(length) {
let arr = new Set()
function creatNum(arr, total) {
if(arr.size===total) return arr
let newRandoms = Math.floor(random2to32())
if(!arr.has(newRandoms)){
arr.add(newRandoms)
}
return creatNum(arr, total)
}
let returnArr = creatNum(arr, length)
return [...returnArr]
}
console.log(createRandomNum(5));
from fe-interview.
只需要 6 行代码:
function getFiveRamdomSet(arr) { if(arr.length >= 5) return arr const randomNumber = ~~ (Math.random() * 30 + 2) const newArr = Array.from(new Set(arr.concat(randomNumber))) return getFiveRamdomSet(newArr) } getFiveRamdomSet([])
step1 就跪了, 6行代码, 呵呵了.
淡定。朋友
from fe-interview.
let arr = [];
let i = 0;
// 生成2~32随机数
function span () {
let num = Math.floor(Math.random() * 31) + 2;
return num;
}
function arrRes () {
let newNum = span();
// 数组的长度为5
if(i < 5) {
if (!arr.includes(newNum)) {
arr.push(newNum) // 每增加一项让i+1
i++;
arrRes() // 递归
}else {
arrRes() // 如果有随机数相同的情况也要进行递归,但是i值不变
}
}
}
arrRes()
console.log(arr)
from fe-interview.
function randomArr(arr){
arr.add(Math.floor(Math.random()*31+2))
if(arr.size < 5) randomArr(arr)
return [...arr]
}
console.log(randomArr(new Set()))
from fe-interview.
(function getRandomArrayByRange(arr = new Set(), len = 5, min = 2, max = 32) {
arr.add(Math.floor(Math.random() * (max - min + 1) + min))
return arr.size < len ? getRandomArrayByRange(arr, len, min, max) : [...arr]
})()
from fe-interview.
function getRandomNum(arr) {
let val = Math.floor(Math.random()*31 + 2);
if (arr.includes(val)) {
return getRandomNum(arr);
} else {
return val;
}
}
function createArr(arr) {
if (arr.length === 5) {
console.log(arr);
return;
}
let val = getRandomNum(arr);
arr.push(val);
createArr(arr);
}
createArr([]);
from fe-interview.
let set = new Set();
function test() {
if (set.size() === 4) set.add(Math.random() * 30 + 2)
}
let arr = Array.from(set)
from fe-interview.
let a = new Array(5)
function addArr(arrNo, num) {
if (num == 5) {
return
} else {
var arrNum = Math.floor(Math.random() * 31 + 2)
var n = arrNo.find(e => e == arrNum)
if (n == undefined) {
arrNo.splice(num,1,arrNum)
num ++
}
addArr(arrNo, num)
}
}
addArr(a, 0)
from fe-interview.
那些比几行代码的,我不敲回车可以再少几行!!!!!!!!!
from fe-interview.
获取(min ~ max)范围内的随机整数
Math.floor(Math.random() * (max - min + 1) + min)
输出长度为5且内容不重复的arr
let arr = new Array(5)
let printArr = (arr, i = 0) => {
let rand = Math.floor(Math.random() * 31 + 2)
if (i < arr.length) {
if (!arr.includes(rand)) {
arr[i++] = rand
}
printArr(arr, i)
}
return arr
}
printArr(arr) // 调用
from fe-interview.
https://codepen.io/9lk/pen/OKPwOo
// 1.生成一个长度为5的空数组arr。
var genArray = length => (Array.from({length}))
// 2.生成一个(2-32)之间的随机整数rand。
var genRandNum = () => Math.ceil(Math.random()*30+1)
// 3.数组长度为5且元素的随机数在2-32间不重复的值
var reduceNums = (length, set=[]) => {
if(set.size>= length) return Array.from(set)
return reduceNums(length, new Set([genRandNum(), ...set]))
}
from fe-interview.
function createArray(arr = []) {
// Get a random between 2 and 32
const randomNum = 2 + Math.floor(Math.random()*31)
// Cannot be repeated with the number in arr
!arr.includes(randomNum) && arr.push(randomNum)
// Create a array of length 5
arr.length < 5 && createArray(arr)
return arr
}
from fe-interview.
递归用了2行代码实现。
固定N=5
次循环,100%命中。
除了第一次需要生成样本数据略慢外,后续调用都非常快速。
不会影响其他同步函数执行,不影响渲染。
欢迎讨论性能更好的算法。
"use strict";
function Range ( m, n, step ) {
this._sample = this._generateSample( m, n, step );
}
Range.prototype = {
setSample ( sample = [] ) {
this._sample = Promise.resolve( sample );
},
async shuffle ( size ) {
if ( size ) {
const sample = Array.from( await this._sample );
const n = sample.length;
if ( n < size ) {
throw new Error(
`Shuffle size must not exceed the range size. ` +
`Expected the maximum value of size is ${ n }, but the actual value is ${ size }.`
);
}
const result = new Array( size );
console.time( `shuffle perf` );
this._shuffle( size, sample, n, result );
console.timeEnd( `shuffle perf` );
return result;
}
return [];
},
async _generateSample ( m = 0, n = 0, step = 1 ) {
m > n && ( [ m, n ] = [ n, m ] );
step = Math.abs( step );
const sample = [];
do {
sample.push( n );
}
while( m <= ( n -= step ) );
return sample;
},
_shuffle : ( () => {
const random = Math.random;
function shuffle ( size, sample, n, result ) {
result[ size -= 1 ] = sample.splice( random() * n >> 0, 1 )[ 0 ];
size && shuffle( size, sample, n - 1, result );
}
return shuffle;
} )(),
};
const range = new Range( 2, 32 );
console.log( await range.shuffle( 5 ) );
from fe-interview.
let arr = [];
random(arr);
function random(arr) {
if (arr.length < 5) {
let rand = Math.floor((Math.random()*30)+2);
if (arr.indexOf(rand) === -1) {
arr.push(rand);
}
random(arr);
}
}
from fe-interview.
var randomArr = function(arr=[],length=5,min=2,max=32){
var randomNumber = Math.floor(Math.random()*(max-min))+min;
if(arr.length<length){
if(!arr.includes(randomNumber)){
arr.length === 0 ? arr[0] = randomNumber : arr[arr.length] =
randomNumber;
}
randomArr(arr);
}
if(arr.length==length){
return arr;
}
}
console.log('result_arr',randomArr())
from fe-interview.
function randomArr(arr = new Array(5), len = 5) {
if (len === 0) {
return arr
}
const num = ~~(Math.random() * 31) + 2
if (arr.includes(num)) {
return randomArr(arr, len)
}
arr[--len] = num
return randomArr(arr, len)
}
from fe-interview.
let arr = new Array(5);
for (let i = 0; i < arr.length; i++) {
let num = genNum();
arr[i] = num;
}
function genNum() {
let num = Math.floor(Math.random() * 31 + 2);
if (arr.indexOf(num) < 0) {
return num;
} else {
return genNum();
}
}
console.log(arr)
from fe-interview.
let arr = new Array(5), index = 0;
function deepLoop(arr) {
if(index > 4) {
return
}
let arnd = Math.floor(Math.random()*31 + 2);
if(!arr.includes(arnd)) {
arr[index++] = arnd;
}
deepLoop(arr);
}
from fe-interview.
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) }
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) }
i++后面应该加一句num = randomNumber();不然每次重新赋值随机数都会占用一次递归.
from fe-interview.
这一题是起源题
描述:
- 这是一道大题目,把考点拆成了4个小项;需要侯选人用递归算法实现(限制15行代码以内实现;限制时间10分钟内完成):
a) 生成一个长度为5的空数组arr。
b) 生成一个(2-32)之间的随机整数rand。
c) 把随机数rand插入到数组arr内,如果数组arr内已存在与rand相同的数字,则重新生成随机数rand并插入到arr内[需要使用递归实现,不能使用for/while等循环]
d) 最终输出一个长度为5,且内容不重复的数组arr。
let arr = [];
function PushArr() {
let num = 2 + Math.floor(Math.random() * 30);
if (arr.length < 5) {
if (arr.indexOf(num) === -1) {
arr.push(num);
PushArr();
} else {
PushArr();
}
if (arr.length === 5) {
return arr;
}
}
}
PushArr();
from fe-interview.
var arr = new Array(5),
num = Math.ceil(Math.random() * 31 + 1),
i = 0;
function randomArr(a,n){
//去重
if (a.indexOf(n) < 0){
a[i] = n;
i++;
}else{
n = Math.ceil(Math.random() * 31 + 1);
}
//递归条件
if(i >= a.length){
return;
}else{
randomArr(a,n);
}
}
randomArr(arr,num);
from fe-interview.
var arr = new Array(5);//创建长度为5的空数组
var rand,i = 0;//声明随机数rand和i
function rDom(rand,i){
rand = Math.round(Math.random()*30)+2; //生成2~32的整数
if(arr[4] != undefined){ //递归结束条件
return arr;
}else{
if(arr.indexOf(rand) == -1){ //indexOf检索arr数组
arr[i] = rand;
i++;
}
return rDom(rand,i);
}
}
rDom(rand,i);
console.log(arr);
from fe-interview.
let arr = []
for (let i = 0; i < 5; i++) {
function fn() {
let num = Math.floor(Math.random() * 30 + 2)
if (!arr.includes(num)) {
arr[i] = num
} else {
fn()
}
}
fn()
}
console.log(arr)
from fe-interview.
function fillRandomNum(arr) {
while (true) {
// fixed interval random number
//[a, b): (int)(Math.random()*(b-a)+a)
//[a, b]: (int)(Math.random()*(b-a+1)+a)
var item = Math.floor(Math.random() * 30 + 2)
if (arr.includes(item)) {
++i
} else {
arr.push(item)
return arr
}
}
}
function fillArray(arr) {
debugger
var array = arr || []
if (
array.filter(e => e < 2 || e >= 32).length > 0 &&
array.length > 0
)
array = []
if (array.length === 5) {
return array
} else {
array = fillRandomNum(array)
// here must return keyword that console the end array
return fillArray(array)
}
}
console.log(fillArray([1]))
from fe-interview.
let arr = [];
function generate() {
if (arr.length < 5) {
// 产生随机数
let number = Math.ceil(Math.random() * 30 + 2);
if (arr.indexOf(number) > -1) {
generate();
} else {
arr.push(number);
generate();
}
}
}
generate();
console.log('arr:', arr);
from fe-interview.
干好15行~~~
let arr = new Array(5);
let i = 0;
let rand = parseInt(Math.random() * 30 + 2);
let setArr = function (x) {
if (arr[arr.length - 1]) {
return arr;
};
if(arr.includes(x)) {
rand = parseInt(Math.random() * 30 + 2);
}else {
arr[i++] = rand
}
setArr(rand);
return arr;
}
from fe-interview.
const fn= function(n, r){
if(!n){
n = 0;
r = [];
}
return n+1 <6 ? r.concat(Math.floor(Math.random()*31 + 2)).concat(fn(n+1, r)) : r;
}
fn();
from fe-interview.
var arr = [];
function fn (arr=[], length=5, min=2, max=32) {
if (arr.length >= length
|| !Array.isArray(arr)
|| typeof length !== 'number'
|| typeof min !== 'number'
|| typeof max !== 'number'
|| min > max){
return;
}
length = length > max - min ? max - min : length;
var val = Math.floor( Math.random() * (max - min + 1) + min );
if ( !arr.includes( val ) ) {
arr.push(val);
}
fn(arr, length, min, max);
}
fn(arr);
console.log(arr);
from fe-interview.
// ------优化includes indexOf 查找速度 ,避免这一项时间复杂度--------------
// 使用 set 数组自动去重特性
function getRandom(n) {
var setArray = new Set();
return function insert2(_setArray) {
if (_setArray.size == n) {
//最终返回时 将set 转为 普通数组格式 []
return [..._setArray];
}
var number = parseInt(Math.random() * 31 + 2);
// set 数组自动去重特性,避免了 每次查找数组是否有值
_setArray.add(number);
return insert2(_setArray);
}(setArray)
}
getRandom(5)
from fe-interview.
考虑扩展性,可能有点性能问题~
function getArr(length,min,max){
var arr=[],hash={};
function fn(){
var num=Math.floor(Math.random()*(max-1))+min;
if(!hash[num]){
hash[num] = true;
arr.push(num);
}
return arr.length===length?arr:fn();
}
return fn();
}
getArr(5,2,32)
from fe-interview.
const fn = (arr = [], x) => {
if(arr.length >= 5) { return arr }
x && !arr. includes(x) && arr.push(x)
return fn(arr, Math.floor((Math.random() * 32)) + 2) }
fn()
from fe-interview.
const varr = Array(5);
const rand1 = Math.max(2, Math.floor((Math.random() * 1000) % 32));
const vres = [];
function fillArr(arr, res) {
const rand = Math.max(2, Math.floor((Math.random() * 1000) % 32));
if (arr.indexOf(rand) == -1 && res.length < 5) {
res.push(rand);
arr.push(rand);
fillArr(arr, res)
} else if (res.length >= 5) {
return res;
}
}
fillArr(varr, vres);
主要学习到更优雅的随机数生成方法Math.floor(Math.random()*31+2)
~
另外没有使用下标,而是直接生成新数组,内部判断合并
from fe-interview.
Related Issues (20)
- [angular] 第1814天 请说说在Angular中的ngSwitch是什么?有哪些用途?
- [angular] 第1815天 请说说在Angular中的组件是什么?
- [angular] 第1816天 请说说在Angular中什么是指令?有哪些类型的指令?
- [angular] 第1817天 请说说在Angular中的依赖注入是什么?
- [angular] 第1818天 请说说在Angular中的NgModule是什么?
- [angular] 第1819天 请说说在Angular中的可观察对象是什么?
- [angular] 第1820天 请说说在Angular中的路由器守卫是什么?它有哪些类型?
- [angular] 第1821天 请说说在Angular中的服务是什么?如何创建一个服务?
- [angular] 第1822天 请说说在Angular中的模板语法是什么?
- [angular] 第1823天 请说说在Angular中的管道是什么?如何创建一个管道?
- [angular] 第1824天 请说说在Angular中的Change Detection是什么?如何优化应用程序的性能?
- [angular] 第1825天 请说说在Angular中的NgModule是如何工作的?它有哪些功能?
- [angular] 第1826天 请说说在Angular中的动态组件是什么?
- [angular] 第1827天 在Angular中怎样创建一个动态组件?
- [angular] 第1828天 在Angular中怎样创建一个服务工厂?
- [angular] 第1829天 请说说在Angular中的RxJS是什么?
- [angular] 第1830天 请说说在Angular中的单元测试是什么?
- [angular] 第1831天 在Angular中怎样写一个单元测试?
- [angular] 第1832天 请说说在Angular中的服务工厂是什么?
- [angular] 第1833天 在Angular中怎样使用RxJS?
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from fe-interview.