Skip to content

Commit

Permalink
feat(2024): day 07
Browse files Browse the repository at this point in the history
  • Loading branch information
scarf005 committed Dec 7, 2024
1 parent 224b7d7 commit b97ac74
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions 2024/day07.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package `2024`.day07

import prelude.*
import scala.annotation.tailrec

def digits(x: Long) = math.log10(x.toDouble).toInt + 1

extension (a: Long)
inline def ||(b: Long) = (a * math.pow(10, digits(b)) + b).toLong

extension [C <: Iterable, A](xs: C[A])
def orEmpty[B](f: C[A] => B)(els: => B) = if (xs.isEmpty) els else f(xs)

type Op = Long => Long => List[Long]

def getCombo(xs: List[Long], next: Op) =
@tailrec def go(xs: List[Long], acc: List[Long] = List()): List[Long] =
xs match
case Nil => acc
case x :: Nil => acc.flatMap(next(x))
case x :: ys => go(ys, acc.orEmpty(_.flatMap(next(x)))(List(x)))
go(xs)

def solve(xss: Vector[(Long, List[Long])], op: Op) =
xss.filter((target, xs) => getCombo(xs, op).exists(_ == target)).map(_._1).sum

@main def main() =
val input = readInput(this).getLines.collect { case s"$target: $xs" =>
(target.toLong, xs.split(" ").map(_.toLong).toList)
}.toVector

println(solve(input, (x) => (a) => List(a + x, a * x)))
println(solve(input, (x) => (a) => List(a + x, a * x, a || x)))

0 comments on commit b97ac74

Please sign in to comment.