# Randomizing Order of elements in a Rectangular Array

I have a 4,4 rectangular array and after i load the elements into the array i would like to randomize the order of the elements, I am using C# how would i go about doing this?

You need any shuffling algorithm. The basic one is just to pick two random indexes and swap the values in them. The more iterations you take, the more it’ll be shuffled.

At first I didn’t want to give you code, but I changed my mind somewhat and here’s some code that doesn’t compile but is easy to fix.

This is how you can shuffle a two-dimensional (square) table in C#:

``````int[,] intTable = new int[dim,dim];
int maxIndex = dim*dim;
bool shuffledEnough = false;

while(!shuffledEnough){
//choose random indexes to swap
int firstIndex = Random(0,maxIndex);
int secondIndex = Random(0,maxIndex);

//store the value from the first index
int temp = arr[firstIndex/dim,firstIndex%dim];

//perform swap
arr[firstIndex/dim,firstIndex%dim] = arr[secondIndex/dim,secondIndex%dim];
arr[secondIndex/dim,secondIndex%dim] = temp;

//determine if there's been enough shuffling
shuffledEnough = Random.value < 0.05f;
}
``````