First let's examine the example and we can see that there is a pattern here

The first row turns into the last column

The second row turns into the second-last column

And such that

And there are two square cycles which are

// first cycle 1 2 3 4 5 6 7 8 9 10 11 1213 14 15 16

// second cycle1 2 3 45 6 7 8 9 10 11 1213 14 15 16

Since this is a 2D array, so obviously we will need one iteration inside another. The question here is “What are the range for each loop?” and “What are we going to implement in each loop cycle?”. Basically we have

Therefore, we can swap 4 numbers in a single round of loops. We could also come to a deduction that x will definitely smaller than n but how small exactly is it to n?. Plausible thought is that x = n / 2 but what if n is an odd number? Well we can round it up, yet a question arise, should we round it up or round it down? Let’s figure it out by trying on a 3 x 3 matrix

1 2 34 5 67 8 9

n = 3;x = n / 2 = 1.5; // should x be 1 or 1.5 ?

(i, j) = (0, 0)1 2 34 5 67 8 9

(i, j) = (0, 1)1 2 34 5 67 8 9

In this example, we know that i would not make it to the second row, so we might conclude that x = Math.floor(n / 2) . Now we have figured out x in the first iteration. Let’s move on with y in the second loop. Should j run from 0 to n – 1? Let’s try out some more examples for our first matrix.

(i, j) = (0, 2)13 9 5 114 6 7 215 10 11 316 12 8 4

(i, j) = (0, 3) // this position is already swapped

Our current matrix13 9 5 114 6 7 215 10 11 316 12 8 4

Now, we know that y < n – 1 . By the moment we finish the loop for the first row, the first cycle has already been swapped, so it would not make any sense if we continue to have j run from 0 and it would also not a good idea if we run j to the last column(n – 1) as well because it is going to mess up our first cycle. Therefore, j obviously has some correlation with i. Let’s continue our swapping with the second row in the example.

(i, j) = (1, 0) // this would mess up our first cycle => definite not let j run from j.

(i, j) = (1, 1)13 9 5 114 6 7 215 10 11 316 12 8 4

will turn into 13 9 5 114 10 6 215 11 7 316 12 8 4

We can see that j is likely to run from i to n-1-i. Since we have figured out the range and the implementation, we have wrap up our programming