aboutsummaryrefslogtreecommitdiff
path: root/2021/02/second.zig
blob: 3126118431f2d8a999a7799499828dec2de2b8ac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
const std = @import("std");

const example = @embedFile("example");
const input = @embedFile("input");

pub fn main() anyerror!void {
    const result = try solve(input);
    try std.io.getStdOut().writer().print("{}\n", .{result});
}

fn solve(puzzle: []const u8) !u64 {
    var it = std.mem.tokenize(u8, puzzle, "\n");
    var aim: u64 = 0;
    var pos: u64 = 0;
    var depth: u64 = 0;
    while (it.next()) |line| {
        var it2 = std.mem.tokenize(u8, line, " ");
        const step = it2.next() orelse unreachable;
        const n: u64 = std.fmt.parseInt(u64, it2.next().?, 10) catch unreachable;
        switch (step[0]) {
            'f' => {
                pos += n;
                depth += n * aim;
            },
            'd' => aim += n,
            'u' => aim -= n,
            else => unreachable,
        }
    }
    return pos * depth;
}

test "solve" {
    try std.testing.expectEqual(solve(example), 900);
}