= dirname(@__FILE__);
root = joinpath(root, "..", "..", "DATA", "2023", "input_day08.txt");
input_file #input_file = joinpath(root, "..", "..", "DATA", "2023", "example_input_day08.txt");
= read(open(input_file, "r"), String); input_data
Day 8
The input
First line are the directions. Afterwards, there are “nodes”.
= split(input_data, "\n\n");
directions , nodes_raw = CSV.read(
nodes IOBuffer(nodes_raw),
DataFrame;= ["name", "value"],
header = " = "
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)
= match(r"\((?<left>\w+), (?<right>\w+)\)", s);
m return (m["left"], m["right"])
end
create_pairs (generic function with 1 method)
transform!(
nodes,:value => ByRow(create_pairs) => :value
)= Dict(zip(nodes.name, nodes.value)) nodes_dict
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)
= "AAA";
start_node = "ZZZ";
end_node = 0;
steps = 1;
direction_no
= start_node;
cur_node while cur_node != end_node
= check_directions(directions[direction_no]);
cur_direction 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.