~jamesnvc/advent_2021

advent_2021/p15.pl -rw-r--r-- 13.2 KiB
9f3efbed — James N. V. Cash Day 18 6 months ago
                                                                                
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
:- module(p15, []).
/*--- Day 15: Chiton ---

You've almost reached the exit of the cave, but the walls are getting closer together. Your submarine can barely still fit, though; the main problem is that the walls of the cave are covered in chitons, and it would be best not to bump any of them.

The cavern is large, but has a very low ceiling, restricting your motion to two dimensions. The shape of the cavern resembles a square; a quick scan of chiton density produces a map of risk level throughout the cave (your puzzle input). For example:

1163751742
1381373672
2136511328
3694931569
7463417111
1319128137
1359912421
3125421639
1293138521
2311944581

You start in the top left position, your destination is the bottom right position, and you cannot move diagonally. The number at each position is its risk level; to determine the total risk of an entire path, add up the risk levels of each position you enter (that is, don't count the risk level of your starting position unless you enter it; leaving it adds no risk to your total).

Your goal is to find a path with the lowest total risk. In this example, a path with the lowest total risk is highlighted here:

1163751742
1381373672
2136511328
3694931569
7463417111
1319128137
1359912421
3125421639
1293138521
2311944581

The total risk of this path is 40 (the starting position is never entered, so its risk is not counted).

What is the lowest total risk of any path from the top left to the bottom right?
--- Part Two ---

Now that you know how to find low-risk paths in the cave, you can try to find your way out.

The entire cave is actually five times larger in both dimensions than you thought; the area you originally scanned is just one tile in a 5x5 tile area that forms the full map. Your original map tile repeats to the right and downward; each time the tile repeats to the right or downward, all of its risk levels are 1 higher than the tile immediately up or left of it. However, risk levels above 9 wrap back around to 1. So, if your original map had some position with a risk level of 8, then that same position on each of the 25 total tiles would be as follows:

8 9 1 2 3
9 1 2 3 4
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7

Each single digit above corresponds to the example position with a value of 8 on the top-left tile. Because the full map is actually five times larger in both dimensions, that position appears a total of 25 times, once in each duplicated tile, with the values shown above.

Here is the full five-times-as-large version of the first example above, with the original map in the top left corner highlighted:

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

Equipped with the full map, you can now find a path from the top left corner to the bottom right corner with the lowest total risk:

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

The total risk of this path is 315 (the starting position is still never entered, so its risk is not counted).

Using the full map, what is the lowest total risk of any path from the top left to the bottom right?

*/

