diff options
Diffstat (limited to 'aoc/2021/10/part-two.zig')
-rw-r--r-- | aoc/2021/10/part-two.zig | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/aoc/2021/10/part-two.zig b/aoc/2021/10/part-two.zig new file mode 100644 index 0000000..4578272 --- /dev/null +++ b/aoc/2021/10/part-two.zig @@ -0,0 +1,44 @@ +const Stack = @import("Stack.zig"); +const desc = std.sort.desc(usize); +const indexOfScalar = std.mem.indexOfScalar; +const page_allocator = std.heap.page_allocator; +const print = std.debug.print; +const sort = std.sort.sort; +const std = @import("std"); +const tokenize = std.mem.tokenize; + +pub fn main() !void { + var input = tokenize(@embedFile("input"), "\n"); + var i: usize = 0; + var max_len: usize = 0; + while (input.next()) |line| : (i += 1) { + if (line.len > max_len) + max_len = line.len; + } + var stack = try Stack.alloc(page_allocator, max_len); + defer stack.free(); + + var scores = try page_allocator.alloc(usize, i); + defer page_allocator.free(scores); + input.reset(); + loop: while (input.next()) |line| : (stack.reset()) { + i -= 1; + scores[i] = 0; + for (line) |c| + switch (c) { + '(', '[', '{', '<' => stack.push(c), + else => if (stack.pop().? ^ c > 6) continue :loop, + }; + while (stack.pop()) |c| { + scores[i] *= 5; + scores[i] += @as(usize, switch (c) { + '(' => 1, '[' => 2, '{' => 3, '<' => 4, + else => unreachable, + }); + } + } + + sort(usize, scores, {}, desc); + i = indexOfScalar(usize, scores, 0).?; + print("{}\n", .{ scores[i / 2] }); +} |