Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 3c45b7a

Browse files
authored
Merge pull request #818 from AvaPL/day19-code
Add 2024 day 19 code
2 parents ff8014d + 336e727 commit 3c45b7a

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

‎2024/src/day19.scala‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
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+
patterns.count(isPossible(towels))
28+
29+
def isPossible(towels: List[Towel])(pattern: Pattern): Boolean =
30+
val regex = towels.mkString("^(", "|", ")*$").r
31+
regex.matches(pattern)
32+
33+
def part2(input: String): Long =
34+
val (towels, patterns) = parse(input)
35+
countOptions(towels, patterns)
36+
37+
def countOptions(towels: List[Towel], patterns: List[Pattern]): Long =
38+
val cache = mutable.Map.empty[Pattern, Long]
39+
40+
def loop(pattern: Pattern): Long =
41+
cache.getOrElseUpdate(
42+
pattern,
43+
towels
44+
.collect {
45+
case towel if pattern.startsWith(towel) =>
46+
pattern.drop(towel.length)
47+
}
48+
.map { remainingPattern =>
49+
if (remainingPattern.isEmpty) 1
50+
else loop(remainingPattern)
51+
}
52+
.sum
53+
)
54+
55+
patterns.map(loop).sum

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /