Xah Talk Show 2024-04-28 Ep549 WolframLang Coding, Advent of Code 2023, Day 8

xts WolframLang 2024-04-28 Xtz
xts WolframLang 2024-04-28 Xtz
xts WolframLang 2024-04-28 WVW
xts WolframLang 2024-04-28 WVW
RL

AAA = (BBB, CCC)
BBB = (DDD, EEE)
CCC = (ZZZ, GGG)
DDD = (DDD, DDD)
EEE = (EEE, EEE)
GGG = (GGG, GGG)
ZZZ = (ZZZ, ZZZ)

short version:

(* Advent of Code 2023, Day 8 *)

xinput = StringSplit[ "LLR", ""];

t = Association[
"AAA" -> {"BBB", "BBB"},
"BBB" -> {"AAA", "ZZZ"},
"ZZZ" -> {"ZZZ", "ZZZ"}
]

ff[{"ZZZ", x_, n_, y_}] := {"ZZZ", x, n, y}
ff[{v_, {}, n_, y_}] := ff[{v, y, n, y}]
ff[{v_, {"L", r___}, n_, y_}] := { t[v][[1]], {r}, n + 1, y }
ff[{v_ , {"R", r___}, n_, y_}] := { t[v][[2]], {r}, n + 1, y }

Print @ FixedPoint[ ff, {"AAA", xinput, 0, xinput}, 20000 ]

(* {ZZZ, {}, 6, {L, L, R}} *)

code with explanation:

xinput = StringSplit[ "LLR", ""];

xtable = Association[
"AAA" -> {"BBB", "BBB"},
"BBB" -> {"AAA", "ZZZ"},
"ZZZ" -> {"ZZZ", "ZZZ"}
]

Clear[ xnavigator ];
(*
xnavigator.
the function takes 1 arg, of the form
{node, steps, counter, originalSteps}
and return the same thing, with steps reduced by one,
and counter increased by one.
*)

xnavigator[{"ZZZ", x_, counter_, y_}] := {"ZZZ", x, counter, y}

xnavigator[{node_, {}, counter_, originalSteps_}] :=
xnavigator[{node, originalSteps, counter, originalSteps}]

xnavigator[{ node_ , {"L", rest___}, counter_, originalSteps_}] :=
{
Lookup[ xtable, node ]//First,
{rest},
counter+1,
originalSteps
}

xnavigator[{ node_ , {"R", rest___}, counter_, originalSteps_}] :=
{
Lookup[ xtable, node ]//Last,
{rest},
counter+1,
originalSteps
}

(*
start at aaa,
take one step from input, increment counter,
if result is zzz, stop. print counter.
else, repeat.
*)

(* Print @ *)
(* xnavigator[{"AAA", {"R"}, 3, xinput}] *)

Print @
FixedPoint[
xnavigator,
{"AAA", xinput, 0, xinput},
20000
]

(* {ZZZ, {}, 6, {L, L, R}} *)