From 794dddf854820854c9086cb23974230dfd11a1df Mon Sep 17 00:00:00 2001 From: xeals Date: Wed, 13 Dec 2023 16:51:23 +1100 Subject: [PATCH] day13 part1 --- src/day13.zig | 105 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 src/day13.zig diff --git a/src/day13.zig b/src/day13.zig new file mode 100644 index 0000000..62d358a --- /dev/null +++ b/src/day13.zig @@ -0,0 +1,105 @@ +const std = @import("std"); +const util = @import("util.zig"); +const mem = std.mem; + +pub fn main() !void { + const input = @embedFile("data/day13.txt"); + const sln = try solve(util.gpa, input); + std.debug.print("{d}\n", .{sln.a}); + std.debug.print("{d}\n", .{sln.b}); +} + +const Solution = struct { + a: usize, + b: usize, +}; + +fn findReflection(input: []const []const u8) usize { + if (input.len == 0) return 0; + std.debug.print("{s}\n", .{input}); + + const h = input.len; + const w = input[0].len; + + // Scan vertical reflectivity + for (0..w - 1) |scan| { + var offset: usize = 0; + var row: usize = 0; + while (input[row][scan - offset] == input[row][scan + offset + 1]) { + // std.debug.print("{} {}±{}\n", .{ row, scan, offset }); + row = (row + 1) % h; + if (row == 0) offset += 1; + if (scan < offset or scan + offset + 1 >= w) { + return scan + 1; + } + } + } + + // Scan horizontal reflectivity + for (0..h - 1) |scan| { + var offset: usize = 0; + var col: usize = 0; + while (input[scan - offset][col] == input[scan + offset + 1][col]) { + // std.debug.print("{}±{} {}\n", .{ scan, offset, col }); + col = (col + 1) % w; + if (col == 0) offset += 1; + if (scan < offset or scan + offset + 1 >= h) { + return (scan + 1) * 100; + } + } + } + + unreachable; +} + +fn solve(alloc: mem.Allocator, input: []const u8) !Solution { + var curr_pattern = std.ArrayList([]const u8).init(alloc); + defer curr_pattern.deinit(); + + var it = util.splitLines(input); + var sum: usize = 0; + while (it.next()) |line| { + if (line.len == 0) { + const pattern = try curr_pattern.toOwnedSlice(); + defer alloc.free(pattern); + const score = findReflection(pattern); + // std.debug.print("{}\n", .{score}); + sum += score; + } else { + try curr_pattern.append(line); + } + } + + return .{ .a = sum, .b = 0 }; +} + +test "silver" { + const input = + \\#.##..##. + \\..#.##.#. + \\##......# + \\##......# + \\..#.##.#. + \\..##..##. + \\#.#.##.#. + \\ + \\#...##..# + \\#....#..# + \\..##..### + \\#####.##. + \\#####.##. + \\..##..### + \\#....#..# + \\ + ; + const sln = try solve(std.testing.allocator, input); + try std.testing.expectEqual(@as(usize, 405), sln.a); +} + +test "gold" { + const input = + \\ + ; + const sln = try solve(std.testing.allocator, input); + try std.testing.expectEqual(@as(usize, 0), sln.b); +}