commit 0d618af316e2b6af81063c5ec4d3763ffbfc2c14
parent 70032b46a6ca37ccb33527568acc5efa9765fad6
Author: Martin Ashby <martin@ashbysoft.com>
Date: Mon, 9 Dec 2024 06:42:34 +0000
Day5 pt2
Diffstat:
2 files changed, 20 insertions(+), 6 deletions(-)
diff --git a/src/main/scala/Day5.scala b/src/main/scala/Day5.scala
@@ -1,4 +1,19 @@
def day5_pt1(input: Iterator[String]): Int =
+ val (rules, updates) = parse_input(input)
+ updates
+ .filter(l => l.sliding(2).forall(ll => rules.contains((ll(0), ll(1)))))
+ .map(l => l(l.size / 2))
+ .sum
+
+def day5_pt2(input: Iterator[String]): Int =
+ val (rules, updates) = parse_input(input)
+ updates
+ .filter(l => !(l.sliding(2).forall(ll => rules.contains((ll(0), ll(1))))))
+ .map(lst => lst.sortWith((a, b) => rules.contains((a, b))))
+ .map(l => l(l.size / 2))
+ .sum
+
+def parse_input(input: Iterator[String]): (List[(Int,Int)], List[List[Int]]) =
val lst = input.toList
val ix = lst.indexOf("")
val rulesStrs = lst.slice(0, ix)
@@ -7,7 +22,5 @@ def day5_pt1(input: Iterator[String]): Int =
val a = s.split("\\|").map(ss => Integer.parseInt(ss))
(a(0), a(1))
})
- updatesStrs.map(s => s.split(",").map(s => Integer.parseInt(s)).toList)
- .filter(l => l.sliding(2).forall(ll => rules.contains((ll(0), ll(1)))))
- .map(l => l(l.size / 2))
- .sum
+ val updates = updatesStrs.map(s => s.split(",").map(s => Integer.parseInt(s)).toList)
+ return (rules, updates)
+\ No newline at end of file
diff --git a/src/main/scala/Main.scala b/src/main/scala/Main.scala
@@ -1,2 +1,2 @@
@main def run(): Unit =
- println(day5_pt1(scala.io.Source.fromFile("day5.txt").getLines()))
-\ No newline at end of file
+ println(day5_pt2(scala.io.Source.fromFile("day5.txt").getLines()))
+\ No newline at end of file