Skip to content

Commit 8e9fa4a

Browse files
committed
Solve 2024 day 19 part 2
1 parent 919da6d commit 8e9fa4a

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

src/main/scala/eu/sim642/adventofcode2024/Day19.scala

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package eu.sim642.adventofcode2024
22

3+
import scala.collection.mutable
34
import scala.util.matching.Regex
45

56
object Day19 {
@@ -18,6 +19,28 @@ object Day19 {
1819
input.designs.count(regex.matches)
1920
}
2021

22+
def countWays(patterns: Seq[Towel], design: Towel): Long = {
23+
val memo = mutable.Map.empty[Int, Long]
24+
25+
def helper(i: Int): Long = {
26+
memo.getOrElseUpdate(i, {
27+
if (i == design.size)
28+
1
29+
else {
30+
(for {
31+
pattern <- patterns
32+
if design.startsWith(pattern, i)
33+
} yield helper(i + pattern.size)).sum
34+
}
35+
})
36+
}
37+
38+
helper(0)
39+
}
40+
41+
def sumDesignWays(input: Input): Long =
42+
input.designs.map(countWays(input.patterns, _)).sum
43+
2144
def parsePatterns(s: String): Seq[Towel] = s.split(", ").toSeq
2245

2346
def parseDesigns(s: String): Seq[Towel] = s.linesIterator.toSeq
@@ -30,5 +53,8 @@ object Day19 {
3053

3154
def main(args: Array[String]): Unit = {
3255
println(countPossibleDesigns(parseInput(input)))
56+
println(sumDesignWays(parseInput(input)))
57+
58+
// part 2: 1006410103498494 - too high (had i >= design.size - 1 in countWays)
3359
}
3460
}

src/test/scala/eu/sim642/adventofcode2024/Day19Test.scala

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,4 +24,12 @@ class Day19Test extends AnyFunSuite {
2424
test("Part 1 input answer") {
2525
assert(countPossibleDesigns(parseInput(input)) == 226)
2626
}
27+
28+
test("Part 2 examples") {
29+
assert(sumDesignWays(parseInput(exampleInput)) == 16)
30+
}
31+
32+
test("Part 2 input answer") {
33+
assert(sumDesignWays(parseInput(input)) == 601201576113503L)
34+
}
2735
}

0 commit comments

Comments
 (0)