Problem:
Given a square or rectangular matrix, print its element in spiral order.
For example, if input matrix is this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Output should be:
1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
This code assumes a matrix of 6X5. I do feel it can look more elegant or functional. I want to get rid of vars.
import scala.util.Random
object MatrixSpiral extends App {
val matrix = Array.fill(6)(Array.fill(5)(Random.nextInt(10)))
matrix foreach (row => println(row.mkString(",")))
var rows = 6
var cols = 5
var r = 0
var c = 0
var startR = 0
var startC = 0
println
while (r < rows && c < cols) {
for (i <- c until cols) {
c = i; print(matrix(r)(i) + " ")
}
r += 1
for (j <- r until rows) {
r = j; print(matrix(j)(c) + " ")
}
c -= 1
for (k <- c to startC by -1) {
c = k; print(matrix(r)(k) + " ")
}
r -= 1
for (l <- r to startR + 1 by -1) {
r = l; print(matrix(l)(c) + " ")
}
rows -= 1
cols -= 1
c += 1
startR = r
startC = c
}
}