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 457cd7e commit 28d60b0
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 14 deletions.
44 changes: 32 additions & 12 deletions scala2/src/main/scala/jurisk/adventofcode/y2024/Advent19.scala
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
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 = Int
type N = Long

def parse(input: String): Input = {
val (stripes, towels) = input.split("\n\n").toList match {
Expand All @@ -18,22 +19,41 @@ object Advent19 {
Input(stripes, towels)
}

private def isValid(towel: String, stripes: List[String]): Boolean = {
if (towel.isEmpty) true
else {
stripes.exists { stripe =>
// println(s"Towel $towel, Stripe $stripe, Starts: ${towel.startsWith(stripe)}")
towel.startsWith(stripe) && isValid(towel.drop(stripe.length), stripes)
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
}
}
}

def part1(data: Input): N = {
data.towels.count(towel => isValid(towel, data.stripes))
data.towels.count(towel => ways(towel, data.stripes) > 0)
}

def part2(data: Input): N =
0
def part2(data: Input): N = {
lazy val waysMemoized = Memoize.memoize1(ways)

def ways(towel: String): N = {
if (towel.isEmpty) 1L
else {
data.stripes.map { stripe =>
if (towel.startsWith(stripe)) {
waysMemoized(towel.drop(stripe.length))
} else {
0L
}
}.sum
}
}

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

def parseFile(fileName: String): Input =
parse(readFileText(fileName))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@ class Advent19Spec extends AnyFreeSpec {

"part 2" - {
"test" in {
part2(testData) shouldEqual 0
part2(testData) shouldEqual 16
}

"real" in {
part2(realData) shouldEqual 0
part2(realData) shouldEqual 1100663950563322L
}
}
}

0 comments on commit 28d60b0

Please sign in to comment.