diff --git a/src/days/day08.zig b/src/days/day08.zig index 5f695ee..87a7c79 100644 --- a/src/days/day08.zig +++ b/src/days/day08.zig @@ -53,6 +53,8 @@ pub fn run(allocator: std.mem.Allocator) !void { .index = junction_box_index, .position = .{ .v = .{ x, y, z } }, }; + std.debug.print("{f}\n", .{junction_box}); + try junction_boxes.append(allocator, junction_box); } @@ -70,16 +72,43 @@ pub fn run(allocator: std.mem.Allocator) !void { .to = other_junction_box, .length = length, }; + std.debug.print("{f}\n", .{connection}); + try possible_connections.append(allocator, connection); } } - for (junction_boxes.items) |junction_box| { - std.debug.print("{f}\n", .{junction_box}); - } + std.mem.sort(Connection, possible_connections.items, {}, struct { + fn f(_: void, lhs: Connection, rhs: Connection) bool { + return lhs.length < rhs.length; + } + }.f); + + var network_id: usize = 0; + for (possible_connections.items, 0..) |*connection, i| { + var connection_network_id = network_id; + for (possible_connections.items) |other_connection| { + if (connection.index == other_connection.index) { + continue; + } + if (other_connection.network == null) { + continue; + } + if (connection.connected(other_connection)) { + connection_network_id = other_connection.network.?; + } + } + + connection.network = connection_network_id; + if (connection_network_id == network_id) { + network_id += 1; + } - for (possible_connections.items) |connection| { std.debug.print("{f}\n", .{connection}); + + if (i >= 10) { + break; + } } } @@ -95,6 +124,14 @@ const Connection = struct { pub fn format(self: Self, w: *std.io.Writer) std.io.Writer.Error!void { try w.print("({d}) {d} to {d}, length = {d}, network = {?d}", .{self.index, self.from.index, self.to.index, self.length, self.network}); } + + pub fn connected(self: Self, other: Self) bool { + if (self.from.index == other.from.index) return true; + if (self.to.index == other.from.index) return true; + if (self.from.index == other.to.index) return true; + if (self.to.index == other.to.index) return true; + return false; + } }; const JunctionBox = struct {