This commit is contained in:
Christian
2024-12-08 09:16:48 +01:00
parent 4f94a48bbe
commit 7c4328ca42
6 changed files with 109 additions and 1 deletions

View File

@@ -2,11 +2,13 @@ package dev.ctsk.aoc
case class Point(x: Int, y: Int):
def +(o: Point): Point = Point(x + o.x, y + o.y)
def -(o: Point): Point = Point(x - o.x, y - o.y)
def *(n: Int): Point = Point(n * x, n * y)
enum Direction:
case Up, Right, Down, Left
def turnRight: Direction = Direction.fromOrdinal((ordinal + 1) % 4)
def toPoint: Point =
this match
case Up => Point(-1, 0)
@@ -15,6 +17,7 @@ enum Direction:
case Left => Point(0, -1)
def apply(p: Point): Point = p + toPoint
def applyN(p: Point, n: Int): Point = p + toPoint * n
def flip: Direction =
@@ -31,6 +34,7 @@ case class Pose(pos: Point, dir: Direction):
class Grid[A](val data: Array[Array[A]]):
def height: Int = data.length
def width: Int = data(0).length
def apply(p: Point): Option[A] =
@@ -53,3 +57,6 @@ class Grid[A](val data: Array[Array[A]]):
}.headOption
def count(f: A => Boolean): Int = data.map(_.count(f)).sum
def contains(p: Point): Boolean =
p.x >= 0 && p.y >= 0 && p.x < height && p.y < width

View File

@@ -9,7 +9,8 @@ val solvers = Map[Int, Solver](
4 -> Day04,
5 -> Day05,
6 -> Day06,
7 -> Day07
7 -> Day07,
8 -> Day08
)
def runSolver(solver: Solver, input: os.Path): Unit =

View File

@@ -0,0 +1,3 @@
package dev.ctsk.aoc

View File

@@ -0,0 +1,45 @@
package dev.ctsk.aoc.days
import dev.ctsk.aoc._
extension [A](xs: Seq[A])
def pairs: Iterator[(A, A)] =
xs.combinations(2).map(xs => (xs(0), xs(1)))
object Day08 extends Solver(8):
type Input = (Vector[Vector[Point]], Grid[Char])
case class Ctx(f: os.ReadablePath):
val grid = Grid(os.read.lines(f).map(_.toArray).toArray)
val antennae =
grid.find(_ != '.').groupBy(grid(_)).map(_._2.toVector).toVector
def antinodes(a: Point, b: Point): Iterator[Point] =
def it(a: Point, b: Point) =
Iterator.iterate(a)(_ + a - b).takeWhile(grid.contains)
it(a, b) ++ it(b, a)
def part1: Int =
antennae
.flatMap(
_.pairs
.flatMap((a, b) => Iterator(a + a - b, b + b - a))
.filter(grid.contains)
)
.toSet
.size
def part2: Int =
antennae
.flatMap(_.pairs.flatMap(p => antinodes(p._1, p._2)))
.toSet
.size
def run(input: os.ReadablePath): (Timings, Solution) =
val (pre_time, ctx) = timed { Ctx(input) }
val (p1_time, p1_solution) = timed { ctx.part1 }
val (p2_time, p2_solution) = timed { ctx.part2 }
(
Timings(pre_time, p1_time, p2_time),
Solution(Int.box(p1_solution), Int.box(p2_solution))
)