summaryrefslogtreecommitdiff
path: root/src/days/3/3.zig
blob: 66c6f9c7e43ba2c719501bccda9292afe81827d2 (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
const std = @import("std");

pub fn main() !void {

    const buf = @embedFile("input");

    var lines = std.mem.tokenizeScalar(u8, buf, '\n');

    var sum: u64 = 0;

    const n = 12; // n = 2 for p1

    var digits_ind: [n]?usize = undefined;

    while (lines.next()) |line| {

        digits_ind[0] = 0;
        for (1..n) |i| {
            digits_ind[i] = null;
        }

        outer: for (1..line.len) |i| {

            const c = line[i];

            for (0..@min(n, i)) |digit| {

                const index = digits_ind[digit] orelse line.len;
                const char = if (index < line.len) line[index] else 0;

                if ((c > char and i < line.len-(n-1-digit)) or char == 0) {
                    digits_ind[digit] = i;

                    for (digit+1..n) |j| {
                        digits_ind[j] = null;
                    }
                    continue :outer;
                }
            }
        }

        var num: u64 = 0;
        for (digits_ind, 0..) |ind, i| {
            num += (line[ind.?] - '0')*std.math.pow(u64, 10, n-i-1);
        }


        sum += num;
    }

    std.debug.print("{}\n", .{sum});
}