Xah Talk Show 2024-04-28 Ep549 WolframLang Coding, Advent of Code 2023, Day 8
- Timestamp
- 2:10 reading the problem
- 10:12 intro to WolframLang
- 12:08 Emacs Wolfram mode
- 13:05 start coding
- 17:56 emacs key macro, change brackets
- 27:19 counter, bane of functional programing
- 28:51 hand pain, RSI
- 1:23:36 first eval
- 1:25:12 pattern matching, haskell ocaml fsharp
- 1:45:31 graph analysis
- 1:53:30 intermission
- 2:01:25 1st solution and summary
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}} *)