方案1: 找到 count 个不同改的索引, 然后返回索引对应值的数组, 不同的索引使用 map 结构保证(indexCache), getRandomNumber 找到随机大于 items.length 个的数子, 大于它能保证取余的值是随机的.
function pick(count, items) {
if (count > items.length) throw new Error(`You cannot choose ${count} different things from ${items.length}`)
const indexCache = {}
const getRandomNumber = () => Math.ceil(10 ** (items.length + 1) * Math.random())
let counter = count
while (counter) {
const index = getRandomNumber() % items.length
if (indexCache[index] !== undefined) continue
indexCache[index] = null
counter--
}
return Object.keys(indexCache).map(i => items[i])
}
方案1优化:
function getRandomNumebrInRange(left, right) {
const number = Math.ceil((right - left) * Math.random()) + left
return number
}
function pick(count, items) {
const result = []
const indexCache = {}
while(count) {
const length = items.length
const index = getRandomNumebrInRange(0, length -1)
if(indexCache[index] !== undefined) continue
result.push(items[index])
indexCache[index] = index
count--
}
return result
方案2: 打乱顺序, 再从数组里面直接截取所需长度的元素
function pick(count, items) {
const newItems = [...items]
newItems.sort(() => Math.random() - 0.5)
return newItems.slice(0, count)
}
版权声明:本文为tzzdblog原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。