如何在一个特定的范围内获得随机指标只有一次[复制]

问题描述 投票:-1回答:1

您好我想在列表中的特定范围内得到一个随机指数。在此之后,指数不应再次,如果我想有一个列表的另一个随机指数返回。

javascript random indexing
1个回答
0
投票

这是在[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)));
© www.soinside.com 2019 - 2024. All rights reserved.