|
| 1 | +package day06 |
| 2 | + |
| 3 | +import locations.Directory.currentDir |
| 4 | +import inputs.Input.loadFileSync |
| 5 | + |
| 6 | +@main def part1: Unit = |
| 7 | + println(s"The solution is ${part1(loadInput())}") |
| 8 | + |
| 9 | +@main def part2: Unit = |
| 10 | + println(s"The solution is ${part2(loadInput())}") |
| 11 | + |
| 12 | +def loadInput(): String = loadFileSync(s"$currentDir/../input/day06") |
| 13 | + |
| 14 | +extension [A](xs: IterableOnce[A]) |
| 15 | + inline def splitBy(sep: A) = |
| 16 | + val (b, cur) = (Vector.newBuilder[Vector[A]], Vector.newBuilder[A]) |
| 17 | + for e <- xs.iterator do |
| 18 | + if e != sep then cur += e else { b += cur.result(); cur.clear() } |
| 19 | + (b += cur.result()).result() |
| 20 | + |
| 21 | +extension (xs: IterableOnce[(symbol: String, nums: IterableOnce[String])]) |
| 22 | + inline def calculate: Long = xs.iterator.collect { |
| 23 | + case ("*", nums) => nums.iterator.map(_.toLong).product |
| 24 | + case ("+", nums) => nums.iterator.map(_.toLong).sum |
| 25 | + }.sum |
| 26 | + |
| 27 | +def part1(input: String): Long = input.linesIterator.toVector |
| 28 | + .map(_.trim.split(raw"\s+")) |
| 29 | + .transpose |
| 30 | + .iterator |
| 31 | + .map { col => (col.last, col.view.init) } |
| 32 | + .calculate |
| 33 | + |
| 34 | +def part2(input: String): Long = |
| 35 | + val lines = input.linesIterator.toVector |
| 36 | + val ops = lines.last.split(raw"\s+").toVector |
| 37 | + val xss = lines.init.transpose.map(_.mkString.trim).splitBy("") |
| 38 | + |
| 39 | + (ops lazyZip xss).calculate |
0 commit comments