Day 4 - Puzzle 2

This commit is contained in:
Dusk 2022-12-04 19:04:02 +01:00
parent 91d9a3179f
commit f226594ca5
1 changed files with 70 additions and 0 deletions

70
day4/puzzle2.zig Normal file
View File

@ -0,0 +1,70 @@
const std = @import("std");
const mem = std.mem;
const fmt = std.fmt;
const input = @embedFile("input");
pub fn main() !void {
var count: usize = 0;
// Iterate through the lines
var lines = mem.split(u8, input, "\n");
while (lines.next()) |line| {
// If line is empty, ignore
if (line.len == 0) continue;
var limits: [2][2]usize = undefined;
//std.debug.print("{s}\n", .{line});
// Which elf
var elf: usize = 0;
// Which limit
var limit: usize = 0;
// Start of slice
var start: usize = 0;
for (line) |char, index| {
if (char == '-') {
const number = fmt.parseInt(usize, line[start..index], 10) catch 0;
//std.debug.print("{}\n", .{number});
limits[elf][limit] = number;
start = index + 1;
limit += 1;
// 10-20,30-40
// ^
}
if (char == ',') {
const number = fmt.parseInt(usize, line[start..index], 10) catch 0;
//std.debug.print("{}\n", .{number});
limits[elf][limit] = number;
start = index + 1;
elf += 1;
limit = 0;
// 10-20,30-40
// ^
}
if (index == line.len - 1) {
const number = fmt.parseInt(usize, line[start..], 10) catch 0;
//std.debug.print("{}\n", .{number});
limits[elf][limit] = number;
}
}
// Check if they overlap
if ((limits[0][0] >= limits[1][0] and limits[0][0] <= limits[1][1]) or
(limits[1][0] >= limits[0][0] and limits[1][0] <= limits[0][1])) {
count += 1;
}
}
std.debug.print("{}\n", .{count});
}