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:
This looks like an adaptation of Sattolo's Algorithm a variation on the Fisher Yates algorithm.
Nice and Easy
Thanks
Alfes
really thanks a lot for your effort
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);
Post a Comment