Skip to content

Commit 3cd3bbd

Browse files
committed
Add day 19 code.
1 parent ff8014d commit 3cd3bbd

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

2024/src/day19.scala

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package day19
2+
3+
import scala.collection.mutable
4+
5+
import locations.Directory.currentDir
6+
import inputs.Input.loadFileSync
7+
8+
@main def part1: Unit =
9+
println(s"The solution is ${part1(loadInput())}")
10+
11+
@main def part2: Unit =
12+
println(s"The solution is ${part2(loadInput())}")
13+
14+
def loadInput(): String = loadFileSync(s"$currentDir/../input/day19")
15+
16+
type Towel = String
17+
type Pattern = String
18+
19+
def parse(input: String): (List[Towel], List[Pattern]) =
20+
val Array(towelsString, patternsString) = input.split("\n\n")
21+
val towels = towelsString.split(", ").toList
22+
val patterns = patternsString.split("\n").toList
23+
(towels, patterns)
24+
25+
def part1(input: String): Int =
26+
val (towels, patterns) = parse(input)
27+
val possiblePatterns = patterns.filter(isPossible(towels))
28+
possiblePatterns.size
29+
30+
def isPossible(towels: List[Towel])(pattern: Pattern): Boolean =
31+
val regex = towels.mkString("^(", "|", ")*$").r
32+
regex.matches(pattern)
33+
34+
def part2(input: String): Long =
35+
val (towels, patterns) = parse(input)
36+
countOptions(towels, patterns)
37+
38+
def countOptions(towels: List[Towel], patterns: List[Pattern]): Long =
39+
val cache = mutable.Map.empty[Pattern, Long]
40+
41+
def loop(pattern: Pattern): Long =
42+
cache.getOrElseUpdate(
43+
pattern,
44+
towels
45+
.collect {
46+
case towel if pattern.startsWith(towel) =>
47+
pattern.drop(towel.length)
48+
}
49+
.map { remainingPattern =>
50+
if (remainingPattern.isEmpty) 1
51+
else loop(remainingPattern)
52+
}
53+
.sum
54+
)
55+
56+
patterns.map(loop).sum

0 commit comments

Comments
 (0)