mirror of
https://codeberg.org/andyscott/advent-of-code.git
synced 2024-12-22 01:23:11 -05:00
48 lines
1.4 KiB
Zig
48 lines
1.4 KiB
Zig
const std = @import("std");
|
|
const print = std.debug.print;
|
|
|
|
const util = @import("util.zig");
|
|
|
|
fn isSafe(items: []const i16) bool {
|
|
if (!std.sort.isSorted(i16, items, {}, std.sort.asc(i16)) and
|
|
!std.sort.isSorted(i16, items, {}, std.sort.desc(i16))) return false;
|
|
|
|
for (1..items.len) |i| {
|
|
if (@abs(items[i] - items[i - 1]) > 3 or items[i] == items[i - 1]) return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
pub fn main() !void {
|
|
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
|
|
const allocator = gpa.allocator();
|
|
|
|
const input = try util.readAllInput(2, allocator);
|
|
|
|
var safe: u16 = 0;
|
|
var safe_with_dampener: u16 = 0;
|
|
var lines = std.mem.tokenizeScalar(u8, input, '\n');
|
|
outer: while (lines.next()) |line| {
|
|
const levels = try util.inputToArrayList(i16, allocator, line);
|
|
defer levels.deinit();
|
|
|
|
// PART 1
|
|
if (isSafe(levels.items)) {
|
|
safe += 1;
|
|
continue;
|
|
}
|
|
// PART 2
|
|
for (0..levels.items.len) |i| {
|
|
var damp_levels = try levels.clone();
|
|
defer damp_levels.deinit();
|
|
_ = damp_levels.orderedRemove(i);
|
|
if (isSafe(damp_levels.items)) {
|
|
safe_with_dampener += 1;
|
|
continue :outer;
|
|
}
|
|
}
|
|
}
|
|
|
|
print("PART 1 - SAFE REPORTS: {d}\n", .{safe});
|
|
print("PART 2 - SAFE WITH DAMPENER: {d}\n", .{safe + safe_with_dampener});
|
|
}
|