aboutsummaryrefslogtreecommitdiff
path: root/day3.zig
diff options
context:
space:
mode:
authorMartin Ashby <martin@ashbysoft.com>2023-12-03 22:18:37 +0000
committerMartin Ashby <martin@ashbysoft.com>2023-12-03 22:18:37 +0000
commitb3b47eb8664a6f530fb33df6a1a5ffbe6c86cb32 (patch)
tree09ba4fbe23a12f550b53ecf4a57c63fc069381fe /day3.zig
parent4700fa924ab82ca2e41daa627a59f691d8177d5b (diff)
downloadaoc2023-b3b47eb8664a6f530fb33df6a1a5ffbe6c86cb32.tar.gz
aoc2023-b3b47eb8664a6f530fb33df6a1a5ffbe6c86cb32.tar.bz2
aoc2023-b3b47eb8664a6f530fb33df6a1a5ffbe6c86cb32.tar.xz
aoc2023-b3b47eb8664a6f530fb33df6a1a5ffbe6c86cb32.zip
Add comments to day3
Diffstat (limited to 'day3.zig')
-rw-r--r--day3.zig14
1 files changed, 14 insertions, 0 deletions
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| {