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,
Test cases in Scala
Algorithm in Scala
18 lines of Scala (compatible versions 2.13 & 3.0), showing how concise Scala can be!
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)
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 in Scala lets you quickly identify what you are looking for in a data, and also extract it.