0

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.

0

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I have incorporated your suggestion. It worked as I wanted. Thank you
I'm glad you solved your problem. Please accept the answer if it solves your problem.
1

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;
}

1 Comment

I see what it is mentally mapping as Stephan said, it is actually treated transposed by java. int grid[N][N] = {{0,0,0,0,2,0,0,0,0}, {0,0,3,0,0,0,2,0,5}, {0,0,0,0,0,0,0,9,0}, {0,0,0,0,0,0,5,0,0}, {0,0,0,0,0,0,0,0,3}, {0,7,0,4,0,0,0,0,0}, {0,2,0,0,0,0,0,0,0}, {7,0,9,0,0,0,4,0,8}, {1,0,0,0,5,0,0,0,0}}; here, the nested array, that I see as rows, in fact they are treated as column in java! Am I right?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.