diff options
Diffstat (limited to 'day11.zig')
-rw-r--r-- | day11.zig | 96 |
1 files changed, 96 insertions, 0 deletions
diff --git a/day11.zig b/day11.zig new file mode 100644 index 0000000..bcb5c2a --- /dev/null +++ b/day11.zig @@ -0,0 +1,96 @@ +const std = @import("std"); + +pub fn main() !void { + try std.fmt.format(std.io.getStdOut().writer(), "day 11 pt1: {}\n", .{try solve_pt1(std.heap.page_allocator, puzzle_input)}); +} + +const Coord = struct { + x: usize, + y: usize, +}; + +inline fn get(grid: []const u8, width: usize, x: usize, y: usize) u8 { + return grid[y*(width+1) + x]; +} + +fn solve_pt1(a: std.mem.Allocator, input: []const u8) !u64 { + const width: usize = std.mem.indexOfScalar(u8, input, '\n') orelse return error.BadInput; + const height: usize = (input.len / width + 1) - 1; + // std.log.warn("width {} height {}", .{width, height}); + const x_adjust = try a.alloc(usize, width); + defer a.free(x_adjust); + const y_adjust = try a.alloc(usize, height); + defer a.free(y_adjust); + var galaxies = std.ArrayList(Coord).init(a); + defer galaxies.deinit(); + var x_adj: usize = 0; + for (0..width) |x| { + var allspace = true; + for (0..height) |y| { + const ch = get(input, width, x, y); + if (ch == '#') { + try galaxies.append(.{.x = x, .y = y}); + allspace = false; + } + } + if (allspace) { + x_adj += 1; + } + x_adjust[x] = x_adj; + } + var y_adj:usize = 0; + for (0..height) |y| { + var allspace = true; + for (0..width) |x| { + const ch = get(input, width, x, y); + if (ch == '#') { + allspace = false; + } + } + if (allspace) { + y_adj += 1; + } + y_adjust[y] = y_adj; + } + + for (galaxies.items) |*gal| { + const x = gal.x; + const y = gal.y; + gal.* = .{ + .x = x + x_adjust[x], + .y = y + y_adjust[y], + }; + } + + var sum: usize = 0; + for (0..galaxies.items.len) |ix1| { + for (ix1..galaxies.items.len) |ix2| { + const g1 = galaxies.items[ix1]; + const g2 = galaxies.items[ix2]; + const x_diff = @max(g1.x, g2.x) - @min(g1.x, g2.x); + const y_diff = @max(g1.y, g2.y) - @min(g1.y, g2.y); + sum += x_diff + y_diff; + } + } + + return sum; +} + +test "pt1" { + try std.testing.expectEqual(@as(u64, 374), try solve_pt1(std.testing.allocator, test_input)); +} + +const test_input = +\\...#...... +\\.......#.. +\\#......... +\\.......... +\\......#... +\\.#........ +\\.........# +\\.......... +\\.......#.. +\\#...#..... +; + +const puzzle_input = @embedFile("day11.in");
\ No newline at end of file |