-
-
Save waynejo/cecb5c6db8f64ff6a381913434e227bc to your computer and use it in GitHub Desktop.
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
import java.io.FileInputStream | |
import scala.annotation.tailrec | |
import scala.io.StdIn | |
@tailrec | |
def buildAllDiffs(acc: Vector[Vector[Int]], values: Vector[Int]): Vector[Vector[Int]] = { | |
if values.forall(_ == 0) then | |
acc :+ values | |
else | |
val next = values.sliding(2).map { | |
pair => pair(1) - pair(0) | |
}.toVector | |
buildAllDiffs(acc :+ values, next) | |
} | |
def solve9_1(values: Vector[Vector[Int]]): Int = | |
values.map(values => { | |
buildAllDiffs(Vector.empty, values).reverse.foldLeft(0) { | |
case (acc, x) => acc + x.last | |
} | |
}).sum | |
def solve9_2(values: Vector[Vector[Int]]): Int = | |
values.map(values => { | |
buildAllDiffs(Vector.empty, values).reverse.foldLeft(0) { | |
case (acc, x) => x.head - acc | |
} | |
}).sum | |
@main def solve9(): Unit = | |
val in = new FileInputStream("example9-2.in") | |
System.setIn(in) | |
val inputs = Iterator.continually(StdIn.readLine()) | |
.takeWhile(line => null != line) | |
.map(_.split(" ").map(_.toInt).toVector) | |
.toVector | |
println(solve9_1(inputs)) | |
println(solve9_2(inputs)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment