Friday 12 October 2007

Shuffling a List in C#

Fixed this post:

public static readonly Random random = new Random();
public static IList<T> Shuffle<T>(IList<T> toShuffle)
{
List<T> deck = new List<T> ( toShuffle );
int N = deck.Count;

for (int i = 0; i < N; ++i )
{
int r = i + (int)(random.Next(N - i));
T t = deck[r];
deck[r] = deck[i];
deck[i] = t;
}

return deck;
}

1 comment:

Grumpy Grandma said...

LOL! This was linked as a version that worked, but it doesn't!

No biggie, just funny.