From b3b47eb8664a6f530fb33df6a1a5ffbe6c86cb32 Mon Sep 17 00:00:00 2001 From: Martin Ashby Date: Sun, 3 Dec 2023 22:18:37 +0000 Subject: Add comments to day3 --- day3.zig | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/day3.zig b/day3.zig index 4fe95b5..04c432f 100644 --- a/day3.zig +++ b/day3.zig @@ -55,6 +55,11 @@ const Grid = struct { } }; +// iterate over the map +// tracking if we're in a 'span' of digits +// at the end of the 'span', parse the number and check all the surrounding +// cells. If any are symbols other than . or a digit, then this span is a +// part number and add it to the sum. fn solve(a: std.mem.Allocator, input: []const u8) !u32 { var spanBuf = std.ArrayList(u8).init(a); var spanStart: usize = 0; // easier than backtracking @@ -103,6 +108,13 @@ fn solve(a: std.mem.Allocator, input: []const u8) !u32 { return sum; } +// iterate over the map, finding 'spans' like before. +// Except this time, store the span's number in a arraylist +// and record the number's index in the cells (in a 'shadow' grid) +// where the span covered the cell +// Then make a second pass to find gears, and check the 'shadow' grid +// for adjescent spans. If there are exactly 2 adjescent spans, +// lookup their values from the arraylist and multiple them together! fn solve_pt2(a: std.mem.Allocator, input: []const u8) !u32 { var spanBuf = std.ArrayList(u8).init(a); var spanStart: usize = 0; // easier than backtracking @@ -141,6 +153,7 @@ fn solve_pt2(a: std.mem.Allocator, input: []const u8) !u32 { var sum: u32 = 0; var spixes = std.AutoHashMap(usize, bool).init(a); defer spixes.deinit(); + // find gears for (0..grid.height) |y| { for (0..grid.width) |x| { const ch = grid.get(x, y) orelse @panic("borken"); @@ -149,6 +162,7 @@ fn solve_pt2(a: std.mem.Allocator, input: []const u8) !u32 { const mx = std.math.sub(usize, x, 1) catch x; const my = std.math.sub(usize, y, 1) catch y; + // Find adjescent spans spixes.clearRetainingCapacity(); for (mx..(x+2)) |x_p| { for (my..(y+2)) |y_p| { -- cgit v1.2.3-ZIG