1
Fork 0
mirror of https://github.com/thegeneralist01/aoc synced 2026-03-07 10:59:54 +01:00
This commit is contained in:
TheGeneralist 2024-12-04 19:31:04 +01:00
parent 5982a62d70
commit 1d9f361587
Signed by: thegeneralist01
SSH key fingerprint: SHA256:pp9qddbCNmVNoSjevdvQvM5z0DHN7LTa8qBMbcMq/R4
5 changed files with 372 additions and 0 deletions

78
2 Normal file
View file

@ -0,0 +1,78 @@
const std = @import("std");
const input = @embedFile("test");
fn string_from_grid_intervals(grid: [][]const u8, y1: u64, y2: u64, x1: u64, x2: u64, ally: std.mem.Allocator) ![]const u8 {
var result = std.ArrayList(u8).init(ally);
defer result.deinit();
std.debug.print("y1: {d} y2: {d} x1: {d} x2: {d}\n", .{ y1, y2, x1, x2 });
for (grid[y1..y2]) |row| {
for (row[x1..x2]) |c| {
std.debug.print("{c}", .{ c });
try result.append(c);
}
}
return result.toOwnedSlice();
}
fn xmas_exists(grid: [][]const u8, x: u64, y: u64, x_len: u64, y_len: u64, ally: std.mem.Allocator) bool {
var exists = false;
// Right
if (x_len >= x + 4) {
exists = exists or std.mem.eql(u8, grid[y][x..x+4], "XMAS");
}
// Left
if (!exists and x >= 3) {
exists = exists or std.mem.eql(u8, grid[y][x-3..x+1], "XMAS");
}
// Top
if (!exists and y >= 3) {
exists = exists or std.mem.eql(u8, string_from_grid_intervals(grid, y-3, y+1, x, x+1, ally), "XMAS");
}
// Bottom
if (!exists and y_len >= y + 4) {
exists = exists or std.mem.eql(u8, string_from_grid_intervals(grid, y, y+4, x, x+1, ally), "XMAS");
}
// Top Right
if (!exists and x_len >= x + 4 and y - 3 >= 0) {
exists = exists or std.mem.eql(u8, string_from_grid_intervals(grid, y-3, y+1, x, x+4, ally), "XMAS");
}
// Bottom Right
if (!exists and x_len >= x + 4 and y_len >= y + 4) {
exists = exists or std.mem.eql(u8, string_from_grid_intervals(grid, y, y+4, x, x+4, ally), "XMAS");
}
// Top Left
if (!exists and x - 3 >= 0 and y - 3 >= 0) {
exists = exists or std.mem.eql(u8, string_from_grid_intervals(grid, y-3, y+1, x-3, x+1, ally), "XMAS");
}
// Bottom Left
if (!exists and x - 3 >= 0 and y_len >= y + 4) {
exists = exists or std.mem.eql(u8, string_from_grid_intervals(grid, y, y+4, x-3, x+1, ally), "XMAS");
}
return exists;
}
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const ally = gpa.allocator();
defer _ = gpa.deinit();
var lines = std.mem.tokenize(u8, input, "\r\n");
var grid = std.ArrayList([]const u8).init(ally);
defer grid.deinit();
while (lines.next()) |line| {
if (line.len > 0) {
try grid.append(line);
}
}
var xmas: u16 = 0;
for (grid.items, 0..) |row, y| {
for (row, 0..) |_, x| {
if (xmas_exists(grid.items, x, y, row.len, grid.items.len, ally)) xmas += 1;
}
}
}