Created
February 25, 2016 12:51
-
-
Save polyglotpiglet/6d10d7b69ecdbe5da5e4 to your computer and use it in GitHub Desktop.
Matrix rotation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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
rotate90
could you expand the (_) to be a full expression? And why not you use transpose function in scala direct?rotateMinus90
Can we change that to be more functional why without for loop?