Xah Talk Show 2023-12-28 Advent of Code Day 5, Live Coding, in WolframLang

Advent of Code 2023, Day 5, Problem Description

seeds: 79 14 55 13

seed-to-soil map:
50 98 2
52 50 48

soil-to-fertilizer map:
0 15 37
37 52 2
39 0 15

fertilizer-to-water map:
49 53 8
0 11 42
42 0 7
57 7 4

water-to-light map:
88 18 7
18 25 70

light-to-temperature map:
45 77 23
81 45 19
68 64 13

temperature-to-humidity map:
0 69 1
1 0 69

humidity-to-location map:
60 56 37
56 93 4

efficient solution

(* advent of code, day 5, part 1.

efficient solution.

*)

{seeds, maps} = Get[ "c:/Users/xah/web/xahlee_info/talk_show/i/advent_of_code_2023_day_5_parsed_input.m" ];

getDestID =
 Function[{seed, xrange},
  If[xrange === {}, seed,
   With[{sourceStart = xrange[[2]], destStart = xrange[[1]],
     numOfItems = xrange[[3]]},
    If[sourceStart <= seed <= sourceStart + numOfItems - 1,
     seed - sourceStart + destStart, seed]]]]

Function[{aSeed},
  Fold[Function[{xseed, triplets},
    getDestID[xseed,
     Select[triplets, ((#[[2]] <= xseed <= #[[2]] + #[[3]] - 1) &),
       1] // Flatten]], aSeed, maps]] /@ seeds //Min

(* 
result
484023871
 *)

inefficient solution

(* advent of code, day 5, part 1.

solution.

works, however, when taking the user input, it ran out of memory.
because, the user input, each triplet is hundred million items.

algorithm
turn each range to a association

*)

seeds = {79, 14, 55, 13};

maps = {
{{50, 98, 2}, {52, 50, 48}},
{ {0, 15, 37}, {37, 52, 2}, {39, 0, 15}},
{{49, 53, 8}, {0, 11, 42}, {42, 0, 7}, {57, 7, 4}},
{ {88, 18, 7}, {18, 25, 70}},
{ {45, 77, 23}, {81, 45, 19}, {68, 64, 13}},
{ {0, 69, 1}, {1, 0, 69}},
{ {60, 56, 37}, {56, 93, 4}}
};

maps2 = Map[
  Function[{x},
   Association[
    Rule @@@ (Transpose@{Range[x[[2]], x[[2]] + x[[3]] - 1],
        Range[x[[1]], x[[1]] + x[[3]] - 1]})]], maps, {2}];

map3 = Map[ Function[ KeySort[Union@@#]] , maps2];

Map[ Function[{sd}, Fold[ Function[{x,y}, Lookup[y, x, x] ], sd , map3] ] , seeds] //Min

(* sample input result is 35 *)

(* explanation.
turn each range into a association.
 *)