88 lines
2.1 KiB
Zig
88 lines
2.1 KiB
Zig
|
const std = @import("std");
|
||
|
|
||
|
const Pair = struct {
|
||
|
opening: u8,
|
||
|
closing: u8,
|
||
|
score: u32,
|
||
|
};
|
||
|
|
||
|
const pairs = [4]Pair{
|
||
|
Pair{
|
||
|
.opening = '(',
|
||
|
.closing = ')',
|
||
|
.score = 3,
|
||
|
},
|
||
|
Pair{
|
||
|
.opening = '[',
|
||
|
.closing = ']',
|
||
|
.score = 57,
|
||
|
},
|
||
|
Pair{
|
||
|
.opening = '{',
|
||
|
.closing = '}',
|
||
|
.score = 1197,
|
||
|
},
|
||
|
Pair{
|
||
|
.opening = '<',
|
||
|
.closing = '>',
|
||
|
.score = 25137,
|
||
|
},
|
||
|
};
|
||
|
|
||
|
pub fn main() !void {
|
||
|
var alloc = std.heap.GeneralPurposeAllocator(.{}){};
|
||
|
defer std.debug.assert(!alloc.deinit());
|
||
|
var gpa = &alloc.allocator;
|
||
|
|
||
|
const stdin = std.io.getStdIn().reader();
|
||
|
|
||
|
var res: u32 = 0;
|
||
|
var scores = std.ArrayList(u64).init(gpa);
|
||
|
defer scores.deinit();
|
||
|
|
||
|
var tmp: [256]u8 = undefined;
|
||
|
while (try stdin.readUntilDelimiterOrEof(&tmp, '\n')) |line| {
|
||
|
var stack = std.ArrayList(u8).init(gpa);
|
||
|
defer stack.deinit();
|
||
|
var corrupt = false;
|
||
|
|
||
|
for (line) |char| {
|
||
|
for (pairs) |pair| {
|
||
|
if (char == pair.opening) {
|
||
|
try stack.append(char);
|
||
|
}
|
||
|
if (char == pair.closing) {
|
||
|
var matching = stack.pop();
|
||
|
if (matching != pair.opening) {
|
||
|
res += pair.score;
|
||
|
corrupt = true;
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
if (!corrupt and stack.items.len > 0) {
|
||
|
var score: u64 = 0;
|
||
|
|
||
|
std.mem.reverse(u8, stack.items);
|
||
|
|
||
|
for (stack.items) |char| {
|
||
|
score *= 5;
|
||
|
for (pairs) |pair, i| {
|
||
|
if (char == pair.opening) {
|
||
|
score += (@intCast(u64, i) + 1);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
try scores.append(score);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
std.sort.sort(u64, scores.items, {}, comptime std.sort.asc(u64));
|
||
|
var middleScore = scores.items[@divFloor(scores.items.len, 2)];
|
||
|
|
||
|
std.debug.print("{}\n", .{res});
|
||
|
std.debug.print("{}\n", .{middleScore});
|
||
|
}
|