# How to switch two columns in a 2 dimensional array?

I am writing a Sudoku code in Java.

I already wrote a code, but instead of columns, rows are switched!

``````int[] tempField = array2D[myFirstCol_toSwitch];
array2D[myFirstCol_toSwitch] = array2D[mySecondCol_toSwitch];
array2D[mySecondCol_toSwitch] = tempField;
``````

In order to generate a Sudoku board I need to swap columns randomly.

On

The entries of a column are distributed across all the rows, one item per row. So in order to swap two columns, you have to loop through all the rows and swap the appropriate items in each row, like this:

``````// ints c1 and c2 are the indices of the columns to be swapped
for (int[] row : array2d){
{
int t = row[c1];
row[c1] = row[c2];
row[c2] = t;
}
``````
On

The "rows" and "columns" of a 2D Java array depend on your perspective; i.e. how you are mentally mapping the array into vertical and horizontal.

However, if what you are currently doing in your example is switching the "rows" (per your mental model) then the way to switch "columns" is to iterate over the individual elements; e.g. something like this:

``````for (int i = 0; i < array2D; i++) {
int tempField = array2D[i][myFirstCol_toSwitch];
array2D[i][myFirstCol_toSwitch] = array2D[i][mySecondCol_toSwitch];
array2D[i][mySecondCol_toSwitch] = tempField;
}
``````

This can be written in other ways that are (arguably) neater. I have chosen this way to make it clear what actually needs to happen to transpose the two columns.