Objective

Rotate a given matrix clockwise by 90°.

Difficulty

Average

Description

In the world of matrices, a square matrix is an ::n \times n:: matrix, i.e. it has ::n:: rows and ::n:: columns.

Shown below are a couple of square matrices, along with their dimensions:

::\begin{bmatrix} 1 & 4 \\ 10 & 2 \end{bmatrix}::
::2 \times 2::
::\begin{bmatrix} 1 & 5 & 2 \\ 0 & 6 & 3 \\ 6 & 15 & 1 \end{bmatrix}::
::3 \times 3::
::\begin{bmatrix} 1 & 9 & 0 & 2 \\ -51 & 2 & 3 & 2 \\ -1 & 16 & -5 & 2 \\ 1 & 90 & 10 & 6 \end{bmatrix}::
::4 \times 4::

When dealing with square matrices, matrix rotation is a possible operation.

As the name suggests, matrix rotation reorders items of the matrix such that the matrix seems to literally have been rotated.

The rotation angle is usually ::90^{\circ}::, but it can be any multiple of ::90::, for e.g. ::180::, ::270::, ::-90::, etc.

The sign of the angle determines the direction of rotation: positive means clockwise and negative means counter-clockwise. For e.g. ::90^{\circ}:: means to rotate the matrix by ::90^{\circ}:: clockwise, while ::-90^{\circ}:: means to rotate the matrix by ::90^{\circ}:: counter-clockwise.

For instance, if we were to rotate the matrix below by ::90^{\circ}::,

::\begin{bmatrix} 1 & 4 \\ 10 & 2 \end{bmatrix}::

then we'd get the following configuration:

::\begin{bmatrix} 10 & 1 \\ 2 & 4 \end{bmatrix}::

Here's a visual animation to help you see the rotation much better:

1
4
10
2

As you can see, at the end of the rotation, the positions of the elements of the matrix have effectively been changed. Neither is any new element added, nor is any existing element deleted — the rotation is merely a means of repositioning items in the matrix.

Now, if we see this rotation operation from the perspective of a programmer, we could see a pattern it. That is, we could discretely list out the steps to be taken in order to rotate a matrix by a given angle (a multiple of ::90::) using a computer program.

In this exercise, you have to create a function rotate_by_90() that rotates a given matrix by ::90^{\circ}::.

The function should have the following signature:

<?php

function rotate_by_90($matrix) {
   // Your code goes here
}

Moreover, it should mutate the original matrix passed to it and also return it back, obviously in its rotated configuration.

Shown below are a couple of examples of how rotate_by_90() should behave:

<?php

/* Functions defined here... */

$a = [ [1, 4], [10, 2] ];
print_matrix(rotate_by_90($a));
echo "\n";
print_matrix($a);

echo "\n";

print_matrix(rotate_by_90(rotate_by_90($a)));
echo "\n";
print_matrix($a);
10 1 2 4 10 1 2 4 4 2 1 10 4 2 1 10

The print_matrix() function used here is defined in PHP Multidimensional Arrays — print_matrix().