Note that there are some explanatory texts on larger screens.

plurals
  1. PORotating a 2-d array by 90 degrees
    primarykey
    data
    text
    <p>A frequent question that props up during array manipulation exercises is to rotate a two dimensional array by 90 degrees. There are a few SO posts that answer how to do it in a variety of programming languages. My question is to clarify one of the answers that is out there and explore what sort of thought-process is required in order to get to the answer in an organic manner.</p> <p>The solution to this problem that I found goes as follows:</p> <pre><code>public static void rotate(int[][] matrix,int n) { for( layer = 0;layer &lt; n/2;++layer){ int first = layer; int last = n -1 - layer; for(int i = first;i&lt;last;++i){ int offset = i - first; int top = matrix[first][i]; matrix[first][i] = matrix[last-offset][first]; matrix[last-offset][first] = matrix[last][last-offset]; matrix[last][last-offset] = matrix[i][last]; matrix[i][last] = top; } } } </code></pre> <p>I have somewhat of an idea what the code above is trying to do, it is swapping out the extremities/corners by doing a four-way swap and doing the same for the other cells separated by some offset.</p> <p>Stepping through this code I know it works, what I do not get is the mathematical basis for the above given algorithm. What is the rationale behind the 'layer','first','last' and the offset?</p> <p>How did 'last' turn out to be <code>n-1-layer</code>? Why is the offset <code>i-first</code>? What is the offset in the first place?</p> <p>If somebody could explain the genesis of this algorithm and step me through the thought process to come up with the solution, that will be great.</p> <p>Thanks</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload