Xah Talk Show 2024-05-07 Ep552 WolframLang Coding, Advent of Code 2023, Day 9

0 3 6 9 12 15
1 3 6 10 15 21
10 13 16 21 30 45
Differences[{10, 13, 16, 21, 30, 45}]
(* {3, 3, 5, 9, 15} *)

Differences[ {1,2} ]
(* {1} *)

Differences[ {1} ]
(* {} *)

Differences[ {} ]
(* {} *)

(* apply Differences recursively *)

FixedPointList[
Function[{x}, Differences[ x ]],
{10, 13, 16, 21, 30, 45}
 ]
(* 
{
{10, 13, 16, 21, 30, 45},
{3, 3, 5, 9, 15},
{0, 2, 4, 6},
{2, 2, 2},
{0, 0},
{0},
{},
{}}
*)

(* example of what FixedPoint do *)
FixedPoint[ f , 3, 4]
(* f[f[f[f[3]]]] *)

FixedPointList[ f , 3, 4]
(* {3, f[3], f[f[3]], f[f[f[3]]], f[f[f[f[3]]]]} *)

solution

(* solution
Advent of Code 2023, Day 9, part 1
 *)

input = "
0 3 6 9 12 15
1 3 6 10 15 21
10 13 16 21 30 45";

input = ReadString[ "c:/Users/xah/web/xahlee_info/talk_show/i/advent_of_code_2023_day_9_input.txt" ];

(* parse input string. turn them into a list of list of number *)
input2 = ToExpression[ Map[ Function[{x}, StringSplit[ x, " " ]],
 StringSplit[ input, "\n" ]] ];
(*
{
{0, 3, 6, 9, 12, 15},
{1, 3, 6, 10, 15, 21},
{10, 13, 16, 21, 30, 45}
}
*)

Total @
Map[
Function[{xline},
Total @ Map[
Function[{yy}, If[yy === {}, 0, Last[yy]]] ,
FixedPointList[ Function[{x}, Differences[ x ]], xline ] ] ],
 input2]

short solution

(* solution Advent of Code 2023, Day 9, part 1 *)

input = "
0 3 6 9 12 15
1 3 6 10 15 21
10 13 16 21 30 45";

input2 = ToExpression@ (StringSplit /@ StringSplit[ input, "\n" ]) ;

Total @ (( Total @ (((If[# === {}, 0, Last[#]]) &) /@ FixedPointList[ Differences , # ]) & ) /@ input2)