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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
|
const std = @import("std");
const print = std.debug.print;
pub fn solve(part: []u8, buffer: []u8, allocator: std.mem.Allocator) !void {
var lines = std.mem.splitScalar(u8, buffer, '\n');
var left = std.ArrayList(usize).init(allocator);
var right = std.ArrayList(usize).init(allocator);
defer left.deinit();
defer right.deinit();
if (std.mem.eql(u8, part, "1")) {
try part1(&lines, &left, &right, allocator);
} else {
try part2(&lines, &left, &right, allocator);
}
}
fn part1(lines: *std.mem.SplitIterator(u8, .scalar), left: *std.ArrayList(usize), right: *std.ArrayList(usize), allocator: std.mem.Allocator) !void {
while (lines.next()) |line| {
if (line.len > 0) {
var components = std.mem.split(u8, line, " ");
try left.append(try std.fmt.parseInt(usize, components.next().?, 10));
try right.append(try std.fmt.parseInt(usize, components.next().?, 10));
}
}
const left_s = try left.toOwnedSlice();
const right_s = try right.toOwnedSlice();
defer allocator.free(left_s);
defer allocator.free(right_s);
std.mem.sort(usize, left_s, {}, std.sort.asc(usize));
std.mem.sort(usize, right_s, {}, std.sort.asc(usize));
var sum: usize = 0;
for (left_s, right_s) |item_l, item_r| {
if (item_l > item_r) {
sum += item_l - item_r;
} else {
sum += item_r - item_l;
}
}
print("{d}\n", .{sum});
}
fn part2(lines: *std.mem.SplitIterator(u8, .scalar), left: *std.ArrayList(usize), right: *std.ArrayList(usize), allocator: std.mem.Allocator) !void {
while (lines.next()) |line| {
if (line.len > 0) {
var components = std.mem.split(u8, line, " ");
try left.append(try std.fmt.parseInt(usize, components.next().?, 10));
try right.append(try std.fmt.parseInt(usize, components.next().?, 10));
}
}
const left_s = try left.toOwnedSlice();
const right_s = try right.toOwnedSlice();
defer allocator.free(left_s);
defer allocator.free(right_s);
std.mem.sort(usize, right_s, {}, std.sort.asc(usize));
var map = std.AutoHashMap(usize, usize).init(allocator);
defer map.deinit();
var sum: usize = 0;
for (left_s) |item_l| {
sum += map.get(item_l) orelse blk: {
var amount: usize = 0;
for (right_s) |item_r| {
if (item_l == item_r) {
amount += item_l;
}
}
try map.put(item_l, amount);
break :blk amount;
};
}
print("{d}\n", .{sum});
}
|