From c3b014e2e1c7471ad0892214b9589e1f12c8132e Mon Sep 17 00:00:00 2001 From: Inga Date: Sun, 3 Dec 2023 17:43:49 +0000 Subject: [PATCH] day 3, part 2 --- day03-hard/build.zig | 70 ++++++++++++ day03-hard/sample.in | 10 ++ day03-hard/src/main.zig | 240 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 320 insertions(+) create mode 100644 day03-hard/build.zig create mode 100644 day03-hard/sample.in create mode 100644 day03-hard/src/main.zig diff --git a/day03-hard/build.zig b/day03-hard/build.zig new file mode 100644 index 0000000..f2c02f3 --- /dev/null +++ b/day03-hard/build.zig @@ -0,0 +1,70 @@ +const std = @import("std"); + +// Although this function looks imperative, note that its job is to +// declaratively construct a build graph that will be executed by an external +// runner. +pub fn build(b: *std.Build) void { + // Standard target options allows the person running `zig build` to choose + // what target to build for. Here we do not override the defaults, which + // means any target is allowed, and the default is native. Other options + // for restricting supported target set are available. + const target = b.standardTargetOptions(.{}); + + // Standard optimization options allow the person running `zig build` to select + // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. Here we do not + // set a preferred release mode, allowing the user to decide how to optimize. + const optimize = b.standardOptimizeOption(.{}); + + const exe = b.addExecutable(.{ + .name = "day03-hard", + // In this case the main source file is merely a path, however, in more + // complicated build scripts, this could be a generated file. + .root_source_file = .{ .path = "src/main.zig" }, + .target = target, + .optimize = optimize, + }); + + // This declares intent for the executable to be installed into the + // standard location when the user invokes the "install" step (the default + // step when running `zig build`). + b.installArtifact(exe); + + // This *creates* a Run step in the build graph, to be executed when another + // step is evaluated that depends on it. The next line below will establish + // such a dependency. + const run_cmd = b.addRunArtifact(exe); + + // By making the run step depend on the install step, it will be run from the + // installation directory rather than directly from within the cache directory. + // This is not necessary, however, if the application depends on other installed + // files, this ensures they will be present and in the expected location. + run_cmd.step.dependOn(b.getInstallStep()); + + // This allows the user to pass arguments to the application in the build + // command itself, like this: `zig build run -- arg1 arg2 etc` + if (b.args) |args| { + run_cmd.addArgs(args); + } + + // This creates a build step. It will be visible in the `zig build --help` menu, + // and can be selected like this: `zig build run` + // This will evaluate the `run` step rather than the default, which is "install". + const run_step = b.step("run", "Run the app"); + run_step.dependOn(&run_cmd.step); + + // Creates a step for unit testing. This only builds the test executable + // but does not run it. + const unit_tests = b.addTest(.{ + .root_source_file = .{ .path = "src/main.zig" }, + .target = target, + .optimize = optimize, + }); + + const run_unit_tests = b.addRunArtifact(unit_tests); + + // Similar to creating the run step earlier, this exposes a `test` step to + // the `zig build --help` menu, providing a way for the user to request + // running the unit tests. + const test_step = b.step("test", "Run unit tests"); + test_step.dependOn(&run_unit_tests.step); +} diff --git a/day03-hard/sample.in b/day03-hard/sample.in new file mode 100644 index 0000000..624ea4f --- /dev/null +++ b/day03-hard/sample.in @@ -0,0 +1,10 @@ +467..114.. +...*...... +..35..633. +......#... +617*...... +.....+.58. +..592..... +......755. +...$.*.... +.664.598.. \ No newline at end of file diff --git a/day03-hard/src/main.zig b/day03-hard/src/main.zig new file mode 100644 index 0000000..37a706c --- /dev/null +++ b/day03-hard/src/main.zig @@ -0,0 +1,240 @@ +const std = @import("std"); + +const Offset = enum(u2) { + Before = 0, + Same = 1, + After = 2, + + fn applyTo(self: *const Offset, index: usize) usize { + return (index + @intFromEnum(self.*)) - 1; + } +}; + +const Char = enum(u4) { + Zero = 0, + One = 1, + Two = 2, + Three = 3, + Four = 4, + Five = 5, + Six = 6, + Seven = 7, + Eight = 8, + Nine = 9, + Dot = 12, + MaybeGear = 13, + OtherSymbol = 14, + + fn isDigit(self: *const Char) bool { + return @intFromEnum(self.*) < 10; + } + + fn getDigit(self: *const Char) u4 { + return @intFromEnum(self.*); + } +}; + +fn StackList(comptime T: type, comptime capacity_type: type, comptime capacity: capacity_type) type { + return struct { + const Self = @This(); + mem: [capacity]T, + length: capacity_type, + + fn add(self: *Self, value: T) void { + self.mem[self.length] = value; + self.length += 1; + } + + fn init() Self { + return Self{ + .mem = undefined, + .length = 0, + }; + } + }; +} + +const CharInfo = struct { + adjacents: [8]Char, + this: Char, + + fn isAdjacentToSymbol(self: *const CharInfo) bool { + for (0..8) |i| { + if (self.adjacents[i] == .MaybeGear or self.adjacents[i] == .OtherSymbol) { + return true; + } + } + + return false; + } + + fn getGearNumbersLocations(self: *const CharInfo) ?[2][2]Offset { + if (self.this != .MaybeGear) { + return null; + } + + var locations = StackList(comptime [2]Offset, comptime u8, comptime 6).init(); + + // previous line + if (self.adjacents[0].isDigit()) { + locations.add(.{ .Before, .Before }); + if (!self.adjacents[1].isDigit() and self.adjacents[2].isDigit()) { + locations.add(.{ .Before, .After }); + } + } else if (self.adjacents[1].isDigit()) { + locations.add(.{ .Before, .Same }); + } else if (self.adjacents[2].isDigit()) { + locations.add(.{ .Before, .After }); + } + + // this line + if (self.adjacents[3].isDigit()) { + locations.add(.{ .Same, .Before }); + } + if (self.adjacents[4].isDigit()) { + locations.add(.{ .Same, .After }); + } + + // next line + if (self.adjacents[5].isDigit()) { + locations.add(.{ .After, .Before }); + if (!self.adjacents[6].isDigit() and self.adjacents[7].isDigit()) { + locations.add(.{ .After, .After }); + } + } else if (self.adjacents[6].isDigit()) { + locations.add(.{ .After, .Same }); + } else if (self.adjacents[7].isDigit()) { + locations.add(.{ .After, .After }); + } + + if (locations.length == 2) { + return .{ locations.mem[0], locations.mem[1] }; + } + + return null; + } +}; + +const State = struct { + number: u32 = 0, + is_adjacent_to_symbol: bool = false, + + fn addDigit(self: *State, char_info: CharInfo) void { + self.number = self.number * 10 + char_info.this.getDigit(); + self.is_adjacent_to_symbol = self.is_adjacent_to_symbol or char_info.isAdjacentToSymbol(); + } +}; + +fn getNumberAt(engine: [][]const CharInfo, x: usize, y: usize) u32 { + const line = engine[x]; + var index: usize = y; + while (index > 0) : (index -= 1) { + if (!line[index].this.isDigit()) { + break; + } + } + + if (!line[index].this.isDigit()) { + index += 1; + } + + var result: u32 = 0; + while (index < line.len) : (index += 1) { + if (!line[index].this.isDigit()) { + break; + } + + result = result * 10 + line[index].this.getDigit(); + } + + return result; +} + +fn solve(engine: [][]const CharInfo) u32 { + var result: u32 = 0; + + for (engine, 0..) |line, i| { + //std.debug.print("handling new line\n", .{}); + for (line, 0..) |char_info, j| { + //std.debug.print("handling: {s}({s})\n", .{ [_]u8{char_info.this}, char_info.adjacents }); + const gearNumberLocations = char_info.getGearNumbersLocations(); + if (gearNumberLocations) |*value| { + //std.debug.print("found gear at {d},{d}; relative number positions are {d},{d} and {d},{d}\n", .{ i, j, value[0][0], value[0][1], value[1][0], value[1][1] }); + const a = getNumberAt(engine, value[0][0].applyTo(i), value[0][1].applyTo(j)); + const b = getNumberAt(engine, value[1][0].applyTo(i), value[1][1].applyTo(j)); + result += a * b; + } + } + } + + return result; +} + +fn charLinesToCharInfoLines(allocator: std.mem.Allocator, char_lines: [][]const Char) ![][]const CharInfo { + var char_info_lines = try allocator.alloc([]CharInfo, char_lines.len); + for (0..char_lines.len) |i| { + const char_line = char_lines[i]; + var char_info_line = try allocator.alloc(CharInfo, char_line.len); + for (0..char_line.len) |j| { + char_info_line[j] = CharInfo{ .this = char_line[j], .adjacents = .{ + if (i > 0 and j > 0) char_lines[i - 1][j - 1] else .Dot, + if (i > 0) char_lines[i - 1][j] else .Dot, + if (i > 0 and j + 1 < char_line.len) char_lines[i - 1][j + 1] else .Dot, + if (j > 0) char_line[j - 1] else .Dot, + if (j + 1 < char_line.len) char_line[j + 1] else .Dot, + if (i + 1 < char_lines.len and j > 0) char_lines[i + 1][j - 1] else .Dot, + if (i + 1 < char_lines.len) char_lines[i + 1][j] else .Dot, + if (i + 1 < char_lines.len and j + 1 < char_line.len) char_lines[i + 1][j + 1] else .Dot, + } }; + } + + char_info_lines[i] = char_info_line; + } + + return char_info_lines; +} + +fn readInput(allocator: std.mem.Allocator, reader: anytype) ![][]const Char { + var lines = std.ArrayList([]Char).init(allocator); + var line_buffer: [1000]u8 = undefined; + while (try reader.readUntilDelimiterOrEof(&line_buffer, '\n')) |line_ref| { + var line = try allocator.alloc(Char, line_ref.len); + for (line_ref, line) |raw_char, *char| { + char.* = switch (raw_char) { + '0'...'9' => @enumFromInt(raw_char - '0'), + '.' => .Dot, + '*' => .MaybeGear, + else => .OtherSymbol, + }; + } + try lines.append(line); + } + + return lines.items; +} + +pub fn main() !void { + const stdout = std.io.getStdOut().writer(); + + const raw_in = std.io.getStdIn(); + var buffered_reader = std.io.bufferedReader(raw_in.reader()); + var reader = buffered_reader.reader(); + + var allocator_buffer: [1_000_000]u8 = undefined; + var fba = std.heap.FixedBufferAllocator.init(&allocator_buffer); + var allocator = fba.allocator(); + + var lines_arena = std.heap.ArenaAllocator.init(allocator); + const lines_allocator = lines_arena.allocator(); + const char_lines = try readInput(lines_allocator, reader); + + var info_lines_arena = std.heap.ArenaAllocator.init(allocator); + const info_lines_allocator = info_lines_arena.allocator(); + const info_lines = try charLinesToCharInfoLines(info_lines_allocator, char_lines); + lines_arena.deinit(); + + const result = solve(info_lines); + info_lines_arena.deinit(); + + try stdout.print("{d}\n", .{result}); +}