diff options
author | Nguyễn Gia Phong <mcsinyx@disroot.org> | 2021-12-10 21:09:19 +0700 |
---|---|---|
committer | Nguyễn Gia Phong <mcsinyx@disroot.org> | 2021-12-10 21:09:19 +0700 |
commit | 9d041894e485f3dcd93a952266273a25f6614f07 (patch) | |
tree | 0613e0975b71e9f98ddb11bf7e0ba39054f8a741 /aoc/2021/10/part-two.zig | |
parent | f53ac491b1ec74ad9c44d20065517467c1877190 (diff) | |
download | cp-9d041894e485f3dcd93a952266273a25f6614f07.tar.gz |
[aoc/2021/10] Get rid of bullshit
Diffstat (limited to 'aoc/2021/10/part-two.zig')
-rw-r--r-- | aoc/2021/10/part-two.zig | 46 |
1 files changed, 17 insertions, 29 deletions
diff --git a/aoc/2021/10/part-two.zig b/aoc/2021/10/part-two.zig index 6e5b11d..4578272 100644 --- a/aoc/2021/10/part-two.zig +++ b/aoc/2021/10/part-two.zig @@ -1,5 +1,6 @@ -const Stack = @import("stack.zig").Stack; -const asc = std.sort.asc(usize); +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; @@ -8,49 +9,36 @@ const tokenize = std.mem.tokenize; pub fn main() !void { var input = tokenize(@embedFile("input"), "\n"); - var incomplete: usize = 0; + var i: usize = 0; var max_len: usize = 0; - while (input.next()) |line| : (incomplete += 1) { + while (input.next()) |line| : (i += 1) { if (line.len > max_len) max_len = line.len; } - - var stack = try Stack(u8).alloc(page_allocator, max_len); + var stack = try Stack.alloc(page_allocator, max_len); defer stack.free(); - input.reset(); - while (input.next()) |line| { - for (line) |c| - switch (c) { - '(', '[', '{', '<' => stack.push(c), - else => if (stack.pop() ^ c > 6) { - incomplete -= 1; - break; - }, - }; - stack.reset(); - } - var scores = try page_allocator.alloc(usize, incomplete); + var scores = try page_allocator.alloc(usize, i); defer page_allocator.free(scores); input.reset(); - loop: while (input.next()) |line| { - stack.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, + else => if (stack.pop().? ^ c > 6) continue :loop, }; - incomplete -= 1; - scores[incomplete] = 0; - while (stack.len > 0) { - scores[incomplete] *= 5; - scores[incomplete] += @as(usize, switch (stack.pop()) { + while (stack.pop()) |c| { + scores[i] *= 5; + scores[i] += @as(usize, switch (c) { '(' => 1, '[' => 2, '{' => 3, '<' => 4, else => unreachable, }); } } - sort(usize, scores, {}, asc); - print("{}\n", .{ scores[scores.len / 2] }); + sort(usize, scores, {}, desc); + i = indexOfScalar(usize, scores, 0).?; + print("{}\n", .{ scores[i / 2] }); } |