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;
}

Generics Array Helper

Rather than

ObjectWithReallyLongName [] array = new ObjectWithReallyLongName [] { new ObjectWithReallyLongName(...), ... }

We can use generics to create a function:

public T[] Array<T> ( params T[] array )
{
return array;
}

used

ObjectWithReallyLongName [] array = Array(new ObjectWithReallyLongName(...), ...);

Seems to read better too.