# Scala algorithm: Rotate a matrix by 90 degrees clockwise

Published , last updated

## Algorithm goal

Note: the layout of the page might show differently from normal.

Rotate a matrix by 90 degrees, ie what was the first row going left-to-right becomes the last column top-to-bottom. For example,

1 | 2 |

3 | 4 |

Becomes:

3 | 1 |

4 | 2 |

## Explanation

There are 2 key ways to represent a matrix: with a Map[Index, T], and with a Vector[Vector[T]] (similar to Array[Array[T]]). In the first case, the approach is to think about how to remap from one index to another, and in the second case, the approach is to think about how we can transform the data itself - for example, in the upcoming algorithm ReshapeMatrix, we use the Vector[Vector[T]] approach because the initial representation makes it easier to transform to the target one.

In the case of this problem, a rotation means that for each element, the new y is x, and the x depends on y (best advice is to see how each index maps to another index). (this is Â© from www.scala-algorithms.com)

### Scala specifics

The height is computed by simply finding the highest y-value. To compute it, we use a lazy val, as if we did a val, and the input were empty, there could be an empty list on which we cannot do a .max operation without a runtime exception. Height is only requested when there are elements, so we do not get a runtime exception when there are elements.

## Scala concepts & Hints

### Pattern Matching

Pattern matching in Scala lets you quickly identify what you are looking for in a data, and also extract it.

## Algorithm in Scala

19 lines of Scala (version 2.13), showing how concise Scala can be!

## Test cases in Scala

```
assert(rotateMatrix(Map.empty) == Map.empty)
assert(
rotateMatrix(Map(MatrixIndex(1, 1) -> 1)) == Map(MatrixIndex(1, 1) -> 1)
)
assert(
rotateMatrix(
Map(
MatrixIndex(y = 1, x = 1) -> 1,
MatrixIndex(y = 1, x = 2) -> 2,
MatrixIndex(y = 2, x = 1) -> 3,
MatrixIndex(y = 2, x = 2) -> 4
)
) == Map(
MatrixIndex(y = 1, x = 1) -> 3,
MatrixIndex(y = 1, x = 2) -> 1,
MatrixIndex(y = 2, x = 1) -> 4,
MatrixIndex(y = 2, x = 2) -> 2
)
)
assert(
rotateMatrix(
Map(
MatrixIndex(y = 1, x = 1) -> 1,
MatrixIndex(y = 1, x = 2) -> 2,
MatrixIndex(y = 1, x = 3) -> 3,
MatrixIndex(y = 2, x = 1) -> 4,
MatrixIndex(y = 2, x = 2) -> 5,
MatrixIndex(y = 2, x = 3) -> 6
)
) == Map(
MatrixIndex(y = 1, x = 1) -> 4,
MatrixIndex(y = 1, x = 2) -> 1,
MatrixIndex(y = 2, x = 1) -> 5,
MatrixIndex(y = 2, x = 2) -> 2,
MatrixIndex(y = 3, x = 1) -> 6,
MatrixIndex(y = 3, x = 2) -> 3
)
)
```