blog icon indicating copy to clipboard operation
blog copied to clipboard

如何生成某个范围内的随机整数,但排除整数子集?

Open wuxianqiang opened this issue 5 years ago • 0 comments

function randomInt(min, max, exclude) {
  const nums = [];
  const excludeLookup = new Set(exclude);
  for (let i = min; i <= max; i++) {
    if (!excludeLookup.has(i)) nums.push(i);
  }
  if (nums.length === 0) return false;

  const randomIndex = Math.floor(Math.random() * nums.length);
  return nums[randomIndex];
}

console.log(randomInt(1, 5, [2, 3]))

wuxianqiang avatar Jan 09 '20 02:01 wuxianqiang