const std = @import("std");

const path = "data/day09/input.txt";

const RetType = u10;

const directions = [4][2]i2{
    .{ 1, 0 },
    .{ 0, 1 },
    .{ -1, 0 },
    .{ 0, -1 },
};

const grid_row = 100;
const grid_col = 100;
const GridType = u4;
const Grid = [grid_row][grid_col]GridType;

pub fn parseInput() anyerror!Grid {
    const input = @embedFile(path);
    var lines = std.mem.split(u8, input, "\n");

    var g: Grid = undefined;

    var row: usize = 0;
    while (lines.next()) |line| : (row += 1) {
        for (line) |_, col| {
            g[row][col] = try std.fmt.parseUnsigned(GridType, line[col .. col + 1], 10);
        }
    }

    return g;
}

pub fn first(allocator: ?std.mem.Allocator) anyerror!RetType {
    _ = allocator;

    const grid = try parseInput();

    var ret: RetType = 0;
    for (grid) |line, row| {
        items: for (line) |item, col| {
            for (directions) |dir| {
                const diffrow = @intCast(i10, row) + dir[0];
                const diffcol = @intCast(i10, col) + dir[1];
                if ((diffrow < 0) or (diffrow >= grid_row)) continue;
                if ((diffcol < 0) or (diffcol >= grid_col)) continue;
                if (item >= grid[@intCast(usize, diffrow)][@intCast(usize, diffcol)]) {
                    continue :items;
                }
            }
            ret += item + 1;
        }
    }

    return ret;
}

pub fn main() anyerror!void {
    var timer = try std.time.Timer.start();
    const ret = try first(null);
    const f = timer.lap() / 1000;

    try std.testing.expectEqual(ret, @as(RetType, 550));

    std.debug.print("Day 9a result: {d} \t\ttime: {d}us\n", .{ ret, f });
}

test "day09a" {
    try std.testing.expectEqual(@as(RetType, 550), try first(std.testing.allocator));
}