Skip to content

Commit

Permalink
2024-19 Scala 2
Browse files Browse the repository at this point in the history
  • Loading branch information
jurisk committed Dec 19, 2024
1 parent 28d60b0 commit 847530e
Showing 1 changed file with 13 additions and 25 deletions.
38 changes: 13 additions & 25 deletions scala2/src/main/scala/jurisk/adventofcode/y2024/Advent19.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,44 +2,27 @@ package jurisk.adventofcode.y2024

import jurisk.utils.FileInput._
import jurisk.utils.Memoize
import jurisk.utils.Parsing.StringOps

object Advent19 {
final case class Input(
stripes: List[String],
towels: List[String],
)
type N = Long
type N = Long

def parse(input: String): Input = {
val (stripes, towels) = input.split("\n\n").toList match {
case List(stripes, towels) => (stripes.split(", ").toList, towels.linesIterator.toList)
case _ => throw new Exception("Invalid input")
case List(stripes, towels) =>
(stripes.split(", ").toList, towels.linesIterator.toList)
case _ => throw new Exception("Invalid input")
}
Input(stripes, towels)
}

def part1(data: Input): N = {
def ways(towel: String, stripes: List[String]): N = {
if (towel.isEmpty) 1L
else {
stripes.map { stripe =>
if (towel.startsWith(stripe)) {
ways(towel.drop(stripe.length), stripes)
} else {
0L
}
}.sum
}
}

data.towels.count(towel => ways(towel, data.stripes) > 0)
}

def part2(data: Input): N = {
def solve(data: Input, countF: N => N): N = {
lazy val waysMemoized = Memoize.memoize1(ways)

def ways(towel: String): N = {
def ways(towel: String): N =
if (towel.isEmpty) 1L
else {
data.stripes.map { stripe =>
Expand All @@ -50,11 +33,16 @@ object Advent19 {
}
}.sum
}
}

data.towels.map(towel => waysMemoized(towel)).sum
data.towels.map(towel => countF(waysMemoized(towel))).sum
}

def part1(data: Input): N =
solve(data, _ min 1)

def part2(data: Input): N =
solve(data, identity)

def parseFile(fileName: String): Input =
parse(readFileText(fileName))

Expand Down

0 comments on commit 847530e

Please sign in to comment.