-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday10.sc
49 lines (36 loc) · 1.2 KB
/
day10.sc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import common.loadPackets
import scala.annotation.tailrec
val input = loadPackets(List("day10.txt")).map(_.map(_.toString.toInt))
val ys = input.indices
val xs = input.head.indices
enum Direction:
case Up, Right, Down, Left
case class Point(x: Int, y: Int):
def onGrid: Boolean = xs.contains(x) && ys.contains(y)
def plus(d: Point, steps: Int = 1): Point = copy(x = x + d.x * steps, y = y + d.y * steps)
def move(d: Direction): Point = d match {
case Direction.Up => plus(Point(0, -1))
case Direction.Right => plus(Point(1, 0))
case Direction.Down => plus(Point(0, 1))
case Direction.Left => plus(Point(-1, 0))
}
def height: Int = input(y)(x)
def neighbors: Seq[Point] = Direction.values.toSeq
.map(move)
.filter(_.onGrid)
.filter(_.height == height + 1)
val points = for
y <- ys
x <- xs
yield Point(x, y)
val trailheads = points.filter(_.height == 0)
def score(point: Point): Set[Point] =
if point.height == 9
then Set(point)
else point.neighbors.toSet.flatMap(score)
val part1 = trailheads.map(score).map(_.size).sum
def rating(point: Point): Int =
if point.height == 9
then 1
else point.neighbors.map(rating).sum
val part2 = trailheads.map(rating).sum