commit beb42f5f4e4b11f885a738876978b067607b8840
parent d6ae2c784752671804624e8259d52ed6e6208956
Author: Martin Ashby <martin@ashbysoft.com>
Date: Tue, 3 Dec 2024 23:12:04 +0000
Day3 pt2
Diffstat:
3 files changed, 31 insertions(+), 2 deletions(-)
diff --git a/day3_sample2.txt b/day3_sample2.txt
@@ -0,0 +1 @@
+xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))
+\ No newline at end of file
diff --git a/src/main/scala/Day3.scala b/src/main/scala/Day3.scala
@@ -3,6 +3,33 @@ def day3_pt1(input: Iterator[String]): Int =
List.range(0, line.size)
.flatMap(n => try_mul(line.substring(n)))
.sum
+
+def day3_pt2(input: Iterator[String]): Int =
+ val line = input.next()
+ val (_, res) = List.range(0, line.size)
+ .foldLeft[(Boolean,Int)]((true, 0)) { (z: (Boolean, Int), n: Int) =>
+ val (enabled, sum) = z
+ val l1 = line.substring(n)
+ if enabled then
+ if try_dont(l1) then
+ (false, sum)
+ else
+ (true, sum + try_mul(line.substring(n)).getOrElse(0))
+ else
+ if try_do(l1) then
+ (true, sum)
+ else
+ (false, sum)
+ }
+ res
+
+
+def try_do(s: String): Boolean =
+ return s.startsWith("do()")
+
+def try_dont(s: String): Boolean =
+ return s.startsWith("don't()")
+
def try_mul(s: String): Option[Int] =
if s.startsWith("mul(") then
val ix = s.indexOf(")")
diff --git a/src/main/scala/Main.scala b/src/main/scala/Main.scala
@@ -1,2 +1,2 @@
@main def run(): Unit =
- println(day3_pt1(scala.io.Source.fromFile("day3.txt").getLines()))
-\ No newline at end of file
+ println(day3_pt2(scala.io.Source.fromFile("day3.txt").getLines()))
+\ No newline at end of file