Title: Randomize two-dimensional arrays in C#
This example uses the following extension method to randomize two-dimensional arrays.
// Randomize a 2D array.
public static void Randomize<T>(this T[,] values)
// Get the dimensions.
int num_rows = values.GetUpperBound(0) + 1;
int num_cols = values.GetUpperBound(1) + 1;
int num_cells = num_rows * num_cols;
// Randomize the array.
Random rand = new Random();
for (int i = 0; i < num_cells - 1; i++)
// Pick a random cell between i and the end of the array.
int j = rand.Next(i, num_cells);
// Convert to row/column indexes.
int row_i = i / num_cols;
int col_i = i % num_cols;
int row_j = j / num_cols;
int col_j = j % num_cols;
// Swap cells i and j.
T temp = values[row_i, col_i];
values[row_i, col_i] = values[row_j, col_j];
values[row_j, col_j] = temp;
To randomize two-dimensional arrays, the code starts by getting the number of rows and columns in the array, and by calculating the total number of items contained in the array. It then loops through all of the cells in the array numbered 0 through the number of items minus 1. For example, if the array has 20 items, then the loop runs from 0 to 19.
For each index i in this loop, the code picks a random index j greater than or equal to i. The code then swaps the items at indexes i and j.
The only trick here is calculating the row and column for the indexes i and j. To find the row, the code divides the index by the number of columns in each row. Because all of the values in the calculation are integers, the division is integer division so the the result is truncated. To find the column, the code takes the index mod the number of columns.
For example, suppose the array has 4 rows and 5 columns and consider index i = 13. Then i / num_cols = 13 / 5 = 2 and i % num_cols = 13 % 5 = 3, so the row is 2 and the column is 3. If you draw out such an array and number its entries, you'll find that this works out (if you remember that the index i and the row and column indexes all start with 0).
Download the example to experiment with it and to see additional details.