Friday, December 22, 2006

C#: Random selection of elements in a list, with no repeats

Following code snippet shows how we can randomize selection of element in a list in effective manner:

System.Collections.Generic.List intList = new System.Collections.Generic.List();
intList.Add(1);
intList.Add(2);
intList.Add(3);
intList.Add(4);
intList.Add(5);

int size = intList.Count;
while (size>0)
{
size--;
int index = (new Random()).Next(0,size);
int elem = intList[index];
intList[index] = intList[size];
Console.WriteLine(elem.ToString());
}

4 comments:

Unknown said...

This looks like an adaptation of Sattolo's Algorithm a variation on the Fisher Yates algorithm.

Alfes said...

Nice and Easy
Thanks
Alfes

Anonymous said...

really thanks a lot for your effort

Anonymous said...

Works nice, but I ran a few tests taking samples from the same collection of ten items and sometimes the samples were exactly the same as a previous one (sometimes 2 or 3 iterations later).

You can solve this if instead of creating a new instance of the random generator just create one outside the while code. It's also more efficient.

int index = r.Next(0, size);