## Objective

Rotate a given matrix clockwise by 90°.

Average

## Description

In the world of matrices, a square matrix is a $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 useful 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 determine 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 simply a change of the order of values.

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 rotateBy90() that rotates a given matrix by $90^{\circ}$.

The function has the following signature:

function rotateBy90(matrix) {
// your code goes here
}

It should mutate the original matrix array passed to it and then finally return it in its rotated configuration.

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

rotateBy90([[1, 4], [10, 2]])
[[10, 1], [2, 4]]
rotateBy90([])
[]