How about using a utility enumerable method:
static IEnumerable<int> RandomNumbersBetween(int min, int max)
{
int availableNumbers = (max - min) + 1 ;
int yieldedNumbers = 0;
Random rand = new Random();
Dictionary<int, object> used = new Dictionary<int, object>();
while (true)
{
int n = rand.Next(min, max+1); //Random.Next max value is exclusive, so add one
if (!used.ContainsKey(n))
{
yield return n;
used.Add(n, null);
if (++yieldedNumbers == availableNumbers)
yield break;
}
}
}
Because it returns IEnumerable, you can use it with LINQ and IEnumerable extension methods:
RandomNumbersBetween(0, 20).Take(10)
Or maybe take odd numbers only:
RandomNumbersBetween(1, 1000).Where(i => i%2 == 1).Take(100)
Et cetera.
Edit:
Note that this solution has terrible performance characteristics if you are trying to generate a full set of random numbers between min
and max
.
However it works efficiently if you want to generate, say 10 random numbers between 0 and 20, or even better, between 0 and 1000.
In worst-case scenario it can also take (max - min)
space.