This commit is contained in:
Paul-Henri Froidmont 2024-12-10 12:59:26 +01:00
parent 2e76446786
commit e6604dbb24
Signed by: phfroidmont
GPG key ID: BE948AFD7E7873BE
2 changed files with 106 additions and 0 deletions

63
src/day10.scala Normal file
View file

@ -0,0 +1,63 @@
package aoc
package day10
val dayNumber = "10"
@main def part1: Unit =
println(part1(loadInput(dayNumber)))
@main def part2: Unit =
println(part2(loadInput(dayNumber)))
def part1(input: String): String =
val (topoMap, trailheads) = parseInput(input)
def findTrails(from: Point): Vector[List[Point]] =
val visited = scala.collection.mutable.HashSet.empty[Point]
def aux(cur: Point, alt: Int, path: List[Point]): Vector[List[Point]] =
visited += cur
if alt == 9 then Vector(cur :: path)
else
cur.neighbors
.flatMap(n => topoMap.get(n).map(n -> _))
.filter((n, nAlt) => nAlt == alt + 1 && !visited.contains(n))
.flatMap((n, nAlt) => aux(n, nAlt, cur :: path))
aux(from, topoMap(from), Nil)
trailheads.map(findTrails(_).length).sum.toString
def part2(input: String): String =
val (topoMap, trailheads) = parseInput(input)
def findTrails(from: Point): Vector[List[Point]] =
def aux(cur: Point, alt: Int, path: List[Point]): Vector[List[Point]] =
if alt == 9 then Vector(cur :: path)
else
cur.neighbors
.flatMap(n => topoMap.get(n).map(n -> _))
.filter((_, nAlt) => nAlt == alt + 1)
.flatMap((n, nAlt) => aux(n, nAlt, cur :: path))
aux(from, topoMap(from), Nil)
trailheads.map(findTrails(_).length).sum.toString
type Point = (Int, Int)
extension (point: Point)
def plus(offset: Point) = (point._1 + offset._1, point._2 + offset._2)
def neighbors = Vector(
point.plus(-1 -> 0),
point.plus(1 -> 0),
point.plus(0 -> -1),
point.plus(0 -> 1)
)
def parseInput(input: String): (Map[Point, Int], Seq[Point]) =
val grid = input.split("\n")
val coords =
for
y <- 0 until grid.length
x <- 0 until grid.head.length
yield (x, y) -> grid(y)(x).asDigit
val topoMap = coords.toMap
val trailheads = coords.collect { case (x, y) -> 0 => (x, y) }
(topoMap, trailheads)