From 1c2490f5f2c9419ddb5035fc3a8967beef691e6c Mon Sep 17 00:00:00 2001 From: Xander Bil Date: Mon, 2 Dec 2024 23:38:23 +0100 Subject: solutions day1 and day2 --- src/day02.zig | 91 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 src/day02.zig (limited to 'src/day02.zig') diff --git a/src/day02.zig b/src/day02.zig new file mode 100644 index 0000000..cad2d9d --- /dev/null +++ b/src/day02.zig @@ -0,0 +1,91 @@ +const std = @import("std"); +const stdin = std.io.getStdIn(); +const print = std.debug.print; + +pub fn solve(part: []u8, buffer: []u8) !void { + var lines = std.mem.splitScalar(u8, buffer, '\n'); + if (std.mem.eql(u8, part, "part1")) { + try part1(&lines); + } else { + try part2(&lines); + } +} + +fn part1(lines: *std.mem.SplitIterator(u8, .scalar)) !void { + var count: usize = 0; + lines: while (lines.next()) |line| { + if (line.len > 0) { + var components = std.mem.splitScalar(u8, line, ' '); + var previous: i32 = try std.fmt.parseInt(i32, components.next().?, 10); + var increasing: i32 = 0; + while (components.next()) |number_s| { + const number = try std.fmt.parseInt(i32, number_s, 10); + if (increasing == 0) { + if (previous > number) { + increasing = -1; + } else { + increasing = 1; + } + } + + const difference = (number - previous) * increasing; + if (difference < 1 or difference > 3) { + continue :lines; + } + previous = number; + } + count += 1; + } + } + + print("Safe count: {d}\n", .{count}); +} + +fn part2(lines: *std.mem.SplitIterator(u8, .scalar)) !void { + var count: usize = 0; + while (lines.next()) |line| { + if (line.len > 0) { + var components = std.mem.splitScalar(u8, line, ' '); + + var i: usize = 0; + var j: usize = 0; + + counter: while (i <= j) { + j = 0; + components.reset(); + + if (i == 0) { + _ = components.next(); + } + + var previous: i32 = try std.fmt.parseInt(i32, components.next().?, 10); + var increasing: i32 = 0; + while (components.next()) |number_s| { + if (i != j) { + const number = try std.fmt.parseInt(i32, number_s, 10); + if (increasing == 0) { + if (previous > number) { + increasing = -1; + } else { + increasing = 1; + } + } + + const difference = (number - previous) * increasing; + if (difference < 1 or difference > 3) { + i += 1; + continue :counter; + } + previous = number; + } + + j += 1; + } + + count += 1; + break; + } + } + } + print("Safe count: {d}\n", .{count}); +} -- cgit v1.2.3