From 43b7e42dca9ea770ccb094d799480984f8f4bcae Mon Sep 17 00:00:00 2001 From: Nguyễn Gia Phong Date: Wed, 8 Dec 2021 15:39:14 +0700 Subject: [aoc/2021] Add day 8 Part two is the ziggiest Zig I've ever written! --- aoc/2021/08/part-one.zig | 18 +++++++++++++++ aoc/2021/08/part-two.zig | 60 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+) create mode 100644 aoc/2021/08/part-one.zig create mode 100644 aoc/2021/08/part-two.zig (limited to 'aoc') diff --git a/aoc/2021/08/part-one.zig b/aoc/2021/08/part-one.zig new file mode 100644 index 0000000..0a9ad93 --- /dev/null +++ b/aoc/2021/08/part-one.zig @@ -0,0 +1,18 @@ +const print = std.debug.print; +const std = @import("std"); +const tokenize = std.mem.tokenize; + +pub fn main() !void { + var count: usize = 0; + defer print("{}\n", .{ count }); + + var input = tokenize(@embedFile("input"), "\n"); + while (input.next()) |line| { + var output = tokenize(line[61..], " "); + while (output.next()) |digit| + switch (digit.len) { + 2, 3, 4, 7 => count += 1, + else => {}, + }; + } +} diff --git a/aoc/2021/08/part-two.zig b/aoc/2021/08/part-two.zig new file mode 100644 index 0000000..74db158 --- /dev/null +++ b/aoc/2021/08/part-two.zig @@ -0,0 +1,60 @@ +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, 1) << display[c - 'a']; + sum += pow * for (digits) |d, i| { + if (@bitReverse(u7, d) == digit) // edian + break i; + } else unreachable; + } + } +} -- cgit 1.4.1