Day 4 in zig

This commit is contained in:
Scramble 2022-12-05 20:28:00 +00:00
parent 1d329a549e
commit 9262d1e49b
3 changed files with 1079 additions and 0 deletions

1000
zig/4/input.txt Normal file

File diff suppressed because it is too large Load Diff

38
zig/4/part1.zig Normal file
View File

@ -0,0 +1,38 @@
const std = @import("std");
const Pair = struct {
low: i32 = 0,
high: i32 = 0,
fn fullyOverlaps(self: *Pair, other: *Pair) bool {
return (self.low <= other.low and self.high >= other.high) or (self.low >= other.low and self.high <= other.high);
}
};
fn parsei32Guaranteed(str: []const u8) i32 {
return std.fmt.parseInt(i32, str, 10) catch unreachable;
}
pub fn main() !void {
var file = try std.fs.cwd().openFile("input.txt", .{});
defer file.close();
var a = std.io.bufferedReader(file.reader());
var readerStream = a.reader();
var count: i32 = 0;
var buf: [32]u8 = undefined;
while (try readerStream.readUntilDelimiterOrEof(&buf, '\n')) |line| {
var pairStrings = std.mem.split(u8, line, ",");
var pairs = [_]Pair{ .{}, .{} };
for (pairs) |*pair| {
var elements = std.mem.split(u8, pairStrings.next().?, "-");
pair.low = parsei32Guaranteed(elements.next().?);
pair.high = parsei32Guaranteed(elements.next().?);
}
if (pairs[0].fullyOverlaps(&pairs[1])) {
count += 1;
}
}
std.debug.print("{d}\n", .{count});
}

41
zig/4/part2.zig Normal file
View File

@ -0,0 +1,41 @@
const std = @import("std");
const Pair = struct {
low: i32 = 0,
high: i32 = 0,
fn fullyOverlaps(self: *Pair, other: *Pair) bool {
return (self.low <= other.low and self.high >= other.high) or (self.low >= other.low and self.high <= other.high);
}
fn partiallyOverlaps(self: *Pair, other: *Pair) bool {
return (self.low <= other.high and self.high >= other.low);
}
};
fn parsei32Guaranteed(str: []const u8) i32 {
return std.fmt.parseInt(i32, str, 10) catch unreachable;
}
pub fn main() !void {
var file = try std.fs.cwd().openFile("input.txt", .{});
defer file.close();
var a = std.io.bufferedReader(file.reader());
var readerStream = a.reader();
var count: i32 = 0;
var buf: [32]u8 = undefined;
while (try readerStream.readUntilDelimiterOrEof(&buf, '\n')) |line| {
var pairStrings = std.mem.split(u8, line, ",");
var pairs = [_]Pair{ .{}, .{} };
for (pairs) |*pair| {
var elements = std.mem.split(u8, pairStrings.next().?, "-");
pair.low = parsei32Guaranteed(elements.next().?);
pair.high = parsei32Guaranteed(elements.next().?);
}
if (pairs[0].partiallyOverlaps(&pairs[1])) {
count += 1;
}
}
std.debug.print("{d}\n", .{count});
}