summaryrefslogtreecommitdiff
path: root/src/day03.zig
blob: 0a5e27e76de2b95b43c3b01749da0637ddb6e2dc (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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
const std = @import("std");
const mecha = @import("mecha");
const print = std.debug.print;

pub fn solve(part: []u8, buffer: []u8, allocator: std.mem.Allocator) !void {
    if (std.mem.eql(u8, part, "1")) {
        try part1(buffer, allocator);
    } else {
        try part2(buffer, allocator);
    }
}

fn part1(buffer: []const u8, allocator: std.mem.Allocator) !void {
    const mul = mecha.combine(.{ mecha.string("mul(").discard(), mecha.int(usize, .{}), mecha.ascii.char(',').discard(), mecha.int(usize, .{}), mecha.ascii.char(')').discard() });

    var sum: usize = 0;
    var rest = buffer;
    while (rest.len > 0) {
        const result = mul.parse(allocator, rest) catch {
            rest = rest[1..];
            continue;
        };
        sum += result.value[0] * result.value[1];
        rest = result.rest;
    }

    print("{d}", .{sum});
}

// UGLY
fn part2(buffer: []const u8, allocator: std.mem.Allocator) !void {
    const mul = mecha.combine(.{ mecha.string("mul(").discard(), mecha.int(usize, .{}), mecha.ascii.char(',').discard(), mecha.int(usize, .{}), mecha.ascii.char(')').discard() });

    const dont = mecha.string("don't()");
    const do = mecha.string("do()");

    var sum: usize = 0;
    var rest = buffer;
    var disabled = false;
    while (rest.len > 0) {
        if (disabled) {
            _ = do.parse(allocator, rest) catch {
                rest = rest[1..];
                continue;
            };
            disabled = false;
        } else {
            const result = mul.parse(allocator, rest) catch {
                const result = dont.parse(allocator, rest) catch {
                    rest = rest[1..];
                    continue;
                };
                rest = result.rest;
                disabled = true;
                continue;
            };
            sum += result.value[0] * result.value[1];
            rest = result.rest;
        }
    }

    print("{d}", .{sum});
}