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

1 Answer

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

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

  return num;
}

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

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



/*
run:

6

*/

 



answered 21 hours ago by avibootz

Related questions

...