Skip to content

Commit

Permalink
2023, 09
Browse files Browse the repository at this point in the history
  • Loading branch information
jurisk committed Dec 9, 2023
1 parent cbcb948 commit 8dfdf6e
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 12 deletions.
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
package jurisk.adventofcode.y2023

import jurisk.utils.CollectionOps.{EqIterableOps, IntegralIterableOps}
import jurisk.utils.CollectionOps.{EqIterableOps, IntegralSeqOps}
import jurisk.utils.FileInput._
import jurisk.utils.Parsing.StringOps

object Advent09 {
type N = Long
type Input = List[List[N]]

private def extrapolatedValue(list: Iterable[N]): N =
if (list.allEqual(0)) 0
else list.last + extrapolatedValue(list.differencesUnsafe)
private def extrapolatedValue(list: Seq[N]): N =
if (list.allEqual(0)) 0 else list.last + extrapolatedValue(list.differences)

def part1(input: Input): N = input.map(extrapolatedValue).sum
def part2(input: Input): N = part1(input.map(_.reverse))
Expand Down
12 changes: 4 additions & 8 deletions scala2/src/main/scala/jurisk/utils/CollectionOps.scala
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,10 @@ object CollectionOps {
seq.forall(_ === value)
}

implicit class IntegralIterableOps[N: Integral](seq: Iterable[N]) {
def differencesUnsafe: Iterable[N] =
if (seq.isEmpty) {
sys.error("No differences possible for empty sequence")
} else {
(seq.init zip seq.tail) map { case (a, b) =>
b - a
}
implicit class IntegralSeqOps[N: Integral](seq: Seq[N]) {
def differences: Seq[N] =
seq.sliding2 map { case (a, b) =>
b - a
}
}

Expand Down

0 comments on commit 8dfdf6e

Please sign in to comment.