:- use_module(library(apply_macros)).
:- use_module(library(dcg/basics), [integer//1, digits//1, whites//0, nonblanks//1, string_without//2]).
:- use_module(library(dcg/high_order), [sequence//3, sequence//5]).
:- use_module(library(pure_input), [phrase_from_file/2]).
:- use_module(library(aggregate), [aggregate_all/3]).
:- use_module(library(clpfd), [transpose/2]).
:- use_module(library(apply), [maplist/2, maplist/3, maplist/4, include/3, partition/4]).
:- use_module(library(heaps)).
:- use_module(library(lists), [sum_list/2]).
:- use_module(library(ordsets), [ord_seteq/2]).
:- use_module(library(yall)).

integers(Nums) -->
    digits(Ds), { maplist([D, N]>>number_codes(N, [D]), Ds, Nums) }.

:- dynamic cell/3.

assert_cells(Grid) :-
    length(Grid, YMax),
    nth0(0, Grid, Row_), length(Row_, XMax),
    forall(( between(1, YMax, Y),
             between(1, XMax, X) ),
           ( nth1(Y, Grid, Row),
             nth1(X, Row, Val),
             assertz(cell(X, Y, Val) ))).

:- table path(_, _, _, _, min) as subsumptive.

path(FromX, FromY, ToX, ToY, Risk) :-
    neighbour(FromX, FromY, ToX, ToY),
    cell(ToX, ToY, Risk).
path(FromX, FromY, ToX, ToY, Risk) :-
    path(FromX, FromY, MidX, MidY, Risk0),
    neighbour(MidX, MidY, ToX, ToY),
    cell(ToX, ToY, Risk1),
    Risk is Risk0 + Risk1.

neighbour(X, Y, Xn, Yn) :-
    member(e(Xeq, Yeq), [e(X + 1, Y),
                         e(X, Y + 1),
                         e(X - 1, Y),
                         e(X, Y - 1)]),
    Xn is Xeq, Yn is Yeq.

solve1(Ans) :-
    retractall(cell(_, _, _)),
    abolish_module_tables(p15),
    File = '15_test',
    phrase_from_file(sequence(integers, "\n", Grid0), File),
    exclude(==([]), Grid0, Grid),
    assert_cells(Grid),
    length(Grid, YMax),
    nth0(0, Grid, Row_), length(Row_, XMax),
    path(1 ,1, XMax, YMax, Ans).

assert_cells_tiled(Grid) :-
    length(Grid, YMax),
    nth0(0, Grid, Row_), length(Row_, XMax),
    forall(( between(1, YMax, Y),
             between(1, XMax, X),
             between(0, 4, TileX),
             between(0, 4, TileY) ),
           ( nth1(Y, Grid, Row),
             nth1(X, Row, Val),
             Xt is X + XMax * TileX,
             Yt is Y + YMax * TileY,
             ValT is mod((Val - 1) + TileX + TileY, 9) + 1,
             assertz(cell(Xt, Yt, ValT) ))).

% A = 2821.
solve2(Ans) :-
    retractall(cell(_, _, _)),
    abolish_module_tables(p15),
    File = '15_input',
    phrase_from_file(sequence(integers, "\n", Grid0), File),
    exclude(==([]), Grid0, Grid),
    assert_cells_tiled(Grid),
    length(Grid, YMax0),
    nth0(0, Grid, Row_), length(Row_, XMax0),
    YMax is YMax0 * 5, XMax is XMax0 * 5,
    % works, but is slow...should probably be using an actual graph search algorithm
    % % 149,402,607 inferences, 52.662 CPU in 52.778 seconds (100% CPU, 2837009 Lips)
    %% path(1 ,1, XMax, YMax, Ans).
    % A*
    % 162,021,945 inferences, 26.407 CPU in 26.444 seconds (100% CPU, 6135591 Lips)
    astar_path(p(1, 1), p(XMax, YMax), Ans).

est_cost(p(Endx, Endy), p(X, Y), CostEst) :-
    cell(Endx, Endy, EndCost),
    % Lower constant => more searching
    % 5* finishes fast, but gives the wrong answer..
    % 3* gives the right answer for test, closer for real input...
    % 1* is slower (~25s vs ~2s for real input), but is correct
    % ...but is an order of magnitude slower
    % abs not really needed here, since we're always going to max x & y
    CostEst is (abs(Endx - X) + abs(Endy - Y)) + EndCost.

astar_path(Start, End, Cost) :-
    singleton_heap(OpenSet, 0, Start),
    rb_empty(GScore0), % cost from start to N
    rb_insert(GScore0, Start, 0, GScore),
    rb_empty(FScore0), % estimated cost from Start to End via N
    est_cost(End, Start, EstStart),
    rb_insert(FScore0, Start, EstStart, FScore),
    astar_path(End, OpenSet, GScore, FScore, Cost).

astar_path(_, OpenSet, _, _, _) :- empty_heap(OpenSet), !, throw(error(domain, "couldn't find a path")).
astar_path(End, OpenSet0, GScore0, FScore0, Cost) :-
    get_from_heap(OpenSet0, _, Current, OpenSet1),
    ( Current == End
    -> default_lookup(Current, Cost, GScore0)
    ;  ( add_neighbours(End, Current,
                        OpenSet1, OpenSet2,
                        GScore0, GScore1,
                        FScore0, FScore1),
         astar_path(End, OpenSet2, GScore1, FScore1, Cost) ) ).

default_lookup(Key, Value, Tree) :-
    rb_lookup(Key, Value, Tree), !.
default_lookup(_, 1.0Inf, _).

add_neighbours(End, p(Cx, Cy),
               OpenSet0, OpenSet1, GScore0, GScore1, FScore0, FScore1) :-
    findall(p(X, Y)-S, ( neighbour(Cx, Cy, X, Y), cell(X, Y, S) ),
            NeighboursScore),
    default_lookup(p(Cx, Cy), CurrentScore, GScore0),
    foldl({CurrentScore, End}/[Point-Cost, s(O0, G0, F0), s(O1, G1, F1)]>>(
              TentScore is CurrentScore + Cost,
              default_lookup(Point, CurPointScore, G0),
              ( TentScore >= CurPointScore
              -> ( O1 = O0, G1 = G0, F1 = F0 )
              ;  ( rb_insert(G0, Point, TentScore, G1),
                   est_cost(End, Point, EstCost0),
                   EstCost is EstCost0 + TentScore,
                   rb_insert(F0, Point, EstCost, F1),
                   % if already present, update priority?
                   add_to_heap(O0, EstCost, Point, O1) )
              )
          ),
          NeighboursScore,
          s(OpenSet0, GScore0, FScore0),
          s(OpenSet1, GScore1, FScore1)
         ).