summaryrefslogtreecommitdiff
path: root/src/day-5/part-2.zig
diff options
context:
space:
mode:
authorame <[email protected]>2025-12-05 07:19:12 -0600
committerame <[email protected]>2025-12-05 07:19:12 -0600
commit610b11cc5d32b9d19acf0809535183852fb77fc9 (patch)
treed12ed9f5d73c47ccdef47e2b03f38c8c80c9bc2e /src/day-5/part-2.zig
parent22a92ee2ed33a5f2246f1c6498714ead9b9c65cf (diff)
day 5
Diffstat (limited to 'src/day-5/part-2.zig')
-rw-r--r--src/day-5/part-2.zig58
1 files changed, 58 insertions, 0 deletions
diff --git a/src/day-5/part-2.zig b/src/day-5/part-2.zig
new file mode 100644
index 0000000..a1ff825
--- /dev/null
+++ b/src/day-5/part-2.zig
@@ -0,0 +1,58 @@
+const std = @import("std");
+
+const val = struct { n: u64, open: bool };
+
+pub fn asc_val(_: void, a: val, b:val) bool {
+ return a.n < b.n;
+}
+
+pub fn main() !void {
+ var gpa = std.heap.GeneralPurposeAllocator(.{}){};
+ defer _ = gpa.deinit();
+ const alloc = gpa.allocator();
+
+ const path = "input.txt";
+ const fp = try std.fs.cwd().openFile(path, .{.mode = std.fs.File.OpenMode.read_only});
+ defer fp.close();
+ var reader = fp.reader();
+
+ var list = std.ArrayList(val).init(alloc);
+ defer list.deinit();
+
+ var buffer: [256]u8 = undefined;
+
+ while(try reader.readUntilDelimiterOrEof(&buffer, '\n')) |line| {
+
+ if(line.len == 0) break;
+
+ if(std.mem.indexOf(u8, line, "-")) |ind| {
+ const low: u64 = try std.fmt.parseInt(u64, line[0 .. ind], 10);
+ const high: u64 = try std.fmt.parseInt(u64, line[ind + 1 ..], 10);
+
+ //no clue why this is required, since both are inclusive it should be fine, maybe better sorting would work here but im not certain
+ if(low == high){
+ continue;
+ }
+
+ try list.append(.{.n = high, .open = false});
+ try list.append(.{.n = low, .open = true});
+ }
+ }
+
+ std.mem.sort(val, list.items, {}, asc_val);
+
+ var count: i64 = 0;
+ var last_val: u64 = 0;
+ var fresh: u64 = 0;
+ for(list.items) |v| {
+ if(v.open){
+ count += 1;
+ if(count == 1) last_val = v.n;
+ } else {
+ count -= 1;
+ if(count == 0) fresh += v.n - last_val + 1;
+ }
+ }
+
+ std.debug.print("{d}\n", .{fresh});
+}