Skip to content

Commit 36fbcfd

Browse files
committed
Add an article for Day 17 of 2023
1 parent 11cafa0 commit 36fbcfd

File tree

1 file changed

+262
-0
lines changed

1 file changed

+262
-0
lines changed

docs/2023/puzzles/day17.md

Lines changed: 262 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,270 @@ import Solver from "../../../../../website/src/components/Solver.js"
66

77
https://adventofcode.com/2023/day/17
88

9+
## Solution Summary
10+
11+
This is a classic search problem with an interesting restriction on state transformations.
12+
13+
We will solve this using Djikstra's Algorithm to find a path through the grid, using the heat loss of each position as our node weights. However, the states in our priority queue will need to include more than just position and accumulated heat loss, since the streak of forward movements in a given direction affects which positions are accessible from a given state.
14+
15+
Since the restrictions on state transformations differ in part 1 and part 2, we'll model them separately from the base state transformations.
16+
17+
### Framework
18+
19+
First, for convenience, let's introduce classes for presenting position and direction:
20+
21+
```scala
22+
enum Dir:
23+
case N, S, E, W
24+
25+
def turnRight = this match
26+
case Dir.N => E
27+
case Dir.E => S
28+
case Dir.S => W
29+
case Dir.W => N
30+
31+
def turnLeft = this match
32+
case Dir.N => W
33+
case Dir.W => S
34+
case Dir.S => E
35+
case Dir.E => N
36+
37+
case class Point(x: Int, y: Int):
38+
def inBounds = xRange.contains(x) && yRange.contains(y)
39+
40+
def move(dir: Dir) = dir match
41+
case Dir.N => copy(y = y - 1)
42+
case Dir.S => copy(y = y + 1)
43+
case Dir.E => copy(x = x + 1)
44+
case Dir.W => copy(x = x - 1)
45+
```
46+
47+
Since moving forward, turning left, and turning right are common operations, convenience methods for each are included here.
48+
49+
Next, let's work with our input. We'll parse it as a 2D vector of integers:
50+
51+
```scala
52+
val grid: Vector[Vector[Int]] = Vector.from:
53+
val file = loadFileSync(s"$currentDir/../input/day17")
54+
for line <- file.split("\n")
55+
yield line.map(_.asDigit).toVector
56+
```
57+
58+
And now a few convenience methods that need the input:
59+
```scala
60+
val xRange = grid.head.indices
61+
val yRange = grid.indices
62+
63+
def inBounds(p: Point) =
64+
xRange.contains(p.x) && yRange.contains(p.y)
65+
66+
def heatLoss(p: Point) =
67+
if inBounds(p) then grid(p.y)(p.x) else 0
68+
```
69+
70+
### Search State
71+
72+
Now we want to be able to model our state as we're searching. The state will track our position. To know what transitions are possible, we need to keep track of our streak of movements in a given direction. We'll also keep track of the heat lost while getting to a state.
73+
74+
```scala
75+
case class State(pos: Point, dir: Dir, streak: Int):
76+
```
77+
78+
Next let's define some methods for transitioning to new states. We know that we can chose to move forward, turn left, or turn right. For now, we won't consider the restrictions from Part 1 or Part 2 on whether or not you can move forward:
79+
80+
```scala
81+
// methods inside State
82+
def straight: State =
83+
val newPos = pos.move(dir)
84+
State(pos.move(dir), dir, streak + 1)
85+
86+
def turnLeft: State =
87+
val newDir = dir.turnLeft
88+
val newPos = pos.move(newDir)
89+
State(newPos, newDir, 1)
90+
91+
def turnRight: State =
92+
val newDir = dir.turnRight
93+
val newPos = pos.move(newDir)
94+
State(newPos, newDir, 1)
95+
```
96+
97+
Note that the streak resets to one when we turn right or turn left, since we also move the position forward in that new direction.
98+
99+
### Djikstra's Algorithm
100+
101+
Finally, let's lay the groundwork for an implementation of Djikstra's algorithm.
102+
103+
Since our valid state transformations vary between part 1 and part 2, let's parameterize our search method by a function:
104+
105+
```scala
106+
def search(next: State => List[State]): Int =
107+
```
108+
109+
The algorithm uses Map to track the minimum total heat loss for each state, and a Priority Queue prioritizing by this heatloss to choose the next state to visit:
110+
111+
```scala
112+
import collection.mutable.{PriorityQueue, Map}
113+
114+
val minHeatLoss = Map.empty[State, Int]
115+
116+
given Ordering[State] = Ordering.by(minHeatLoss)
117+
val pq = PriorityQueue.empty[State].reverse
118+
119+
var visiting = State(Point(0, 0), Dir.E, 0)
120+
val minHeatLoss(visiting) = 0
121+
```
122+
123+
As we generate new states to add to the priority Queue, we need to make sure not to add suboptimal states. The first time we visit any state, it will be with a minimum possible cost, because we're visiting this new state from an adjacent minimum heatloss state in our priority queue.
124+
So any state we've already visited will be discarded. This is what our loop will look like:
125+
126+
```scala
127+
val end = Point(xRange.max, yRange.max)
128+
while visiting.pos != end do
129+
val states = next(visiting).filterNot(minHeatLoss.contains)
130+
states.foreach: s =>
131+
minHeatLoss(s) = minHeatLoss(visiting) + heatLoss(s)
132+
pq.enqueue(s)
133+
visiting = pq.dequeue()
134+
135+
minHeatLoss(end)
136+
```
137+
Notice how minHeatLoss is always updated to the minimum of the state we're visiting from plus the incremental heatloss of the new state we're adding to the queue.
138+
139+
### Part 1
140+
141+
Now we need to model our state transformation restrictions for Part 1. We can typically move straight, left, and right, but we need to make sure our streak straight streak never exceeds 3:
142+
143+
```scala
144+
// Inside case class State:
145+
def nextStates: List[State] =
146+
List(straight, turnLeft, turnRight).filter: s =>
147+
inBounds(s.pos) && s.streak <= 3
148+
```
149+
150+
This will only ever filter out the forward movement, since moving to the left or right resets the streak to 1.
151+
152+
### Part 2
153+
154+
Part 2 is similar, but our streak limit increases to 10.
155+
Furthermore, while the streak is less than four, only a forward movement is possible:
156+
157+
```scala
158+
def nextStates2: List[State] =
159+
if streak < 4 then List(straight)
160+
else List(straight, turnLeft, turnRight).filter: s =>
161+
inBounds(s.pos) && s.streak <= 10
162+
```
163+
164+
## Final Code
165+
166+
```scala
167+
import locations.Directory.currentDir
168+
import inputs.Input.loadFileSync
169+
170+
@main def part1: Unit =
171+
println(s"The solution is ${search(_.nextStates)}")
172+
173+
@main def part2: Unit =
174+
println(s"The solution is ${search(_.nextStates2)}")
175+
176+
def loadInput(): Vector[Vector[Int]] = Vector.from:
177+
val file = loadFileSync(s"$currentDir/../input/day17")
178+
for line <- file.split("\n")
179+
yield line.map(_.asDigit).toVector
180+
181+
enum Dir:
182+
case N, S, E, W
183+
184+
def turnRight = this match
185+
case Dir.N => E
186+
case Dir.E => S
187+
case Dir.S => W
188+
case Dir.W => N
189+
190+
def turnLeft = this match
191+
case Dir.N => W
192+
case Dir.W => S
193+
case Dir.S => E
194+
case Dir.E => N
195+
196+
val grid = loadInput()
197+
198+
val xRange = grid.head.indices
199+
val yRange = grid.indices
200+
201+
case class Point(x: Int, y: Int):
202+
def move(dir: Dir) = dir match
203+
case Dir.N => copy(y = y - 1)
204+
case Dir.S => copy(y = y + 1)
205+
case Dir.E => copy(x = x + 1)
206+
case Dir.W => copy(x = x - 1)
207+
208+
def inBounds(p: Point) =
209+
xRange.contains(p.x) && yRange.contains(p.y)
210+
211+
def heatLoss(p: Point) =
212+
if inBounds(p) then grid(p.y)(p.x) else 0
213+
214+
case class State(pos: Point, dir: Dir, streak: Int):
215+
def straight: State =
216+
val newPos = pos.move(dir)
217+
State(pos.move(dir), dir, streak + 1)
218+
219+
def turnLeft: State =
220+
val newDir = dir.turnLeft
221+
val newPos = pos.move(newDir)
222+
State(newPos, newDir, 1)
223+
224+
def turnRight: State =
225+
val newDir = dir.turnRight
226+
val newPos = pos.move(newDir)
227+
State(newPoss, newDir, 1)
228+
229+
def nextStates: List[State] =
230+
List(straight, turnLeft, turnRight).filter: s =>
231+
inBounds(s.pos) && s.streak <= 3
232+
233+
def nextStates2: List[State] =
234+
if streak < 4 then List(straight)
235+
else List(straight, turnLeft, turnRight).filter: s =>
236+
inBounds(s.pos) && s.streak <= 10
237+
238+
def search(next: State => List[State]): Int =
239+
import collection.mutable.{PriorityQueue, Map}
240+
241+
val minHeatLoss = Map.empty[State, Int]
242+
243+
given Ordering[State] = Ordering.by(minHeatLoss)
244+
val pq = PriorityQueue.empty[State].reverse
245+
246+
var visiting = State(Point(0, 0), Dir.E, 0)
247+
val minHeatLoss(visiting) = 0
248+
249+
val end = Point(xRange.max, yRange.max)
250+
while visiting.pos != end do
251+
val states = next(visiting).filterNot(minHeatLoss.contains)
252+
states.foreach: s =>
253+
minHeatLoss(s) = minHeatLoss(visiting) + heatLoss(s)
254+
pq.enqueue(s)
255+
visiting = pq.dequeue()
256+
257+
minHeatLoss(end)
258+
```
259+
260+
### Run it in the browser
261+
262+
#### Part 1
263+
264+
<Solver puzzle="day17-part1" year="2023"/>
265+
266+
#### Part 2
267+
268+
<Solver puzzle="day17-part2" year="2023"/>
269+
9270
## Solutions from the community
10271

272+
- [Solution](https://github.com/stewSquared/advent-of-code/blob/master/src/main/scala/2021/Day17.worksheet.sc) by [stewSquared](https://github.com/stewSquared)
11273
- [Solution](https://github.com/merlinorg/aoc2023/blob/main/src/main/scala/Day17.scala) by [merlin](https://github.com/merlinorg/)
12274
- [Solution](https://github.com/xRuiAlves/advent-of-code-2023/blob/main/Day17.scala) by [Rui Alves](https://github.com/xRuiAlves/)
13275

0 commit comments

Comments
 (0)