方案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
retur