2024 day 18 part 2 with binary search

This commit is contained in:
Tristan 2024-12-19 00:25:35 +00:00
parent 5d8d809844
commit eefce852c2

View file

@ -28,7 +28,7 @@
inherit size bytes input; inherit size bytes input;
walls = init input; walls = init input;
part1result = p1Dijkstra.toGoal.steps; part1result = p1Dijkstra.toGoal.steps;
p1Dijkstra = searchAfterBytes 12; p1Dijkstra = searchAfterBytes bytes;
searchAfterBytes = bytes: let searchAfterBytes = bytes: let
walls = lib.sublist 0 bytes (init input); walls = lib.sublist 0 bytes (init input);
@ -41,19 +41,40 @@
height = size; height = size;
}; };
findFirst = bytes: prevPath: let findFirst = {
dijkstra = lib.traceSeq "retracing after ${toString bytes} with ${key wall}" (searchAfterBytes bytes); index ? bytes,
wall = elemAt walls (bytes - 1); max ? length walls - 1
wallCollides = elem (key wall) (map ({pos,...}: pos) prevPath); }: let
in if !wallCollides calcAt = i: rec {
then findFirst (bytes + 1) prevPath index = i;
else wall = elemAt walls (i - 1);
if dijkstra.isImpossible dijkstra = lib.traceSeq "retracing after ${toString index} with ${key wall}" (searchAfterBytes i);
then key wall possible = !dijkstra.isImpossible;
else };
findFirst (bytes + 1) dijkstra.path;
part2result = findFirst bytes p1Dijkstra.path; thisByte = calcAt index;
maxByte = calcAt max;
midByte = calcAt (index + (max - index) / 2);
isEnd = index == maxByte.index;
rightHalf = lib.traceSeq
"going right to ${toString (midByte.index + 1)}-${toString max}"
(findFirst {index = midByte.index + 1; inherit max;});
leftHalf = lib.traceSeq
"going left to ${toString index}-${toString (midByte.index - 1)}"
(findFirst {index = index + 1; max = midByte.index;});
in
if isEnd then key thisByte.wall else
if !thisByte.possible then "oof" else
if midByte.possible then
rightHalf
else
leftHalf
;
part2result = findFirst {};
}; };