Tuesday, June 05, 2007

Shuffling a List in C#

Inspired by this post:

static Random random = new System.Random();
public static IList<T> Shuffle<T> ( IList<T> deck )
{
  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;
  }
}