1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
|
const std = @import("std");
pub const log_level: std.log.Level = .info;
pub fn main() !void {
try std.fmt.format(std.io.getStdOut().writer(), "Day 8 pt1: {}\n", .{try solve_pt1(std.heap.page_allocator, puzzle_input)});
try std.fmt.format(std.io.getStdOut().writer(), "Day 8 pt2: {}\n", .{try solve_pt2(std.heap.page_allocator, puzzle_input)});
}
const NodeValue = struct {
left: []const u8,
right: []const u8,
};
fn solve_pt1(a: std.mem.Allocator, input: []const u8) !u64 {
var spl = std.mem.split(u8, input, "\n\n");
const instructions = spl.first();
const nodes_str = spl.next() orelse return error.NoNodes;
var spl2 = std.mem.split(u8, nodes_str, "\n");
var nodes = std.StringHashMap(NodeValue).init(a);
defer nodes.deinit();
while (spl2.next()) |node_line| {
var toks = std.mem.tokenize(u8, node_line, " (,)=");
const key = toks.next() orelse return error.NoKey;
const left = toks.next() orelse return error.NoLeft;
const right = toks.next() orelse return error.NoRight;
try nodes.putNoClobber(key, .{
.left = left,
.right = right,
});
}
var steps: u64 = 0;
var pos: []const u8 = "AAA";
while (!std.mem.eql(u8, pos, "ZZZ")) {
for (instructions) |inst| {
const node_value = nodes.get(pos).?;
pos = switch (inst) {
'R' => node_value.right,
'L' => node_value.left,
else => return error.InvalidDirection,
};
steps += 1;
}
}
return steps;
}
test "pt1" {
try std.testing.expectEqual(@as(u64, 6), try solve_pt1(std.testing.allocator, test_input));
}
const HistEntry = struct {
node: []const u8,
step: u64,
};
const Path = struct {
// current position
pos: []const u8,
// list of the _endpoints_ we have reached.
endpoints: std.ArrayList(HistEntry),
// at n*cycle + offset this path is finished where n is integer > 0
offset: ?u64 = null,
cycle: ?u64 = null,
fn init(a: std.mem.Allocator, start: []const u8) !Path {
return .{
.pos = start,
.endpoints = std.ArrayList(HistEntry).init(a),
};
}
fn visit(self: *Path, node: []const u8) void {
self.pos = node;
}
fn check(self: *Path, step: u64) !void {
if (self.cycle != null) return; // we already found the cycle for this one
if (self.pos[2] == 'Z') { // we hit an endpoint
for (self.endpoints.items) |hi| { // did we aleady hit this endpoint?
if (std.mem.eql(u8, hi.node, self.pos)) {
self.offset = hi.step;
self.cycle = step - hi.step;
return;
}
}
try self.endpoints.append(.{ .node = self.pos, .step = step });
}
}
};
fn solve_pt2(a: std.mem.Allocator, input: []const u8) !u64 {
var spl = std.mem.split(u8, input, "\n\n");
const instructions = spl.first();
const nodes_str = spl.next() orelse return error.NoNodes;
var spl2 = std.mem.split(u8, nodes_str, "\n");
var nodes = std.StringHashMap(NodeValue).init(a);
defer nodes.deinit();
while (spl2.next()) |node_line| {
var toks = std.mem.tokenize(u8, node_line, " (,)=");
const key = toks.next() orelse return error.NoKey;
const left = toks.next() orelse return error.NoLeft;
const right = toks.next() orelse return error.NoRight;
try nodes.putNoClobber(key, .{
.left = left,
.right = right,
});
}
var pos: []Path = blk: {
var pl = std.ArrayList(Path).init(a);
defer pl.deinit();
var ki = nodes.keyIterator();
while (ki.next()) |k| {
if (k.*[2] == 'A') { // ends with an A
std.log.info("start pos {s}", .{k.*});
try pl.append(try Path.init(a, k.*));
}
}
break :blk try pl.toOwnedSlice();
};
defer a.free(pos);
var log = std.time.timestamp() + 10;
var steps: u64 = 0;
while (!ends(pos)) {
// > repeat the whole sequence of instructions as necessary
// always repeat the whole set
for (instructions) |inst| {
for (pos) |*p| {
const node_value = nodes.get(p.pos).?;
p.visit(switch (inst) {
'R' => node_value.right,
'L' => node_value.left,
else => return error.InvalidDirection,
});
}
}
steps += instructions.len;
// logging...
const now = std.time.timestamp();
if (now > log) {
for (pos) |p| {
std.log.info("pos {s}", .{p.pos});
}
log = now + 10;
}
// now check for cycles
for (pos) |*p| {
try p.check(steps);
}
// now... check if we have detected a cycle on _all_ tracks
for (pos) |p| {
if (p.cycle == null) break;
} else {
std.log.info("all routes have cycled, using LCM", .{});
// great, so we haven't reached the end but we can probably calculate it.
var l = lcm(pos[0].cycle.?, pos[1].cycle.?);
for (pos[2..]) |p| {
l = lcm(l, p.cycle.?);
}
// so, this is our answer?
return l;
}
}
return steps;
}
fn ends(pos: []Path) bool {
for (pos) |p| {
if (p.pos[2] != 'Z') {
return false;
}
} else {
std.log.err("ends true", .{});
for (pos) |p| {
std.log.err("{s}", .{p.pos});
}
return true;
}
}
fn lcm(a: u64, b: u64) u64 {
return (a * b) / std.math.gcd(a, b);
}
test "pt2" {
try std.testing.expectEqual(@as(u64, 6), try solve_pt2(std.testing.allocator, test_input2));
}
const test_input =
\\LLR
\\
\\AAA = (BBB, BBB)
\\BBB = (AAA, ZZZ)
\\ZZZ = (ZZZ, ZZZ)
;
const test_input2 =
\\LR
\\
\\11A = (11B, XXX)
\\11B = (XXX, 11Z)
\\11Z = (11B, XXX)
\\22A = (22B, XXX)
\\22B = (22C, 22C)
\\22C = (22Z, 22Z)
\\22Z = (22B, 22B)
\\XXX = (XXX, XXX)
;
const puzzle_input = @embedFile("day8.in");
|