Skip to content

Instantly share code, notes, and snippets.

@polyglotpiglet
Created February 25, 2016 12:51
Show Gist options
  • Save polyglotpiglet/6d10d7b69ecdbe5da5e4 to your computer and use it in GitHub Desktop.
Save polyglotpiglet/6d10d7b69ecdbe5da5e4 to your computer and use it in GitHub Desktop.
Matrix rotation
object Rotation extends App {
val matrix = Array(Array(1,2), Array(3,4), Array(5,6))
print(matrix)
print(transpose(matrix))
print(rotate90(matrix))
print(rotateMinus90(matrix))
def transpose(matrix: Array[Array[Int]]): Array[Array[Int]] = {
matrix.head.indices.map(i => matrix.map(_(i))).toArray
}
def rotate90(matrix: Array[Array[Int]]): Array[Array[Int]] = {
transpose(matrix).map(_.reverse)
}
def rotateMinus90(matrix: Array[Array[Int]]): Array[Array[Int]] = {
val t = transpose(matrix)
t.head.indices.foreach { i =>
(0 until (t.length/2)).foreach { j =>
val temp = t(j)(i)
t(j)(i) = t(t.length - j - 1)(i)
t(t.length - j - 1)(i) = temp
}
}
t
}
def print(matrix: Array[Array[Int]]): Unit = {
matrix.foreach(r => println(r.mkString(" ")))
println()
}
}
@MoustafaAMahmoud
Copy link

I was trying to solve this problem from Cracking coding interview book and your solution is very easy and logical. But I have two questions

  • Function rotate90 could you expand the (_) to be a full expression? And why not you use transpose function in scala direct?
  • Function rotateMinus90 Can we change that to be more functional why without for loop?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment