1
0

day13 part1

This commit is contained in:
xeals 2023-12-13 16:51:23 +11:00
parent fa7a9aab14
commit 794dddf854
Signed by: xeals
SSH Key Fingerprint: SHA256:pRv+8swQDA+/LuZ7NHj9m006BbKexlNK62OUA01ZZBc

105
src/day13.zig Normal file
View File

@ -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);
}