If you want a series of random numbers drawn from a group of numbers not in sequence, with no repetition, then you can try this:
Random randomGenerator = new Random();
private List<int> selectRandomFrom = new List<int>
{
1, 24, 13, 12, 9, 3, 5, 8, 2, 499
};
private Dictionary<int,> nHits = new Dictionary<int,>();
private void TestRandomSelection()
{
foreach (var i in selectRandomFrom) nHits.Add(i, 0);
int lastRandomInt = -999;
int x = 0;
int numberOfReTries = 0;
for (int i = 0; i < 100000; i++)
{
while (true)
{
x = selectRandomFrom[randomGenerator.Next(0, selectRandomFrom.Count)];
if (x != lastRandomInt)
{
lastRandomInt = x;
break;
}
else
{
numberOfReTries++;
}
}
nHits[x] ++;
}
foreach (var itemHit in nHits)
{
Console.WriteLine("item:\t{0}\t\tnumber of hits:\t{1}", itemHit.Key, itemHit.Value );
}
Console.WriteLine();
Console.WriteLine("number of re-tries: {0}", numberOfReTries);
}
Here's the output of testing this example:
item: 1 number of hits: 10089
item: 24 number of hits: 9971
item: 13 number of hits: 9910
item: 12 number of hits: 9884
item: 9 number of hits: 10117
item: 3 number of hits: 9926
item: 5 number of hits: 9962
item: 8 number of hits: 10108
item: 2 number of hits: 10062
item: 499 number of hits: 9971
number of re-tries: 11236
Least number of selections: 9910; most selections: 10117.
This is an example of eliminating random selection repetitions
without having to copy a source list; I have not compared the performance of this technique to a similar example using the technique of removing items from a list with each selection, and, then, refreshing the list by copying from a master-list as necessary.
Obviously, as the source list is longer: then the number of retries as a proportion of the total selection will decrease. Doubling the number of items in the source list to #20 resulted in a more than 50% decrease in retries. Reducing the number of items to #5, roughly doubled the number of retries compared to using #10 items. A few tests strongly suggest the number of retries is
linearly related to the number of items in the source list.
My tests (using Stopwatch) indicate using the technique shown here averages over 100% faster than using an approach where you remove items from the source list, and re-initialize the source list as needed, for both large and small source lists. (Code on request)