blob: 91b99fa818b75eecab02add8b28f18e8f761791c (
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
|
const std = @import("std");
pub fn main() !void {
const input = @embedFile("1.txt");
try std.fmt.format(std.io.getStdOut().writer(), "{}\n", .{try run(input)});
}
test {
std.debug.assert(try run(
\\3 4
\\4 3
\\2 5
\\1 3
\\3 9
\\3 3
) == 31);
}
pub fn run(input: []const u8) !u32 {
var lines = std.mem.split(u8, input, "\n");
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
var lefts = std.ArrayList(u32).init(allocator);
defer lefts.deinit();
var rights = std.AutoHashMap(u32, u16).init(allocator);
defer rights.deinit();
while (lines.next()) |line| {
if (line.len == 0) continue;
var words = std.mem.split(u8, line, " ");
const left = try std.fmt.parseInt(u32, words.next() orelse return error.InvalidInput, 10);
const right = try std.fmt.parseInt(u32, words.next() orelse return error.InvalidInput, 10);
try lefts.append(left);
const entry = try rights.getOrPut(right);
if (entry.found_existing)
entry.value_ptr.* += 1
else
entry.value_ptr.* = 1;
}
var sum: u32 = 0;
for (lefts.items) |x| {
const count: u32 = @intCast(rights.get(x) orelse 0);
sum += x * count;
}
return sum;
}
|