-
Notifications
You must be signed in to change notification settings - Fork 1
/
day15.html
809 lines (727 loc) Β· 51.1 KB
/
day15.html
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
<!DOCTYPE html>
<html lang="en-us">
<head>
<title>2021/day15.nim</title>
<link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2280%22>π³</text></svg>">
<meta content="text/html; charset=utf-8" http-equiv="content-type">
<meta content="width=device-width, initial-scale=1" name="viewport">
<link rel='stylesheet' href='https://unpkg.com/normalize.css/'>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/kognise/water.css@latest/dist/dark.min.css">
<link rel='stylesheet' href='https://cdn.jsdelivr.net/gh/pietroppeter/nimib/assets/androidstudio.css'>
<style>
.nb-box {
display: flex;
align-items: center;
justify-content: space-between;
}
.nb-small {
font-size: 0.8rem;
}
button.nb-small {
float: right;
padding: 2px;
padding-right: 5px;
padding-left: 5px;
}
section#source {
display:none
}
</style>
<script async defer data-domain="pietroppeter.github.io/adventofnim" src="https://plausible.io/js/plausible.js"></script>
<style>
a {
text-decoration: none;
color: #009900;
}
a:hover {
color: #99ff99;
}
em {
color: #ffffff;
font-style: normal;
text-shadow: 0 0 5px #ffffff;
}
em.star {
font-style: normal;
color: #ffff66;
text-shadow: 0 0 5px #ffff66;
}
</style>
</head>
<body>
<header>
<div class="nb-box">
<span><a href="..">π‘</a></span>
<span><code>2021/day15.nim</code></span>
<span><a href="https://github.com/pietroppeter/adventofnim"><svg aria-hidden="true" width="1.2em" height="1.2em" style="vertical-align: middle; fill: #fff" preserveAspectRatio="xMidYMid meet" viewBox="0 0 16 16"><path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"></path></svg></a></span>
</div>
<hr>
</header><main>
<h2>Day 15: <a href="https://adventofcode.com/2021/day/15">Chiton</a></h2>
<p>Today is about path search on a grid. I tend to struggle with these
since I never properly studied the theory.</p>
<h3>Part 1</h3>
<p>We need to go from top left to bottom right minimizing sum of risk.
My strategy will be to create from given grid a new grid that
at every "node" (it usually pays to think of these problems in terms of graphs),
will tell me the direction I should come from in order to minimize the risk and
get there. The final path will be found by following directions from bottom right.</p>
<p>Here are the inputs:</p>
<pre><code class="nim hljs"><span class="hljs-keyword">let</span>
testInput = <span class="hljs-string">"""
1163751742
1381373672
2136511328
3694931569
7463417111
1319128137
1359912421
3125421639
1293138521
2311944581"""</span>
puzzleInput = readFile(<span class="hljs-string">"2021/input15.txt"</span>)</code></pre>
<p>I will be using grid code from my Day09 (no blogpost published),
copying and pasting here the useful bits (I will need to think of an ergonomic
way to import from a notebook). I am also fine with having a sentinel value
for stuff outside the grid that is a high value.</p>
<pre><code class="nim hljs"><span class="hljs-keyword">type</span>
<span class="hljs-type">Coord</span> = <span class="hljs-keyword">tuple</span>[x, y: <span class="hljs-built_in">int</span>]
<span class="hljs-type">Grid</span>[<span class="hljs-type">T</span>] = <span class="hljs-keyword">object</span>
data: <span class="hljs-built_in">seq</span>[<span class="hljs-type">T</span>]
yLen, xLen: <span class="hljs-built_in">int</span>
sentinel: <span class="hljs-type">T</span> <span class="hljs-comment"># value for outside the grid</span>
<span class="hljs-type">GridInt</span> = <span class="hljs-type">Grid</span>[<span class="hljs-built_in">int</span>]
<span class="hljs-type">Dir</span> = <span class="hljs-keyword">enum</span>
right, down, left, up
<span class="hljs-keyword">func</span> isOutside[<span class="hljs-type">T</span>](c: <span class="hljs-type">Coord</span>, g: <span class="hljs-type">Grid</span>[<span class="hljs-type">T</span>]): <span class="hljs-built_in">bool</span> =
c.x < <span class="hljs-number">0</span> <span class="hljs-keyword">or</span> c.x >= g.xLen <span class="hljs-keyword">or</span> c.y < <span class="hljs-number">0</span> <span class="hljs-keyword">or</span> c.y >= g.yLen
<span class="hljs-keyword">func</span> toIndex[<span class="hljs-type">T</span>](g: <span class="hljs-type">Grid</span>[<span class="hljs-type">T</span>], c: <span class="hljs-type">Coord</span>): <span class="hljs-built_in">int</span> =
<span class="hljs-keyword">if</span> c.isOutside(g):
-<span class="hljs-number">1</span>
<span class="hljs-keyword">else</span>:
c.y*g.xLen + c.x
<span class="hljs-keyword">func</span> `[]`[<span class="hljs-type">T</span>](g: <span class="hljs-type">Grid</span>[<span class="hljs-type">T</span>], c: <span class="hljs-type">Coord</span>): <span class="hljs-type">T</span> =
<span class="hljs-keyword">let</span> i = g.toIndex(c)
<span class="hljs-keyword">if</span> i < <span class="hljs-number">0</span>:
g.sentinel
<span class="hljs-keyword">else</span>:
g.data[i]
<span class="hljs-comment"># added today</span>
<span class="hljs-keyword">func</span> `[]=`[<span class="hljs-type">T</span>](g: <span class="hljs-keyword">var</span> <span class="hljs-type">Grid</span>[<span class="hljs-type">T</span>], c: <span class="hljs-type">Coord</span>, value: <span class="hljs-type">T</span>) =
<span class="hljs-keyword">let</span> i = g.toIndex(c)
<span class="hljs-keyword">if</span> i >= <span class="hljs-number">0</span>:
g.data[i] = value
<span class="hljs-keyword">func</span> parseInt(c: <span class="hljs-built_in">char</span>): <span class="hljs-built_in">int</span> =
<span class="hljs-literal">result</span> = ord(c) - ord(<span class="hljs-string">'0'</span>)
<span class="hljs-keyword">assert</span> <span class="hljs-literal">result</span> >= <span class="hljs-number">0</span> <span class="hljs-keyword">and</span> <span class="hljs-literal">result</span> <= <span class="hljs-number">9</span>
<span class="hljs-keyword">func</span> parse(text: <span class="hljs-built_in">string</span>): <span class="hljs-type">GridInt</span> =
<span class="hljs-comment"># result.data = newSeqOfCap(text.len)</span>
<span class="hljs-keyword">for</span> line <span class="hljs-keyword">in</span> text.strip.splitLines:
<span class="hljs-literal">result</span>.data.add line.toSeq.map(parseInt)
inc <span class="hljs-literal">result</span>.yLen
<span class="hljs-keyword">if</span> <span class="hljs-literal">result</span>.xLen == <span class="hljs-number">0</span>:
<span class="hljs-literal">result</span>.xLen = line.len
<span class="hljs-keyword">else</span>:
<span class="hljs-keyword">assert</span> line.len == <span class="hljs-literal">result</span>.xLen
<span class="hljs-literal">result</span>.sentinel = <span class="hljs-built_in">int</span>.<span class="hljs-keyword">high</span>
<span class="hljs-keyword">iterator</span> coords[<span class="hljs-type">T</span>](g: <span class="hljs-type">Grid</span>[<span class="hljs-type">T</span>]): <span class="hljs-type">Coord</span> =
<span class="hljs-keyword">for</span> y <span class="hljs-keyword">in</span> <span class="hljs-number">0</span> ..< g.yLen:
<span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> <span class="hljs-number">0</span> ..< g.xLen:
<span class="hljs-keyword">yield</span> (x, y)
<span class="hljs-keyword">func</span> `+`(c: <span class="hljs-type">Coord</span>, dir: <span class="hljs-type">Dir</span>): <span class="hljs-type">Coord</span> =
<span class="hljs-keyword">case</span> dir
<span class="hljs-keyword">of</span> right:
(c.x + <span class="hljs-number">1</span>, c.y)
<span class="hljs-keyword">of</span> down:
(c.x, c.y + <span class="hljs-number">1</span>)
<span class="hljs-keyword">of</span> left:
(c.x - <span class="hljs-number">1</span>, c.y)
<span class="hljs-keyword">of</span> up:
(c.x, c.y - <span class="hljs-number">1</span>)</code></pre>
<p>Let's use it to parse inputs:</p>
<pre><code class="nim hljs"><span class="hljs-keyword">let</span>
testGrid = parse testInput
puzzleGrid = parse puzzleInput
dump (testGrid.xlen, testGrid.ylen)
dump (puzzleGrid.xlen, puzzleGrid.ylen)
dump testGrid.sentinel</code></pre>
<pre><samp>(testGrid.xlen, testGrid.ylen) = (10, 10)
(puzzleGrid.xlen, puzzleGrid.ylen) = (100, 100)
testGrid.sentinel = 9223372036854775807
</samp></pre>
<p>I am not using a <code>GridDiff</code> (I did not copy related code),
I will be using a <code>GridRisk</code> which will tell
me minimal total risk up to here and best direction I should come from.</p>
<p>I will also use show functions to debug.</p>
<pre><code class="nim hljs"><span class="hljs-keyword">type</span>
<span class="hljs-type">Risk</span> = <span class="hljs-keyword">tuple</span>[risk: <span class="hljs-built_in">int</span>, dir: <span class="hljs-type">Dir</span>]
<span class="hljs-type">GridRisk</span> = <span class="hljs-type">Grid</span>[<span class="hljs-type">Risk</span>]
<span class="hljs-keyword">func</span> show(g: <span class="hljs-type">GridInt</span>): <span class="hljs-built_in">string</span> =
<span class="hljs-keyword">for</span> c <span class="hljs-keyword">in</span> g.coords:
<span class="hljs-literal">result</span>.add $g[c]
<span class="hljs-keyword">if</span> c.x == g.xLen - <span class="hljs-number">1</span>:
<span class="hljs-literal">result</span>.add <span class="hljs-string">'\n'</span>
<span class="hljs-keyword">func</span> show(g: <span class="hljs-type">GridRisk</span>, paddingCount=<span class="hljs-number">4</span>): <span class="hljs-built_in">string</span> =
<span class="hljs-keyword">for</span> c <span class="hljs-keyword">in</span> g.coords:
<span class="hljs-keyword">if</span> g[c].risk < g.sentinel.risk:
<span class="hljs-literal">result</span>.add align($(g[c].risk), paddingCount)
<span class="hljs-keyword">else</span>:
<span class="hljs-literal">result</span>.add align(<span class="hljs-string">"*"</span>, paddingCount)
<span class="hljs-keyword">if</span> c.x == g.xLen - <span class="hljs-number">1</span>:
<span class="hljs-literal">result</span>.add <span class="hljs-string">'\n'</span>
<span class="hljs-keyword">echo</span> show testGrid</code></pre>
<pre><samp>1163751742
1381373672
2136511328
3694931569
7463417111
1319128137
1359912421
3125421639
1293138521
2311944581
</samp></pre>
<p>Here is the heart of the problem. Key for this is realizing
how to compute incrementally compute the risk.</p>
<pre><code class="nim hljs"><span class="hljs-keyword">func</span> computeRisk(g: <span class="hljs-type">GridInt</span>, gr: <span class="hljs-type">GridRisk</span>, c: <span class="hljs-type">Coord</span>): <span class="hljs-type">Risk</span> =
<span class="hljs-comment">## Computes Risk at Coord assuming Risk has been computed</span>
<span class="hljs-comment">## for cells on the left and above</span>
<span class="hljs-keyword">let</span>
riskUp = gr[c + up].risk + g[c]
riskLeft = gr[c + left].risk + g[c]
<span class="hljs-comment">#debugEcho "computeRisk for c: ", c</span>
<span class="hljs-comment">#debugEcho " riskUp: ", riskUp</span>
<span class="hljs-comment">#debugEcho " riskLeft: ", riskLeft</span>
<span class="hljs-keyword">if</span> riskUp <= riskLeft:
(riskUp, up)
<span class="hljs-keyword">else</span>:
(riskLeft, left)
<span class="hljs-keyword">func</span> computeGridRisk(g: <span class="hljs-type">GridInt</span>): <span class="hljs-type">GridRisk</span> =
<span class="hljs-literal">result</span>.xLen = g.xLen
<span class="hljs-literal">result</span>.yLen = g.ylen
<span class="hljs-literal">result</span>.sentinel = (g.sentinel - <span class="hljs-number">10</span>, up) <span class="hljs-comment"># forgot this line on first try</span>
<span class="hljs-comment"># need to do - 10 to avoid overflow</span>
<span class="hljs-literal">result</span>.data = @[(<span class="hljs-number">0</span>, up)] <span class="hljs-comment"># risk for initial position does not count</span>
<span class="hljs-keyword">for</span> c <span class="hljs-keyword">in</span> g.coords:
<span class="hljs-keyword">if</span> c == (<span class="hljs-number">0</span>, <span class="hljs-number">0</span>): <span class="hljs-keyword">continue</span>
<span class="hljs-literal">result</span>.data.add g.computeRisk(<span class="hljs-literal">result</span>, c)
<span class="hljs-keyword">func</span> part1(gr: <span class="hljs-type">GridRisk</span>): <span class="hljs-built_in">int</span> =
gr[(gr.xLen - <span class="hljs-number">1</span>, gr.yLen - <span class="hljs-number">1</span>)].risk
<span class="hljs-keyword">let</span>
testGridRisk = computeGridRisk testGrid
puzzleGridRisk = computeGridRisk puzzleGrid
<span class="hljs-keyword">echo</span> show testGridRisk
dump part1 testGridRisk
dump part1 puzzleGridRisk <span class="hljs-comment"># 719 wrong, too high!</span></code></pre>
<pre><samp> 0 1 7 10 17 22 23 30 34 36
1 4 12 11 14 21 24 30 37 38
3 4 7 13 18 19 20 23 25 33
6 10 16 17 26 22 21 26 31 40
13 14 20 20 24 23 28 27 28 29
14 17 18 27 25 25 33 28 31 36
15 18 23 32 34 26 28 32 33 34
18 19 21 26 30 28 29 35 36 43
19 21 30 29 30 31 37 40 38 39
21 24 25 26 35 35 39 44 46 40
part1 testGridRisk = 40
part1 puzzleGridRisk = 719
</samp></pre>
<p>I am stuck at the moment with <em>a correct test result and an incorrect
puzzle result</em>. Not really sure how to debug.</p>
<p>... after looking at our discord aoc I got a useful hint (thanks @Michal58!),
the example only gives a path where the solution only goes down and to the right
and this was also my (wrong) assumption! It is indeed possible
for a minimal solution to wiggle around all directions but
my algorithm for sure is not going to find it.</p>
<p>So I really need to implement <a href="https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm">Dijkstra</a>
or <a href="https://en.wikipedia.org/wiki/A*_search_algorithm">A*</a> algorithm!</p>
<p>But first let me give a minimal example that makes it clear why I need
the better approach:</p>
<pre><code class="nim hljs"><span class="hljs-keyword">let</span>
hintInput = <span class="hljs-string">"19999</span><span class="hljs-meta">\n</span><span class="hljs-string">19111</span><span class="hljs-meta">\n</span><span class="hljs-string">11191"</span>
hintGrid = parse hintInput
hintGridRisk = computeGridRisk hintGrid
<span class="hljs-keyword">echo</span> show hintGrid, <span class="hljs-string">"</span><span class="hljs-meta">\n</span><span class="hljs-string">"</span>, show hintGridRisk</code></pre>
<pre><samp>19999
19111
11191
0 9 18 27 36
1 10 11 12 13
2 3 4 13 14
</samp></pre>
<p>... <em>(a few hours later) back to writing the blogpost and writing my solution</em>.</p>
<p>This morning I shared the hint on <a href="https://www.reddit.com/r/adventofcode/comments/rgszh7/2021_day_15_part_1_hint_if_you_get_correct_answer/">advent of code subreddit</a>
and it has been quite popular! The irony is that I have not yet taken advantage of the hint and finalized my solution π, so let's get to it.</p>
<p>I will implement Dijkstra's algorithm because it is simpler than A* (although in general less powerful) and also because of its
<a href="https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#History#:~:text=it%20was%20a%20twenty,pencil%20and%20paper">compelling history</a>
(did you open last link on a chromium based browser? did you know what <a href="https://web.dev/text-fragments/">text-fragments</a> are?
I didn't but having seen some weird highlighted stuff after google results I got curious...).</p>
<p>I will still be using my <code>GridRisk</code> type although it seems not completely appropriate...
The <code>risk</code> value will be the distance, I will try also to set the correct distance.</p>
<p>In the following implementation comments not in parenthesis are taken verbatim
from wikipedia's description of the algorithm. An important change I make
is to make sure I use a priority queue. Among the many Dijkstra implementations
that have been written today, I dare say this must rank among the worst...
"</p>
<pre><code class="nim hljs"><span class="hljs-keyword">import</span> std / heapqueue <span class="hljs-comment"># (not among my standard aoc imports)</span>
<span class="hljs-keyword">type</span>
<span class="hljs-type">Node</span> = <span class="hljs-keyword">tuple</span>[coord: <span class="hljs-type">Coord</span>, risk: <span class="hljs-built_in">int</span>]
<span class="hljs-keyword">proc</span> `<`(a, b: <span class="hljs-type">Node</span>): <span class="hljs-built_in">bool</span> = a.risk < b.risk
<span class="hljs-keyword">iterator</span> neighbours[<span class="hljs-type">T</span>](g: <span class="hljs-type">Grid</span>[<span class="hljs-type">T</span>], c: <span class="hljs-type">Coord</span>): (<span class="hljs-type">Coord</span>, <span class="hljs-type">Dir</span>) =
<span class="hljs-keyword">for</span> dir <span class="hljs-keyword">in</span> <span class="hljs-type">Dir</span>:
<span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> (c + dir).isOutside(g):
<span class="hljs-keyword">yield</span> (c + dir, dir)
<span class="hljs-keyword">func</span> dijkstra(g: <span class="hljs-type">GridInt</span>): <span class="hljs-type">GridRisk</span> =
<span class="hljs-comment"># (0. initialize result)</span>
<span class="hljs-literal">result</span>.xLen = g.xLen
<span class="hljs-literal">result</span>.yLen = g.ylen
<span class="hljs-literal">result</span>.sentinel = (g.sentinel, up)
<span class="hljs-comment"># 1. Mark all nodes unvisited. Create a set of all the unvisited nodes called the unvisited set.</span>
<span class="hljs-comment"># (I will instead create a visited set)</span>
<span class="hljs-comment"># (I will also create a priority queue for unvisited nodes, but I will start populating later)</span>
<span class="hljs-keyword">var</span>
visited = initHashSet[<span class="hljs-type">Coord</span>]()
unvisited = initHeapQueue[<span class="hljs-type">Node</span>]()
<span class="hljs-comment"># 2. Assign to every node a tentative distance value: set it to zero for our initial node and to infinity for all other nodes.</span>
<span class="hljs-literal">result</span>.data = @[(<span class="hljs-number">0</span>, up)] <span class="hljs-comment"># risk for initial position does not count</span>
<span class="hljs-keyword">for</span> c <span class="hljs-keyword">in</span> g.coords:
<span class="hljs-keyword">if</span> c == (<span class="hljs-number">0</span>, <span class="hljs-number">0</span>): <span class="hljs-keyword">continue</span>
<span class="hljs-literal">result</span>.data.add @[<span class="hljs-literal">result</span>.sentinel]
<span class="hljs-comment"># 3. For the current node, consider all of its unvisited neighbors</span>
<span class="hljs-comment"># and calculate their tentative distances through the current node.</span>
<span class="hljs-comment"># Compare the newly calculated tentative distance to the current assigned value</span>
<span class="hljs-comment"># and assign the smaller one</span>
<span class="hljs-keyword">var</span>
current = (<span class="hljs-number">0</span>, <span class="hljs-number">0</span>)
destination = (g.xLen - <span class="hljs-number">1</span>, g.yLen - <span class="hljs-number">1</span>)
risk: <span class="hljs-built_in">int</span>
<span class="hljs-comment"># 5. If the destination node has been marked visited then stop. The algorithm has finished.</span>
<span class="hljs-keyword">while</span> destination <span class="hljs-keyword">not_in</span> visited:
<span class="hljs-keyword">for</span> neighbour, dir <span class="hljs-keyword">in</span> g.neighbours(current):
<span class="hljs-keyword">if</span> neighbour <span class="hljs-keyword">in</span> visited:
<span class="hljs-keyword">continue</span>
risk = <span class="hljs-literal">result</span>[current].risk + g[neighbour]
<span class="hljs-keyword">if</span> risk < <span class="hljs-literal">result</span>[neighbour].risk:
<span class="hljs-literal">result</span>[neighbour] = (risk, dir)
unvisited.push (neighbour, risk) <span class="hljs-comment"># (push to queue)</span>
<span class="hljs-comment"># 4. When we are done considering all of the unvisited neighbors of the current node,</span>
<span class="hljs-comment"># mark the current node as visited and remove it from the unvisited set</span>
visited.incl current
<span class="hljs-keyword">if</span> current == destination: <span class="hljs-keyword">break</span> <span class="hljs-comment"># seems I need this (for puzzle input)</span>
<span class="hljs-comment"># 6. Otherwise, select the unvisited node that is marked with the smallest tentative distance,</span>
<span class="hljs-comment"># set it as the new current node, and go back to step 3.</span>
<span class="hljs-keyword">while</span> current <span class="hljs-keyword">in</span> visited: <span class="hljs-comment"># (I think it may happen that I pull from queue stuff already visited)</span>
<span class="hljs-keyword">if</span> len(unvisited) == <span class="hljs-number">0</span>:
debugEcho <span class="hljs-string">"current: "</span>, current
<span class="hljs-keyword">raise</span> <span class="hljs-type">ValueError</span>.newException <span class="hljs-string">"whaaaat?"</span>
current = unvisited.pop().coord <span class="hljs-comment"># (pull from queue)</span>
<span class="hljs-keyword">echo</span> show dijkstra(hintGrid)
<span class="hljs-keyword">echo</span> <span class="hljs-string">"</span><span class="hljs-meta">\n</span><span class="hljs-string">"</span>, show dijkstra(testGrid)</code></pre>
<pre><samp> 0 9 14 15 16
1 10 5 6 7
2 3 4 13 8
0 1 7 10 17 22 23 30 34 36
1 4 12 11 14 21 23 29 32 34
3 4 7 13 18 19 20 23 25 33
6 10 16 17 26 22 21 26 31 38
13 14 20 20 24 23 28 27 28 29
14 17 18 27 25 25 33 28 31 36
15 18 23 32 34 26 28 32 33 34
18 19 21 26 30 28 29 35 36 43
19 21 30 29 30 31 37 40 38 39
21 24 25 26 35 35 39 44 46 40
</samp></pre>
<p>results look good!</p>
<pre><code class="nim hljs"><span class="hljs-keyword">let</span> puzzleGridDijkstra = dijkstra(puzzleGrid)
<span class="hljs-keyword">echo</span> puzzleGridDijkstra.data[^<span class="hljs-number">1</span>]</code></pre>
<pre><samp>(risk: 717, dir: down)
</samp></pre>
<blockquote>
<p>That's the right answer! You are <em class="star">one gold star</em> closer to saving your vacation.</p>
</blockquote>
<h3>Part 2</h3>
<p>Now the map is bigger, and from what I hear around, the implementation
with the priority queue might be key to have a working solution now.</p>
<p>Let's create the bigger maps and solve part 2:</p>
<pre><code class="nim hljs"><span class="hljs-keyword">func</span> biggerMap(g: <span class="hljs-type">GridInt</span>): <span class="hljs-type">GridInt</span> =
<span class="hljs-literal">result</span>.xLen = g.xLen*<span class="hljs-number">5</span>
<span class="hljs-literal">result</span>.yLen = g.yLen*<span class="hljs-number">5</span>
<span class="hljs-literal">result</span>.sentinel = g.sentinel
<span class="hljs-literal">result</span>.data = newSeqWith(len=g.data.len*<span class="hljs-number">25</span>): <span class="hljs-number">0</span>
<span class="hljs-keyword">for</span> coord <span class="hljs-keyword">in</span> <span class="hljs-literal">result</span>.coords:
<span class="hljs-keyword">let</span>
smallCoord = (coord.x <span class="hljs-keyword">mod</span> g.xLen, coord.y <span class="hljs-keyword">mod</span> g.yLen)
oneUps = (coord.x <span class="hljs-keyword">div</span> g.xLen) + (coord.y <span class="hljs-keyword">div</span> g.yLen)
<span class="hljs-literal">result</span>[coord] = (g[smallCoord] + oneUps - <span class="hljs-number">1</span>) <span class="hljs-keyword">mod</span> <span class="hljs-number">9</span> + <span class="hljs-number">1</span>
<span class="hljs-keyword">let</span>
testGridBigger = testGrid.biggerMap
puzzleGridBigger = puzzleGrid.biggerMap
<span class="hljs-keyword">echo</span> show testGridBigger</code></pre>
<pre><samp>11637517422274862853338597396444961841755517295286
13813736722492484783351359589446246169155735727126
21365113283247622439435873354154698446526571955763
36949315694715142671582625378269373648937148475914
74634171118574528222968563933317967414442817852555
13191281372421239248353234135946434524615754563572
13599124212461123532357223464346833457545794456865
31254216394236532741534764385264587549637569865174
12931385212314249632342535174345364628545647573965
23119445813422155692453326671356443778246755488935
22748628533385973964449618417555172952866628316397
24924847833513595894462461691557357271266846838237
32476224394358733541546984465265719557637682166874
47151426715826253782693736489371484759148259586125
85745282229685639333179674144428178525553928963666
24212392483532341359464345246157545635726865674683
24611235323572234643468334575457944568656815567976
42365327415347643852645875496375698651748671976285
23142496323425351743453646285456475739656758684176
34221556924533266713564437782467554889357866599146
33859739644496184175551729528666283163977739427418
35135958944624616915573572712668468382377957949348
43587335415469844652657195576376821668748793277985
58262537826937364893714847591482595861259361697236
96856393331796741444281785255539289636664139174777
35323413594643452461575456357268656746837976785794
35722346434683345754579445686568155679767926678187
53476438526458754963756986517486719762859782187396
34253517434536462854564757396567586841767869795287
45332667135644377824675548893578665991468977611257
44961841755517295286662831639777394274188841538529
46246169155735727126684683823779579493488168151459
54698446526571955763768216687487932779859814388196
69373648937148475914825958612593616972361472718347
17967414442817852555392896366641391747775241285888
46434524615754563572686567468379767857948187896815
46833457545794456865681556797679266781878137789298
64587549637569865174867197628597821873961893298417
45364628545647573965675868417678697952878971816398
56443778246755488935786659914689776112579188722368
55172952866628316397773942741888415385299952649631
57357271266846838237795794934881681514599279262561
65719557637682166874879327798598143881961925499217
71484759148259586125936169723614727183472583829458
28178525553928963666413917477752412858886352396999
57545635726865674683797678579481878968159298917926
57944568656815567976792667818781377892989248891319
75698651748671976285978218739618932984172914319528
56475739656758684176786979528789718163989182927419
67554889357866599146897761125791887223681299833479
</samp></pre>
<p>looks good, let's go for the prize:</p>
<pre><code class="nim hljs"><span class="hljs-keyword">let</span>
testGridBiggerDijkstra = testGridBigger.dijkstra
puzzleGridBiggerDijkstra = puzzleGridBigger.dijkstra
<span class="hljs-keyword">echo</span> <span class="hljs-string">"part2(test): "</span>, testGridBiggerDijkstra.data[^<span class="hljs-number">1</span>]
<span class="hljs-keyword">echo</span> <span class="hljs-string">"part2(puzzle): "</span>, puzzleGridBiggerDijkstra.data[^<span class="hljs-number">1</span>]</code></pre>
<pre><samp>part2(test): (risk: 315, dir: right)
part2(puzzle): (risk: 2993, dir: down)
</samp></pre>
<blockquote>
<p>That's the right answer! You are <em class="star">one gold star</em> closer to saving your vacation.</p>
</blockquote>
</main>
<footer>
<hr>
<div class="nb-box">
<span><span class="nb-small">made with <a href="https://pietroppeter.github.io/nimib/">nimib π³</a></span></span>
<span></span>
<span><button class="nb-small" id="show" onclick="toggleSourceDisplay()">Show Source</button></span>
</div>
</footer>
<section id="source">
<pre><code class="nim hljs"><span class="hljs-keyword">import</span> animu, nimib
nbInit(theme=useAdventOfNim)
nbText: <span class="hljs-string">"""## Day 15: [Chiton](https://adventofcode.com/2021/day/15)
Today is about path search on a grid. I tend to struggle with these
since I never properly studied the theory.
### Part 1
We need to go from top left to bottom right minimizing sum of risk.
My strategy will be to create from given grid a new grid that
at every "node" (it usually pays to think of these problems in terms of graphs),
will tell me the direction I should come from in order to minimize the risk and
get there. The final path will be found by following directions from bottom right.
Here are the inputs:
"""</span>
nbCode:
<span class="hljs-keyword">let</span>
testInput = <span class="hljs-string">"""
1163751742
1381373672
2136511328
3694931569
7463417111
1319128137
1359912421
3125421639
1293138521
2311944581"""</span>
puzzleInput = readFile(<span class="hljs-string">"2021/input15.txt"</span>)
nbText: <span class="hljs-string">"""I will be using grid code from my Day09 (no blogpost published),
copying and pasting here the useful bits (I will need to think of an ergonomic
way to import from a notebook). I am also fine with having a sentinel value
for stuff outside the grid that is a high value.
"""</span>
nbCode:
<span class="hljs-keyword">type</span>
<span class="hljs-type">Coord</span> = <span class="hljs-keyword">tuple</span>[x, y: <span class="hljs-built_in">int</span>]
<span class="hljs-type">Grid</span>[<span class="hljs-type">T</span>] = <span class="hljs-keyword">object</span>
data: <span class="hljs-built_in">seq</span>[<span class="hljs-type">T</span>]
yLen, xLen: <span class="hljs-built_in">int</span>
sentinel: <span class="hljs-type">T</span> <span class="hljs-comment"># value for outside the grid</span>
<span class="hljs-type">GridInt</span> = <span class="hljs-type">Grid</span>[<span class="hljs-built_in">int</span>]
<span class="hljs-type">Dir</span> = <span class="hljs-keyword">enum</span>
right, down, left, up
<span class="hljs-keyword">func</span> isOutside[<span class="hljs-type">T</span>](c: <span class="hljs-type">Coord</span>, g: <span class="hljs-type">Grid</span>[<span class="hljs-type">T</span>]): <span class="hljs-built_in">bool</span> =
c.x < <span class="hljs-number">0</span> <span class="hljs-keyword">or</span> c.x >= g.xLen <span class="hljs-keyword">or</span> c.y < <span class="hljs-number">0</span> <span class="hljs-keyword">or</span> c.y >= g.yLen
<span class="hljs-keyword">func</span> toIndex[<span class="hljs-type">T</span>](g: <span class="hljs-type">Grid</span>[<span class="hljs-type">T</span>], c: <span class="hljs-type">Coord</span>): <span class="hljs-built_in">int</span> =
<span class="hljs-keyword">if</span> c.isOutside(g):
-<span class="hljs-number">1</span>
<span class="hljs-keyword">else</span>:
c.y*g.xLen + c.x
<span class="hljs-keyword">func</span> `[]`[<span class="hljs-type">T</span>](g: <span class="hljs-type">Grid</span>[<span class="hljs-type">T</span>], c: <span class="hljs-type">Coord</span>): <span class="hljs-type">T</span> =
<span class="hljs-keyword">let</span> i = g.toIndex(c)
<span class="hljs-keyword">if</span> i < <span class="hljs-number">0</span>:
g.sentinel
<span class="hljs-keyword">else</span>:
g.data[i]
<span class="hljs-comment"># added today</span>
<span class="hljs-keyword">func</span> `[]=`[<span class="hljs-type">T</span>](g: <span class="hljs-keyword">var</span> <span class="hljs-type">Grid</span>[<span class="hljs-type">T</span>], c: <span class="hljs-type">Coord</span>, value: <span class="hljs-type">T</span>) =
<span class="hljs-keyword">let</span> i = g.toIndex(c)
<span class="hljs-keyword">if</span> i >= <span class="hljs-number">0</span>:
g.data[i] = value
<span class="hljs-keyword">func</span> parseInt(c: <span class="hljs-built_in">char</span>): <span class="hljs-built_in">int</span> =
<span class="hljs-literal">result</span> = ord(c) - ord(<span class="hljs-string">'0'</span>)
<span class="hljs-keyword">assert</span> <span class="hljs-literal">result</span> >= <span class="hljs-number">0</span> <span class="hljs-keyword">and</span> <span class="hljs-literal">result</span> <= <span class="hljs-number">9</span>
<span class="hljs-keyword">func</span> parse(text: <span class="hljs-built_in">string</span>): <span class="hljs-type">GridInt</span> =
<span class="hljs-comment"># result.data = newSeqOfCap(text.len)</span>
<span class="hljs-keyword">for</span> line <span class="hljs-keyword">in</span> text.strip.splitLines:
<span class="hljs-literal">result</span>.data.add line.toSeq.map(parseInt)
inc <span class="hljs-literal">result</span>.yLen
<span class="hljs-keyword">if</span> <span class="hljs-literal">result</span>.xLen == <span class="hljs-number">0</span>:
<span class="hljs-literal">result</span>.xLen = line.len
<span class="hljs-keyword">else</span>:
<span class="hljs-keyword">assert</span> line.len == <span class="hljs-literal">result</span>.xLen
<span class="hljs-literal">result</span>.sentinel = <span class="hljs-built_in">int</span>.<span class="hljs-keyword">high</span>
<span class="hljs-keyword">iterator</span> coords[<span class="hljs-type">T</span>](g: <span class="hljs-type">Grid</span>[<span class="hljs-type">T</span>]): <span class="hljs-type">Coord</span> =
<span class="hljs-keyword">for</span> y <span class="hljs-keyword">in</span> <span class="hljs-number">0</span> ..< g.yLen:
<span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> <span class="hljs-number">0</span> ..< g.xLen:
<span class="hljs-keyword">yield</span> (x, y)
<span class="hljs-keyword">func</span> `+`(c: <span class="hljs-type">Coord</span>, dir: <span class="hljs-type">Dir</span>): <span class="hljs-type">Coord</span> =
<span class="hljs-keyword">case</span> dir
<span class="hljs-keyword">of</span> right:
(c.x + <span class="hljs-number">1</span>, c.y)
<span class="hljs-keyword">of</span> down:
(c.x, c.y + <span class="hljs-number">1</span>)
<span class="hljs-keyword">of</span> left:
(c.x - <span class="hljs-number">1</span>, c.y)
<span class="hljs-keyword">of</span> up:
(c.x, c.y - <span class="hljs-number">1</span>)
nbText: <span class="hljs-string">"""
Let's use it to parse inputs:
"""</span>
nbCode:
<span class="hljs-keyword">let</span>
testGrid = parse testInput
puzzleGrid = parse puzzleInput
dump (testGrid.xlen, testGrid.ylen)
dump (puzzleGrid.xlen, puzzleGrid.ylen)
dump testGrid.sentinel
nbText: <span class="hljs-string">"""
I am not using a `GridDiff` (I did not copy related code),
I will be using a `GridRisk` which will tell
me minimal total risk up to here and best direction I should come from.
I will also use show functions to debug.
"""</span>
nbCode:
<span class="hljs-keyword">type</span>
<span class="hljs-type">Risk</span> = <span class="hljs-keyword">tuple</span>[risk: <span class="hljs-built_in">int</span>, dir: <span class="hljs-type">Dir</span>]
<span class="hljs-type">GridRisk</span> = <span class="hljs-type">Grid</span>[<span class="hljs-type">Risk</span>]
<span class="hljs-keyword">func</span> show(g: <span class="hljs-type">GridInt</span>): <span class="hljs-built_in">string</span> =
<span class="hljs-keyword">for</span> c <span class="hljs-keyword">in</span> g.coords:
<span class="hljs-literal">result</span>.add $g[c]
<span class="hljs-keyword">if</span> c.x == g.xLen - <span class="hljs-number">1</span>:
<span class="hljs-literal">result</span>.add <span class="hljs-string">'\n'</span>
<span class="hljs-keyword">func</span> show(g: <span class="hljs-type">GridRisk</span>, paddingCount=<span class="hljs-number">4</span>): <span class="hljs-built_in">string</span> =
<span class="hljs-keyword">for</span> c <span class="hljs-keyword">in</span> g.coords:
<span class="hljs-keyword">if</span> g[c].risk < g.sentinel.risk:
<span class="hljs-literal">result</span>.add align($(g[c].risk), paddingCount)
<span class="hljs-keyword">else</span>:
<span class="hljs-literal">result</span>.add align(<span class="hljs-string">"*"</span>, paddingCount)
<span class="hljs-keyword">if</span> c.x == g.xLen - <span class="hljs-number">1</span>:
<span class="hljs-literal">result</span>.add <span class="hljs-string">'\n'</span>
<span class="hljs-keyword">echo</span> show testGrid
nbText: <span class="hljs-string">"""
Here is the heart of the problem. Key for this is realizing
how to compute incrementally compute the risk.
"""</span>
nbCode:
<span class="hljs-keyword">func</span> computeRisk(g: <span class="hljs-type">GridInt</span>, gr: <span class="hljs-type">GridRisk</span>, c: <span class="hljs-type">Coord</span>): <span class="hljs-type">Risk</span> =
<span class="hljs-comment">## Computes Risk at Coord assuming Risk has been computed</span>
<span class="hljs-comment">## for cells on the left and above</span>
<span class="hljs-keyword">let</span>
riskUp = gr[c + up].risk + g[c]
riskLeft = gr[c + left].risk + g[c]
<span class="hljs-comment">#debugEcho "computeRisk for c: ", c</span>
<span class="hljs-comment">#debugEcho " riskUp: ", riskUp</span>
<span class="hljs-comment">#debugEcho " riskLeft: ", riskLeft</span>
<span class="hljs-keyword">if</span> riskUp <= riskLeft:
(riskUp, up)
<span class="hljs-keyword">else</span>:
(riskLeft, left)
<span class="hljs-keyword">func</span> computeGridRisk(g: <span class="hljs-type">GridInt</span>): <span class="hljs-type">GridRisk</span> =
<span class="hljs-literal">result</span>.xLen = g.xLen
<span class="hljs-literal">result</span>.yLen = g.ylen
<span class="hljs-literal">result</span>.sentinel = (g.sentinel - <span class="hljs-number">10</span>, up) <span class="hljs-comment"># forgot this line on first try</span>
<span class="hljs-comment"># need to do - 10 to avoid overflow</span>
<span class="hljs-literal">result</span>.data = @[(<span class="hljs-number">0</span>, up)] <span class="hljs-comment"># risk for initial position does not count</span>
<span class="hljs-keyword">for</span> c <span class="hljs-keyword">in</span> g.coords:
<span class="hljs-keyword">if</span> c == (<span class="hljs-number">0</span>, <span class="hljs-number">0</span>): <span class="hljs-keyword">continue</span>
<span class="hljs-literal">result</span>.data.add g.computeRisk(<span class="hljs-literal">result</span>, c)
<span class="hljs-keyword">func</span> part1(gr: <span class="hljs-type">GridRisk</span>): <span class="hljs-built_in">int</span> =
gr[(gr.xLen - <span class="hljs-number">1</span>, gr.yLen - <span class="hljs-number">1</span>)].risk
<span class="hljs-keyword">let</span>
testGridRisk = computeGridRisk testGrid
puzzleGridRisk = computeGridRisk puzzleGrid
<span class="hljs-keyword">echo</span> show testGridRisk
dump part1 testGridRisk
dump part1 puzzleGridRisk <span class="hljs-comment"># 719 wrong, too high!</span>
nbText: <span class="hljs-string">"""
I am stuck at the moment with _a correct test result and an incorrect
puzzle result_. Not really sure how to debug.
... after looking at our discord aoc I got a useful hint (thanks @Michal58!),
the example only gives a path where the solution only goes down and to the right
and this was also my (wrong) assumption! It is indeed possible
for a minimal solution to wiggle around all directions but
my algorithm for sure is not going to find it.
So I really need to implement [Dijkstra](https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm)
or [A*](https://en.wikipedia.org/wiki/A*_search_algorithm) algorithm!
But first let me give a minimal example that makes it clear why I need
the better approach:
"""</span>
nbCode:
<span class="hljs-keyword">let</span>
hintInput = <span class="hljs-string">"19999</span><span class="hljs-meta">\n</span><span class="hljs-string">19111</span><span class="hljs-meta">\n</span><span class="hljs-string">11191"</span>
hintGrid = parse hintInput
hintGridRisk = computeGridRisk hintGrid
<span class="hljs-keyword">echo</span> show hintGrid, <span class="hljs-string">"</span><span class="hljs-meta">\n</span><span class="hljs-string">"</span>, show hintGridRisk
nbText: <span class="hljs-string">"""
... _(a few hours later) back to writing the blogpost and writing my solution_.
This morning I shared the hint on [advent of code subreddit](https://www.reddit.com/r/adventofcode/comments/rgszh7/2021_day_15_part_1_hint_if_you_get_correct_answer/)
and it has been quite popular! The irony is that I have not yet taken advantage of the hint and finalized my solution π, so let's get to it.
I will implement Dijkstra's algorithm because it is simpler than A* (although in general less powerful) and also because of its
[compelling history](https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#History#:~:text=it%20was%20a%20twenty,pencil%20and%20paper)
(did you open last link on a chromium based browser? did you know what [text-fragments](https://web.dev/text-fragments/) are?
I didn't but having seen some weird highlighted stuff after google results I got curious...).
I will still be using my `GridRisk` type although it seems not completely appropriate...
The `risk` value will be the distance, I will try also to set the correct distance.
In the following implementation comments not in parenthesis are taken verbatim
from wikipedia's description of the algorithm. An important change I make
is to make sure I use a priority queue. Among the many Dijkstra implementations
that have been written today, I dare say this must rank among the worst...
""""</span>
nbCode:
<span class="hljs-keyword">import</span> std / heapqueue <span class="hljs-comment"># (not among my standard aoc imports)</span>
<span class="hljs-keyword">type</span>
<span class="hljs-type">Node</span> = <span class="hljs-keyword">tuple</span>[coord: <span class="hljs-type">Coord</span>, risk: <span class="hljs-built_in">int</span>]
<span class="hljs-keyword">proc</span> `<`(a, b: <span class="hljs-type">Node</span>): <span class="hljs-built_in">bool</span> = a.risk < b.risk
<span class="hljs-keyword">iterator</span> neighbours[<span class="hljs-type">T</span>](g: <span class="hljs-type">Grid</span>[<span class="hljs-type">T</span>], c: <span class="hljs-type">Coord</span>): (<span class="hljs-type">Coord</span>, <span class="hljs-type">Dir</span>) =
<span class="hljs-keyword">for</span> dir <span class="hljs-keyword">in</span> <span class="hljs-type">Dir</span>:
<span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> (c + dir).isOutside(g):
<span class="hljs-keyword">yield</span> (c + dir, dir)
<span class="hljs-keyword">func</span> dijkstra(g: <span class="hljs-type">GridInt</span>): <span class="hljs-type">GridRisk</span> =
<span class="hljs-comment"># (0. initialize result)</span>
<span class="hljs-literal">result</span>.xLen = g.xLen
<span class="hljs-literal">result</span>.yLen = g.ylen
<span class="hljs-literal">result</span>.sentinel = (g.sentinel, up)
<span class="hljs-comment"># 1. Mark all nodes unvisited. Create a set of all the unvisited nodes called the unvisited set.</span>
<span class="hljs-comment"># (I will instead create a visited set)</span>
<span class="hljs-comment"># (I will also create a priority queue for unvisited nodes, but I will start populating later)</span>
<span class="hljs-keyword">var</span>
visited = initHashSet[<span class="hljs-type">Coord</span>]()
unvisited = initHeapQueue[<span class="hljs-type">Node</span>]()
<span class="hljs-comment"># 2. Assign to every node a tentative distance value: set it to zero for our initial node and to infinity for all other nodes.</span>
<span class="hljs-literal">result</span>.data = @[(<span class="hljs-number">0</span>, up)] <span class="hljs-comment"># risk for initial position does not count</span>
<span class="hljs-keyword">for</span> c <span class="hljs-keyword">in</span> g.coords:
<span class="hljs-keyword">if</span> c == (<span class="hljs-number">0</span>, <span class="hljs-number">0</span>): <span class="hljs-keyword">continue</span>
<span class="hljs-literal">result</span>.data.add @[<span class="hljs-literal">result</span>.sentinel]
<span class="hljs-comment"># 3. For the current node, consider all of its unvisited neighbors</span>
<span class="hljs-comment"># and calculate their tentative distances through the current node.</span>
<span class="hljs-comment"># Compare the newly calculated tentative distance to the current assigned value</span>
<span class="hljs-comment"># and assign the smaller one</span>
<span class="hljs-keyword">var</span>
current = (<span class="hljs-number">0</span>, <span class="hljs-number">0</span>)
destination = (g.xLen - <span class="hljs-number">1</span>, g.yLen - <span class="hljs-number">1</span>)
risk: <span class="hljs-built_in">int</span>
<span class="hljs-comment"># 5. If the destination node has been marked visited then stop. The algorithm has finished.</span>
<span class="hljs-keyword">while</span> destination <span class="hljs-keyword">not_in</span> visited:
<span class="hljs-keyword">for</span> neighbour, dir <span class="hljs-keyword">in</span> g.neighbours(current):
<span class="hljs-keyword">if</span> neighbour <span class="hljs-keyword">in</span> visited:
<span class="hljs-keyword">continue</span>
risk = <span class="hljs-literal">result</span>[current].risk + g[neighbour]
<span class="hljs-keyword">if</span> risk < <span class="hljs-literal">result</span>[neighbour].risk:
<span class="hljs-literal">result</span>[neighbour] = (risk, dir)
unvisited.push (neighbour, risk) <span class="hljs-comment"># (push to queue)</span>
<span class="hljs-comment"># 4. When we are done considering all of the unvisited neighbors of the current node,</span>
<span class="hljs-comment"># mark the current node as visited and remove it from the unvisited set</span>
visited.incl current
<span class="hljs-keyword">if</span> current == destination: <span class="hljs-keyword">break</span> <span class="hljs-comment"># seems I need this (for puzzle input)</span>
<span class="hljs-comment"># 6. Otherwise, select the unvisited node that is marked with the smallest tentative distance,</span>
<span class="hljs-comment"># set it as the new current node, and go back to step 3.</span>
<span class="hljs-keyword">while</span> current <span class="hljs-keyword">in</span> visited: <span class="hljs-comment"># (I think it may happen that I pull from queue stuff already visited)</span>
<span class="hljs-keyword">if</span> len(unvisited) == <span class="hljs-number">0</span>:
debugEcho <span class="hljs-string">"current: "</span>, current
<span class="hljs-keyword">raise</span> <span class="hljs-type">ValueError</span>.newException <span class="hljs-string">"whaaaat?"</span>
current = unvisited.pop().coord <span class="hljs-comment"># (pull from queue)</span>
<span class="hljs-keyword">echo</span> show dijkstra(hintGrid)
<span class="hljs-keyword">echo</span> <span class="hljs-string">"</span><span class="hljs-meta">\n</span><span class="hljs-string">"</span>, show dijkstra(testGrid)
nbText: <span class="hljs-string">"results look good!"</span>
nbCode:
<span class="hljs-keyword">let</span> puzzleGridDijkstra = dijkstra(puzzleGrid)
<span class="hljs-keyword">echo</span> puzzleGridDijkstra.data[^<span class="hljs-number">1</span>]
gotTheStar
nbText: <span class="hljs-string">"""
### Part 2
Now the map is bigger, and from what I hear around, the implementation
with the priority queue might be key to have a working solution now.
Let's create the bigger maps and solve part 2:
"""</span>
nbCode:
<span class="hljs-keyword">func</span> biggerMap(g: <span class="hljs-type">GridInt</span>): <span class="hljs-type">GridInt</span> =
<span class="hljs-literal">result</span>.xLen = g.xLen*<span class="hljs-number">5</span>
<span class="hljs-literal">result</span>.yLen = g.yLen*<span class="hljs-number">5</span>
<span class="hljs-literal">result</span>.sentinel = g.sentinel
<span class="hljs-literal">result</span>.data = newSeqWith(len=g.data.len*<span class="hljs-number">25</span>): <span class="hljs-number">0</span>
<span class="hljs-keyword">for</span> coord <span class="hljs-keyword">in</span> <span class="hljs-literal">result</span>.coords:
<span class="hljs-keyword">let</span>
smallCoord = (coord.x <span class="hljs-keyword">mod</span> g.xLen, coord.y <span class="hljs-keyword">mod</span> g.yLen)
oneUps = (coord.x <span class="hljs-keyword">div</span> g.xLen) + (coord.y <span class="hljs-keyword">div</span> g.yLen)
<span class="hljs-literal">result</span>[coord] = (g[smallCoord] + oneUps - <span class="hljs-number">1</span>) <span class="hljs-keyword">mod</span> <span class="hljs-number">9</span> + <span class="hljs-number">1</span>
<span class="hljs-keyword">let</span>
testGridBigger = testGrid.biggerMap
puzzleGridBigger = puzzleGrid.biggerMap
<span class="hljs-keyword">echo</span> show testGridBigger
nbText: <span class="hljs-string">"looks good, let's go for the prize:"</span>
nbCode:
<span class="hljs-keyword">let</span>
testGridBiggerDijkstra = testGridBigger.dijkstra
puzzleGridBiggerDijkstra = puzzleGridBigger.dijkstra
<span class="hljs-keyword">echo</span> <span class="hljs-string">"part2(test): "</span>, testGridBiggerDijkstra.data[^<span class="hljs-number">1</span>]
<span class="hljs-keyword">echo</span> <span class="hljs-string">"part2(puzzle): "</span>, puzzleGridBiggerDijkstra.data[^<span class="hljs-number">1</span>]
gotTheStar
nbSave
</code></pre>
</section><script>
function toggleSourceDisplay() {
var btn = document.getElementById("show")
var source = document.getElementById("source");
if (btn.innerHTML=="Show Source") {
btn.innerHTML = "Hide Source";
source.style.display = "block";
} else {
btn.innerHTML = "Show Source";
source.style.display = "none";
}
}
</script></body>
</html>