2024 day 16 struggles

This commit is contained in:
Tristan 2024-12-17 14:58:14 +00:00
parent 0b105c6396
commit a3e9984d4b
3 changed files with 158 additions and 93 deletions

View file

@ -3,7 +3,7 @@
inherit (lib) splitString mod range;
inherit (lib.lists) findFirstIndex imap0;
inherit (lib.strings) stringToCharacters;
inherit (builtins) elemAt concatStringsSep length elem filter foldl' concatLists floor deepSeq listToAttrs attrValues attrNames mapAttrs hasAttr;
inherit (builtins) elemAt concatStringsSep length elem filter foldl' concatLists floor deepSeq listToAttrs attrValues attrNames mapAttrs hasAttr sort;
index = i: list: elemAt list i;
index2d = {x, y}: m: m |> index y |> index x;
@ -52,18 +52,18 @@
in
if
index2d fwd init.chart == "#"
then null
then {pos = null; dist = null;}
else
if (isNode fwd || fwd == init.goal || fwd == init.pos)
if (isCorner fwd || fwd == init.goal || fwd == init.pos)
then {
name = (key fwd);
value = score + 1;
pos = (key fwd);
dist = score + 1;
}
else
search {pos = fwd; inherit dir; score = score + 1;}
;
isNode = pos: index2d pos init.chart == "." &&
isCorner = pos: index2d pos init.chart == "." &&
(dirs
|> mapAttrs (name: dir: let n = addVec pos dir; in index2d n init.chart == ".")
|> ({north, east, south, west}:
@ -72,126 +72,192 @@
key = {x, y}: "${toString (y + 1)},${toString (x + 1)}";
nodes = range 1 (init.width - 3) |> map (x:
corners = range 1 (init.width - 3) |> map (x:
range 1 (init.height - 3) |> map (y: {inherit x y;})
)
|> concatLists
|> filter isNode
|> filter isCorner
|> (nodes: nodes ++ [init.pos init.goal])
|> map (pos: {
name = key pos;
value = {
value = ({
north = search {inherit pos; dir = dirs.north;};
east = search {inherit pos; dir = dirs.east;};
south = search {inherit pos; dir = dirs.south;};
west = search {inherit pos; dir = dirs.west;};
} |> lib.filterAttrs (n: v: !isNull v);
} |> lib.filterAttrs (n: v: !isNull v.pos)) // {
# pos = key pos;
};
})
|> listToAttrs;
graph = pkgs.runCommand "graph" {} ''
notNull = value: !isNull value;
###### collecting continuous corners, doesn't work.
countDirs = {north ? null, south ? null, east ? null, west ? null, ...}:
[north south east west]
|> filter (dir: notNull dir && notNull dir.pos)
|> length
;
continue = prev: {dirs, dist ? 0}: let
dir = if prev == "north" then "south" else
if prev == "south" then "north" else
if prev == "west" then "east" else
if prev == "east" then "west" else
throw "${toString prev} is not a direction!";
prevEdge = dirs.${dir};
in
dirs |> lib.attrsToList |> lib.findFirst (
{name, value}: !(name == dir) && !(isDead value)
) null
|> (res: res.value // {dir = res.name;})
|> (next: let
nextCorner = corners.${next.pos};
in
if isDead nextCorner || isDeadend nextCorner then null else
if isNode nextCorner
then next // {dist = next.dist + dist + prevEdge.dist + 1000;}
else continue next.dir {
dirs = nextCorner;
dist = dist + prevEdge.dist + 1000;
}
)
;
isDead = corner: corner.pos or null == null;
isNode = corner: let c = countDirs corner; in isTerminal corner || c > 2 || c == 1;
isTerminal = corner: corner.pos == key init.goal || corner.pos == key init.pos;
isDeadend = corner: let c = countDirs corner; in c == 1;
nodes = corners |> mapAttrs (start: corner:
joinNodes corner
);
joinNodes = corner:
corner |> mapAttrs (dir: next:
if isDead next || isDeadend next
then null
else if !isNode corners.${next.pos}
then continue dir {dirs = corners.${next.pos};}
else
next // {inherit dir;})
|> lib.filterAttrs (n: v: notNull v)
;
########
nodeGraph = graph: pkgs.runCommand "graph" {} ''
mkdir -p $out
echo 'digraph {
${nodes |> mapAttrs (from: tos:
tos |> mapAttrs (dir: edge: if isNull edge then "" else ''
"${from}" -> "${edge.name}" [label="${dir} ${toString edge.value}"]
${graph |> mapAttrs (from: edges:
edges |> mapAttrs (dir: edge: if isNull edge.pos or null then "" else ''
"${from}" -> "${edge.pos}" [label="${dir} ${toString edge.dist}"]
'') |> attrValues |> concatStringsSep "\n"
) |> attrValues |> concatStringsSep "\n"}
}' > $out/graph.dot
cat $out/graph.dot | ${pkgs.graphviz}/bin/dot -Tsvg > $out/graph.svg
'';
getPath = {
pos ? key init.pos
, goal
, dir ? "east"
, score ? 0
, hist ? []
, acc ? {}
}: let
node = nodes.${pos};
in attrNames node |> foldl' (best: edgedir:
lib.traceSeq acc
(let
newHist = hist ++ [edge.name value];
edge = node.${edgedir};
turnCost = if edgedir == dir then 0 else 1000;
value = edge.value + turnCost;
newScore = score + value;
in
if isNull edge || elem edge.name hist || (hasAttr "score" best && newScore > best.score) then best else
if edge.name == goal && (hasAttr "score" best -> newScore < best.score) then
({score = newScore;})
else
getPath {
pos = edge.name;
dir = edgedir;
score = newScore;
hist = newHist;
acc = best;
inherit goal;
}
)) acc;
graphs = {
corners = nodeGraph corners;
nodes = nodeGraph nodes;
};
initScores = {
scores = mapAttrs (n: v:
if n == key init.pos then {dir = "east"; score = 0; pos = n;}
else {dir = null; score = null; pos = n;}
) nodes;
done = [];
${key init.pos} = {
dir = "east";
steps = 0;
turns = 0;
pos = key init.pos;
};
};
getScores = state: let
getLowest = state: let
unvisited = removeAttrs state.scores state.done;
top = attrValues unvisited |> foldl' (acc: node:
if isNull acc.score then node else
if isNull node.score then acc else
if acc.score < node.score then acc else node
) {score = null;};
in
nodes.${top.pos}
|> mapAttrs (dir: {name, value}: let
turnCost = if top.dir == dir then 0 else 1000;
existing = state.scores.${name};
score = top.score + value + turnCost;
isBetter = isNull existing.score || existing.score > score;
in {
inherit name;
value = if elem name state.done || !isBetter then existing else {
inherit dir score;
pos = name;
attrValues unvisited |> foldl' (acc: node:
if isNull acc.turns then node else
if isNull node.turns then acc else
if acc.turns < node.turns then acc else node
) {turns = null; steps = null;}
;
getScores = {done ? [], scores ? initScores}: let
prev = getLowest {inherit done scores;};
in
corners.${prev.pos}
|> mapAttrs (dir: edge: let
turns = if prev.dir == dir then prev.turns else prev.turns + 1;
existing = scores.${edge.pos} or null;
steps = prev.steps + edge.dist;
sameSteps = notNull existing
&& existing.steps == steps
# && turns == existing.turns
;
isBetter = isNull existing ||
(existing.steps > steps);
newScore = {
inherit steps dir turns;
inherit (edge) pos;
prev = prev.pos;
};
in {
name = edge.pos;
value = if sameSteps then
existing // {alt = newScore;}
else if isBetter
then newScore
else existing
;
})
|> attrValues
|> listToAttrs
|> (newScores: {
scores = state.scores // newScores;
done = state.done ++ [top.pos];
scores = scores // newScores;
done = done ++ [prev.pos];
})
;
getPriority = {scores, done}: scores
|> lib.attrsToList
|> filter ({name, ...}: !elem name done)
|> filter ({value, ...}: !isNull value.score)
|> sortQueue
;
lessThan = a: b: isNull a || isNull b || a < b;
sortQueue = q: q
|> builtins.sort (a: b: lessThan a.value.score b.value.score)
# |> (q: lib.traceSeq (map (v: v.value.score) q) q)
|> map ({name, value}: {
pos = name;
inherit (value) dir score;
})
;
fastest = s: let
fastest = goal: s: let
next = getScores s;
in if elem (key init.goal) next.done then next else fastest next;
in if elem (key goal) (next.done) then next else fastest goal next;
pathScore = steps: turns: steps + turns * 1000;
toGoal = (fastest init.goal {}).scores.${key init.goal};
part1result = pathScore toGoal.steps toGoal.turns;
# PART 2
# WIP:
# go through the path, add each pos to visited
# if point has alt, find points on that path not visited yet.
# add length of filtered alt, (-1 for the overlap at end?).
# add alt to visited.
pathToList = scores: pos:
let
res = scores.${pos};
prevPath = if res ? prev then pathToList scores res.prev else [];
fullaltPath = pathToList scores res.alt.prev;
joinIndex = findFirstIndex ({pos,...}: !elem pos (map ({pos, ...}: pos) prevPath)) null fullaltPath;
altPath = lib.sublist (joinIndex - 1) (length fullaltPath) fullaltPath;
thisSpot = {inherit (res) pos steps turns dir; };
in
prevPath
++
[(thisSpot // {
alt = if res ? alt then altPath ++ [thisSpot] else null;
})]
;
cornerScores = fastest init.goal {};
part1path = (pathToList cornerScores.scores (key init.goal));
part1result = (fastest initScores).scores.${key init.goal};
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 245 KiB

View file

@ -1 +0,0 @@
/nix/store/3dxw74x2scq38j9m84r6m3iq320npwn4-graph