Created
February 14, 2013 03:20
-
-
Save zerosum/4950355 to your computer and use it in GitHub Desktop.
Project Euler: Problem 81
This file contains hidden or 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
| package euler.zerosum | |
| import io.Source | |
| object Euler0081 { | |
| def main(args: Array[String]) { | |
| val f = Source.fromFile("matrix.txt") | |
| val matrix = f.getLines.foldRight(List(List(0)))((x, y) => | |
| x.split(",").toList.map(_.toInt) :: y | |
| ).init | |
| f.close() | |
| val l = slant(matrix, Nil, 0, matrix.length * 2 - 1) | |
| println(l.reduceRight(findMinimalPath(_,_)).head) | |
| } | |
| private def findMinimalPath(parents: List[Int], children: List[Int]): List[Int] = { | |
| val t = (parents.zipWithIndex, { | |
| if (parents.length < children.length) | |
| children.zipWithIndex | |
| else | |
| (children.head :: children ::: children.last :: Nil).zipWithIndex | |
| }) | |
| val p = t._1 | |
| val c = t._2 | |
| p.map(x => math.min(x._1 + c(x._2)._1, x._1 + c(x._2 + 1)._1)) | |
| } | |
| private def slant(matrix: List[List[Int]], slanted: List[List[Int]], ctr: Int, length: Int): List[List[Int]] = { | |
| if (ctr == length) { | |
| slanted | |
| } else { | |
| { | |
| if (ctr < matrix.length) { | |
| line(matrix, Nil, 0, ctr, 0) | |
| } else { | |
| val index = ctr - length / 2 | |
| line(matrix, Nil, index, ctr, index) | |
| } | |
| } :: slant(matrix, slanted, ctr + 1, length) | |
| } | |
| } | |
| private def line(matrix: List[List[Int]], lined: List[Int], index: Int, lineNo: Int, lim: Int): List[Int] = { | |
| matrix(index)(lineNo - index) :: { | |
| if (lineNo - index == lim) | |
| lined | |
| else | |
| line(matrix, lined, index + 1, lineNo, lim) | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment