Randomize the items in an array in C#
This example builds a Randomizer class. This class provides a generic Randomize method that randomizes an array containing any kind of data.
class RandomizerThe Randomize method is static so you can invoke it without creating an instance of the class. It first creates a Random object. Then for each position i in the array (except the last one), it picks a random item between position i and the end of the array, and then swaps the item in that position into position i. When it is finished, the array is randomized. Note that this is the easiest way to pick several random items from the array without duplication. To pick one item, you can simply use a Random object to pick an item. To pick several items, it's easiest to randomize the array and then just use the first several items. To see why this method randomizes the values uniformly, think about a number m somewhere in the array. We pick any random entry on the first pick so, assuming the random number generator is fair, there's a 1/N chance that m is picked on the first try for the first slot. Once placed, numbers are not moved so there's a 1/N chance that m lands in the first slot. There's a (N-1)/N chance that m isn't chosen for the first slot. When considering the second slot, we're picking out of only N - 1 items so there's a 1/(N-1) chance that we pick it for the second slot. Multiplying by the chance that it didn't land in the first slot already we get a [(N-1)/N] * [1/(N-1)] = 1/N chance overall that it lands in the second slot. Third slot? (N-1)/N * (N-2)/(N-1) * 1/(N-2) = 1/N. Etc.
{
public static void Randomize<T>(T[] items)
{
Random rand = new Random();
// For each spot in the array, pick
// a random item to swap into that spot.
for (int i = 0; i < items.Length - 1; i++)
{
int j = rand.Next(i, items.Length);
T temp = items[i];
items[i] = items[j];
items[j] = temp;
}
}
}



Comments