Finish day11, part 1
This commit is contained in:
parent
5a8bf21386
commit
37b740f07a
2 changed files with 683 additions and 2 deletions
|
|
@ -1,7 +1,79 @@
|
|||
const std = @import("std");
|
||||
|
||||
pub const title = "Day 11";
|
||||
pub const title = "Day 11: Reactor";
|
||||
|
||||
pub fn run(_: std.mem.Allocator) !void {
|
||||
pub fn run(allocator: std.mem.Allocator) !void {
|
||||
const input = @embedFile("./input/day11.txt");
|
||||
//const input =
|
||||
// \\aaa: you hhh
|
||||
// \\you: bbb ccc
|
||||
// \\bbb: ddd eee
|
||||
// \\ccc: ddd eee fff
|
||||
// \\ddd: ggg
|
||||
// \\eee: out
|
||||
// \\fff: out
|
||||
// \\ggg: out
|
||||
// \\hhh: ccc fff iii
|
||||
// \\iii: out
|
||||
// ;
|
||||
|
||||
var lines = std.mem.tokenizeScalar(u8, input, '\n');
|
||||
|
||||
var devices: std.StringHashMap([][]const u8) = .init(allocator);
|
||||
defer {
|
||||
var outputs_iter = devices.valueIterator();
|
||||
while (outputs_iter.next()) |value| {
|
||||
allocator.free(value.*);
|
||||
}
|
||||
devices.deinit();
|
||||
}
|
||||
|
||||
while (lines.next()) |line| {
|
||||
const device = line[0..3];
|
||||
std.debug.print("device = {s}\n", .{device});
|
||||
|
||||
var outputs: std.ArrayList([]const u8) = .empty;
|
||||
defer outputs.deinit(allocator);
|
||||
|
||||
var outputs_iter = std.mem.tokenizeScalar(u8, line[5..], ' ');
|
||||
while (outputs_iter.next()) |output| {
|
||||
try outputs.append(allocator, output);
|
||||
}
|
||||
|
||||
const outputs_slice = try outputs.toOwnedSlice(allocator);
|
||||
errdefer allocator.free(outputs_slice);
|
||||
|
||||
try devices.put(device, outputs_slice);
|
||||
}
|
||||
|
||||
var paths_to_out: usize = 0;
|
||||
visitOutputs("you", devices, &paths_to_out);
|
||||
|
||||
var buffer: [8]u8 = undefined;
|
||||
var stdout_writer = std.fs.File.stdout().writer(&buffer);
|
||||
const stdout = &stdout_writer.interface;
|
||||
|
||||
try stdout.print("{d}\n", .{paths_to_out});
|
||||
|
||||
try stdout.flush();
|
||||
}
|
||||
|
||||
fn visitOutputs(
|
||||
start: []const u8,
|
||||
devices: std.StringHashMap([][]const u8),
|
||||
paths_to_out: *usize,
|
||||
) void {
|
||||
const device = devices.get(start);
|
||||
if (device) |outputs| {
|
||||
for (outputs) |output| {
|
||||
if (std.mem.eql(u8, output, "out")) {
|
||||
paths_to_out.* += 1;
|
||||
} else {
|
||||
visitOutputs(output, devices, paths_to_out);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
std.debug.print("device {s} not found\n", .{start});
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue