|
| 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