【问题标题】:How to get random index in a specific range only once [duplicate]如何仅在特定范围内获取随机索引一次[重复]
【发布时间】:2019-07-03 06:16:53
【问题描述】:

您好,我想在列表的特定范围内获取随机索引。 之后,如果我想要一个列表的另一个随机索引,则不应再次返回该索引。

【问题讨论】:

  • 你能发布你到目前为止的尝试以及你在哪里挣扎吗?

标签: javascript random indexing


【解决方案1】:

这是一种在[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)));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-29
    • 2016-09-19
    • 2018-06-22
    • 1970-01-01
    • 1970-01-01
    • 2014-10-23
    • 1970-01-01
    • 2021-07-24
    相关资源
    最近更新 更多