# Interview Questions – Turn a matrix clockwise in Scala

For a given matrix, rotate elements clockwise.
Examples:

``````entrance
1 2 3
4 5 6
7 8 9

Output:
4 1 2
7 5 3
8 9 6

Entrance:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

Output:
5 1 2 3
9 10 6 4
13 11 7 8
14 15 16 12
``````

Scala implementation is below. I feel like I do not need a predefined rotated matrix (which I fill with -1), and I can build it during my recursive calls, but I can not.
Thank you in advance for helping me with this.

``````import scala.util.Random

object MatrixRotate extends App {

def getCol (c: int, m: array)[Array[Int]]): Seq[Int] = (0 to (m (0). Length - 1)) Map (r => m (r) (c))
def getRow (r: int, m: array)[Array[Int]]): Seq[Int] = m (r) · zuSeq
def innerMatrix (m: Array[Array[Int]]): Array[Array[Int]]= {
if (m.length == 0) Array.empt
miscellaneous
val row = m.length - 1
Val Cols = m (0) · length - 1

(1 to rows) .map {r =>
(1 to columns) .map {c =>
m (r) (c)
} .toArray
} .toArray
}
}

val rotatedMatrix = Array.Fill (6) (Array.Fill (6) (-1))
def turnByOne (m: Array)[Array[Int]], startRow: Int, startCol: Int,
endRow: Int, endCol: Int): Unit = {
m.size match {
Case 0 =>
case _ =>
getRow (0, m) match {
Case zero =>
case x => x.init.zipWithIndex foreach {case (e, index) => rotatedMatrix (startRow) (startCol + index + 1) = e}
}
getCol (m (0) .length - 1, m) match {
Case zero =>
case x => x.init.zipWithIndex foreach {case (e, index) => rotatedMatrix (startRow + index + 1) (endCol) = e}
}
getRow (m.length - 1, m) match {
Case x :: Nil =>
case x => x.tail.zipWithIndex foreach {case (e, index) => rotatedMatrix (endRow) (startCol + index) = e}
}
getCol (0, m) match {
Case x :: Nil =>
case x => x.tail.zipWithIndex foreach {case (e, index) => rotatedMatrix (startRow + index) (startCol) = e}
}
rotateByOne (innerMatrix (m), startRow + 1, startCol + 1, endRow - 1, endCol - 1)
}

}

val matrix = Array.fill (6) (Array.fill (6) (Random.nextInt (100)))
Matrix foreach (row => println (row.mkString (",")))

println ("----------")

Rotate ByOne (Matrix, 0, 0, 5, 5)
rotatedMatrix foreach (row => println (row.mkString (",")))
}
``````