Day 8

Author

Julia Romanowska

The input

First line are the directions. Afterwards, there are “nodes”.

root = dirname(@__FILE__);
input_file = joinpath(root, "..", "..", "DATA", "2023", "input_day08.txt");
#input_file = joinpath(root, "..", "..", "DATA", "2023", "example_input_day08.txt");
input_data = read(open(input_file, "r"), String);
directions , nodes_raw = split(input_data, "\n\n");
nodes = CSV.read(
    IOBuffer(nodes_raw),
    DataFrame;
    header = ["name", "value"],
    delim = " = "
)
702×2 DataFrame
677 rows omitted
Row name value
String3 String15
1 NFK (LMH, RSS)
2 SLJ (NBT, CDG)
3 SKX (SRC, KKX)
4 LRB (MNG, FSH)
5 QMQ (DMG, QRV)
6 VRB (PGG, PRG)
7 QNB (PFD, FFQ)
8 BPK (GFF, DFF)
9 JTD (NVV, VLD)
10 PXD (VNV, BDS)
11 PXP (VFH, DLR)
12 XRH (QMM, LDH)
13 GLV (SDM, MFS)
691 VVS (DJF, VFF)
692 QHG (BQK, JHJ)
693 SLT (PMX, HSS)
694 PDN (KLX, DXM)
695 DLT (XHV, PMS)
696 KKN (FTF, FCX)
697 BLX (QHG, LHJ)
698 GQH (VDG, PQN)
699 VLD (FGX, HVF)
700 KKX (GQT, QXD)
701 KKJ (BGQ, LFM)
702 LNJ (FNL, HMG)

Part 1

The problem

I can create a dictionary of pairs.

function create_pairs(s::AbstractString)
    m = match(r"\((?<left>\w+), (?<right>\w+)\)", s);
    return (m["left"], m["right"])
end
create_pairs (generic function with 1 method)
transform!(
    nodes,
    :value => ByRow(create_pairs) => :value
)
nodes_dict = Dict(zip(nodes.name, nodes.value))
Dict{String3, Tuple{SubString{String}, SubString{String}}} with 702 entries:
  "LFQ" => ("LSB", "RLM")
  "DRR" => ("NFK", "TKJ")
  "FHF" => ("VCB", "BKJ")
  "GQT" => ("NRN", "GLV")
  "TKL" => ("KCR", "XCT")
  "HTL" => ("CBJ", "BFM")
  "CGB" => ("RLV", "DPR")
  "VGB" => ("MRC", "XPH")
  "GNL" => ("HNK", "QQJ")
  "XQQ" => ("QNL", "XXJ")
  "RHM" => ("TFS", "TQL")
  "CHQ" => ("JDC", "MRB")
  "PTK" => ("CMJ", "KDK")
  "FCX" => ("RLJ", "TQN")
  "PMB" => ("PJX", "LTG")
  "LRK" => ("CKB", "HXV")
  "KNP" => ("FFB", "SSB")
  "KSV" => ("HGD", "SBH")
  "VFF" => ("CLD", "NGD")
  "VRR" => ("TGC", "MTP")
  "LRD" => ("XHC", "PBG")
  "PKR" => ("RSQ", "SBS")
  "SKX" => ("SRC", "KKX")
  "CTR" => ("XBB", "VRB")
  "GGJ" => ("GXB", "MPF")
  ⋮     => ⋮

And then, I need the sequence of directions.

The solution

How many steps from “AAA” to “ZZZ”?

function check_directions(c::Char)
    if c == 'L'
        return 1
    end
    return 2
end
check_directions (generic function with 1 method)
start_node = "AAA";
end_node = "ZZZ";
steps = 0;
direction_no = 1;

cur_node = start_node;
while cur_node != end_node
    cur_direction = check_directions(directions[direction_no]);
    global cur_node = nodes_dict[cur_node][cur_direction];
    global steps += 1;
    global direction_no += 1;
    if direction_no == lastindex(directions) + 1
        global direction_no = 1;
    end
end

The trip takes: 19783 steps.