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}); }