@@ -2,33 +2,41 @@ package eu.sim642.adventofcode2024
22
33object Day3 {
44
5- private val mulRegex = """ mul\((\d{1,3}),(\d{1,3})\)""" .r
5+ trait Part {
6+ def sumMuls (s : String ): Int
7+ }
8+
9+ object Part1 extends Part {
10+ private val mulRegex = """ mul\((\d{1,3}),(\d{1,3})\)""" .r
611
7- def sumUncorruptedMuls (s : String ): Int = {
8- mulRegex.findAllMatchIn(s)
9- .map(m => m.group(1 ).toInt * m.group(2 ).toInt)
10- .sum
12+ override def sumMuls (s : String ): Int = {
13+ mulRegex.findAllMatchIn(s)
14+ .map(m => m.group(1 ).toInt * m.group(2 ).toInt)
15+ .sum
16+ }
1117 }
1218
13- private val mulRegex2 = """ mul\((\d{1,3}),(\d{1,3})\)|do(n't)?\(\)""" .r
14-
15- def sumUncorruptedMuls2 (s : String ): Int = {
16- mulRegex2.findAllMatchIn(s)
17- .foldLeft((true , 0 ))({ case ((enabled, sum), m) =>
18- (enabled, m.matched) match {
19- case (_, " do()" ) => (true , sum)
20- case (_, " don't()" ) => (false , sum)
21- case (true , _) => (enabled, sum + m.group(1 ).toInt * m.group(2 ).toInt)
22- case (false , _) => (enabled, sum)
23- }
24- })
25- ._2
19+ object Part2 extends Part {
20+ private val mulRegex = """ mul\((\d{1,3}),(\d{1,3})\)|do(n't)?\(\)""" .r
21+
22+ override def sumMuls (s : String ): Int = {
23+ mulRegex.findAllMatchIn(s)
24+ .foldLeft((true , 0 ))({ case ((enabled, sum), m) =>
25+ (enabled, m.matched) match {
26+ case (_, " do()" ) => (true , sum)
27+ case (_, " don't()" ) => (false , sum)
28+ case (true , _) => (enabled, sum + m.group(1 ).toInt * m.group(2 ).toInt)
29+ case (false , _) => (enabled, sum)
30+ }
31+ })
32+ ._2
33+ }
2634 }
2735
2836 lazy val input : String = scala.io.Source .fromInputStream(getClass.getResourceAsStream(" day3.txt" )).mkString.trim
2937
3038 def main (args : Array [String ]): Unit = {
31- println(sumUncorruptedMuls (input))
32- println(sumUncorruptedMuls2 (input))
39+ println(Part1 .sumMuls (input))
40+ println(Part2 .sumMuls (input))
3341 }
3442}
0 commit comments