51. Randomize items

To randomize the items in an array, loop through the items. For each position i, pick a random position j with j ≥ i and swap items i and j.

After you swap an item into position i, you don't need to consider moving that item again later. This algorithm puts each item in any given position with an equal probability, at least as long as the random number generator is reasonably random.

The following code shows this algorithm implemented as a generic array extension method:

// Randomize the array in place.
public static void Randomize<T>(this T[] values)
{
int numItems = values.Length;

// Pick a random item for each position.
for (int i = 0; i < numItems - 1; i++)
{
// Pick a later item to swap into position i.
int j = Rand.Next(i, numItems);

// Swap items i and j.
T temp = values[i];
values[i] = values[j];
values[j] = temp;
}
}

This code simply follows the algorithm. The exact same code also works for a generic list of items. The only difference is that the array method uses the array's Length property to get the number of items while the list version uses the list's Count property.

Using the extension methods is easy. The following code shows how the RandomizeItems example solution randomizes its FirstNames array and LastNames list:

FirstNames.Randomize();
LastNames.Randomize();

Download the RandomizeItems example solution to see additional details.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset