about summary refs log tree commit diff
path: root/aoc/2021/08/part-two.zig
blob: ae8bf095697a7f566240bd3e6bca6aebc0da5f7e (plain) (blame)
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
const indexOfScalar = std.mem.indexOfScalar;
const print = std.debug.print;
const std = @import("std");
const tokenize = std.mem.tokenize;

const digits = [_]u7{
    0b1110111,
    0b0010010,
    0b1011101,
    0b1011011,
    0b0111010,
    0b1101011,
    0b1101111,
    0b1010010,
    0b1111111,
    0b1111011,
    //8687497
};

pub fn main() void {
    var sum: usize = 0;
    defer print("{}\n", .{ sum });

    var input = tokenize(@embedFile("input"), "\n");
    while (input.next()) |line| {
        var freq = [_]u8{ 0 } ** 7;
        for (line[0..58]) |c|
            switch (c) {
                'a'...'g' => freq[c - 'a'] += 1,
                else => {},
            };

        var patterns = tokenize(line[0..58], " ");
        while (patterns.next()) |p|
            if (p.len == 4)
                for (freq) |*f, i| {
                    if (indexOfScalar(u8, p, 'a' + @intCast(u8, i))) |_|
                        f.* -= 6;
                }; // 8687497 to 8021437

        var display: [7]u3 = undefined;
        for (freq) |f, i|
            display[i] = switch (f) {
                8 => 0, 0 => 1, 2 => 2, 1 => 3, 4 => 4, 3 => 5, 7 => 6,
                else => unreachable,
            };

        var output = tokenize(line[61..], " ");
        var pow: usize = 1000;
        while (output.next()) |s| : (pow /= 10) {
            var digit: u7 = 0;
            for (s) |c|
                digit |= @as(u7, 0b1000000) >> display[c - 'a'];
            sum += pow * indexOfScalar(u7, digits[0..], digit).?;
        }
    }
}