liuguanyu / quiz-every-meeting

8 stars 0 forks source link

2018-07-26 #23

Open chunpu opened 6 years ago

chunpu commented 6 years ago

实现一个 sampleSize 函数, 随机取出数组中n个值

例子如下

sampleSize([1, 2, 3, 4]) // => [2]
sampleSize([1, 2, 3, 4], 2) // => [1, 3]
sampleSize([1, 2, 3, 4], 4) // => [1, 3, 4, 2]
liuguanyu commented 6 years ago

看似经典的洗牌算法,要不重复的抽出值,同时要保证所有未抽到的数据有平等概率被抽到、

const sampleSize = (arr, getCount=1) => {
    const count = arr.length

    let ret = []

    if (count < getCount){
        getCount = count
    }

    for (let i = 0; i < getCount; ++i){
        let nowNode = count-1-i
        let r = Math.floor(Math.random(nowNode) * (nowNode))

        ret.push(arr[r])

        let tmp = arr[nowNode]
        arr[nowNode] = arr[r]
        arr[r] = tmp
    }

    return ret
}