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

1 Answer

0 votes
using System;
using System.Collections.Generic;

class Program
{
    static int RandomExcluding(int N, List<int> excluded) {
        if (excluded.Count > N + 1) {
            return -1; // All numbers are excluded
        }

        var rand = new Random();
        int num;
        do {
            num = rand.Next(0, N + 1); // Inclusive range [0, N]
        } while (excluded.Contains(num));

        return num;
    }

    static void Main()
    {
        var excluded = new List<int> { 2, 5, 7 };
        int N = 14;

        int result = RandomExcluding(N, excluded);
        Console.WriteLine(result);
    }
}



/*
run:

11

*/

 



answered 22 hours ago by avibootz

Related questions

...