这个问题已经在这里有一个答案:
您好我想在列表中的特定范围内得到一个随机指数。在此之后,指数不应再次,如果我想有一个列表的另一个随机指数返回。
这是在[min, max)
范围,并没有重复产生随机数的方法。
它采用了查找对象存储到目前为止每个范围返回的值。
如果没有可供返回的数字,它返回undefined
。
const usedIndicesByRange = {};
function randomIntInRange(min, max) {
const key = `${min}-${max}`;
if (!(key in usedIndicesByRange)) {
usedIndicesByRange[key] = [];
}
if (usedIndicesByRange[key].length === max - min) {
return undefined;
}
const getIdx = () => Math.floor(Math.random() * (max - min) + min);
let idx = getIdx();
while (usedIndicesByRange[key].includes(idx)) {
idx = getIdx();
}
usedIndicesByRange[key].push(idx);
return idx;
}
console.log([...Array(12)].map(() => randomIntInRange(0, 10)));