import scala.math.abs object Solution { // there are 8 possible 3x3 magic squares which use the range [1,9]: val magicSquares = Seq( Seq(Seq(2, 7, 6), Seq(9, 5, 1), Seq(4, 3, 8)), Seq(Seq(2, 9, 4), Seq(7, 5, 3), Seq(6, 1, 8)), Seq(Seq(4, 3, 8), Seq(9, 5, 1), Seq(2, 7, 6)), Seq(Seq(4, 9, 2), Seq(3, 5, 7), Seq(8, 1, 6)), Seq(Seq(6, 1, 8), Seq(7, 5, 3), Seq(2, 9, 4)), Seq(Seq(6, 7, 2), Seq(1, 5, 9), Seq(8, 3, 4)), Seq(Seq(8, 1, 6), Seq(3, 5, 7), Seq(4, 9, 2)), Seq(Seq(8, 3, 4), Seq(1, 5, 9), Seq(6, 7, 2))) def main (args: Array[String]) { val inputSquare = to2DArray(for (y<-0 until 3) yield readLine().split(" ").map(_.toInt)) println(magicSquares.map(differenceBetweenSquares(inputSquare)_).min) } def differenceBetweenSquares(i: Seq[Seq[Int]])(j: Seq[Seq[Int]]): Int = { (for (x <- 0 until 3; y <- 0 until 3) yield abs(i(x)(y) - j(x)(y))).sum } /* * flip it so we are using the notation (x,y) starting with the bottom-right as the origin */ def to2DArray (arr: Seq[Array[Int]]): Seq[Seq[Int]] = { Seq( Seq(arr(2)(0), arr(2)(1), arr(2)(2)), Seq(arr(1)(0), arr(1)(1), arr(1)(2)), Seq(arr(0)(0), arr(0)(1), arr(0)(2))) } }