shfshanyue / Daily-Question

互联网大厂内推及大厂面经整理,并且每天一道面试题推送。每天五分钟,半年大厂中
https://q.shanyue.tech
4.92k stars 508 forks source link

【Q677】如何实现一个 sampleSize 函数,从数组中随机取N个元素 #696

Open shfshanyue opened 3 years ago

shfshanyue commented 3 years ago
const shuffle = (list) => list.sort((x, y) => Math.random() - 0.5)
const sampleSize = (list, n) => shuffle(list).slice(0, n)
voezy commented 1 year ago
Array.prototype.sampleSie = function(size) {
    const result = [];
    const tmp = [...this];
    const len = tmp.length;
    for (let i = 0; i < size && i < len; i++) {
        const index = Math.floor(Math.random() * tmp.length);
        result[i] = tmp.splice(index, 1)[0];
    }
    return result;
}
rujptw commented 1 year ago

不知道这样可不可以,从随机挑选的数,组成的数组,长度达到size,就返回

function sampleSize(array,size){
  let len = array.length,i,pickArr = [];
  while(len&&size){
    i = Math.floor(Math.random()*len);
    len--;
    pickArr.push(array.splice(i,1)[0]);
    size--;
  }
  return pickArr
}
huanxiaomang commented 2 months ago

补充:使用sort会改变原数组,这点其实不太好,可以改为toSorted,说不定是个加分点。

const shuffle = (list) => list.toSorted((x, y) => Math.random() - 0.5)
const sampleSize = (list, n) => shuffle(list).slice(0, n)

会改变原数组的方法:4+3+1+1 4:push pop shift unshift 3:sort reverse splice => 他们的非破坏性版本toSorted toReversed toSpliced 1+1:flat copyWithIn(不太常见)

loveminxo commented 2 months ago

这是来自QQ邮箱的假期自动回复邮件。你好,我最近正在休假中,无法亲自回复你的邮件。我将在假期结束后,尽快给你回复。

shfshanyue commented 2 months ago

@huanx toSorted 确实很好用!