How to generate a random integer from a range [0, N] that is not in a unique integer list with JavaScript

1 Answer

0 votes
function randomExcluding(N, excluded) {
  if (excluded.length > N + 1) {
    return -1; // All numbers are excluded
  }

  let num;
  do {
    num = Math.floor(Math.random() * (N + 1)); // Inclusive range [0, N]
  } while (excluded.includes(num));

  return num;
}

const excluded = [2, 5, 7];
const N = 14;

console.log(randomExcluding(N, excluded));




/*
run:

13

*/

 



answered 21 hours ago by avibootz

Related questions

...