I have read an article about various shuffle algorithms over at Coding Horror. I have seen that somewhere people have done this to shuffle a list:
var r = ne
Looking for an algorithm? You can use my ShuffleList
class:
class ShuffleList : List
{
public void Shuffle()
{
Random random = new Random();
for (int count = Count; count > 0; count--)
{
int i = random.Next(count);
Add(this[i]);
RemoveAt(i);
}
}
}
Then, use it like this:
ShuffleList list = new ShuffleList();
// Add elements to your list.
list.Shuffle();
Let's take an initial sorted list of the 5 first integers: { 0, 1, 2, 3, 4 }
.
The method starts by counting the nubmer of elements and calls it count
. Then, with count
decreasing on each step, it takes a random number between 0
and count
and moves it to the end of the list.
In the following step-by-step example, the items that could be moved are italic, the selected item is bold:
0 1 2 3 4
0 1 2 3 4
0 1 2 4 3
0 1 2 4 3
1 2 4 3 0
1 2 4 3 0
1 2 3 0 4
1 2 3 0 4
2 3 0 4 1
2 3 0 4 1
3 0 4 1 2