package aoc.day9 import aoc._ object Parser extends CommonParser: val nums = rep1(long) val lns = lines.toSeq val inputs = lns.map(Parser.parse(Parser.nums, _).get).toSeq // part1 def calculate(add: Int => (Long, Seq[Long]) => Long)(ns: Seq[Long]) = @scala.annotation.tailrec def loop(ns: Seq[Long], depth: Int, sum: Long): Long = if ns.forall(_ == 0) then sum else val diff = ns.tail.lazyZip(ns).map(_ - _) loop(diff, depth + 1, add(depth)(sum, ns)) loop(ns, 0, 0) def part1 = println(inputs.map(calculate(_ => (sum, ns) => sum + ns.last)).sum) // part 2 def part2 = println( inputs .map( calculate(depth => (sum, ns) => sum + ns.head * (if depth % 2 == 0 then 1 else -1)) ) .sum ) @main def Day9(part: Int) = part match case 1 => part1 case 2 => part2