-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday09pt2.zig
67 lines (57 loc) · 1.87 KB
/
day09pt2.zig
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
const std = @import("std");
const input = @embedFile("input09.txt");
const File = struct { pos: u32, len: u32, id: u32 };
const Gap = struct { pos: u32, len: u32 };
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}).init;
defer if (gpa.deinit() != .ok) @panic("GPA LEAK");
const alloc = gpa.allocator();
var files = std.ArrayListUnmanaged(File).empty;
defer files.deinit(alloc);
var gaps = std.ArrayListUnmanaged(Gap).empty;
defer gaps.deinit(alloc);
var next_pos: u32 = 0;
var next_id: u32 = 0;
var c: usize = 0;
while (c < input.len and input[c] >= '0' and input[c] <= '9') {
try files.append(alloc, .{
.pos = next_pos,
.len = input[c] - '0',
.id = next_id,
});
next_pos += input[c] - '0';
next_id += 1;
c += 1;
if (c >= input.len or input[c] < '0' or input[c] > '9') break;
try gaps.append(alloc, .{
.pos = next_pos,
.len = input[c] - '0',
});
next_pos += input[c] - '0';
c += 1;
}
for (0..files.items.len) |f_tmp| {
const f = files.items.len - f_tmp - 1;
var file = &files.items[f];
var found_gap_index: ?usize = null;
for (gaps.items, 0..) |*gap, i| {
if (gap.pos > file.pos) break;
if (gap.len >= file.len) {
file.pos = gap.pos;
gap.pos += file.len;
gap.len -= file.len;
found_gap_index = i;
break;
}
}
const g = found_gap_index orelse continue;
if (gaps.items[g].len == 0) _ = gaps.orderedRemove(g);
}
var checksum: usize = 0;
for (files.items) |file| {
for (0..file.len) |offset| {
checksum += (file.pos + offset) * file.id;
}
}
std.debug.print("{d}\n", .{checksum});
}