diff options
author | Xander Bil <xander@biltopia.org> | 2024-12-02 23:38:23 +0100 |
---|---|---|
committer | Xander Bil <xander@biltopia.org> | 2024-12-02 23:38:23 +0100 |
commit | 1c2490f5f2c9419ddb5035fc3a8967beef691e6c (patch) | |
tree | 0dd2cb0a588e5fff69d7002585ace9bc81099fb4 /src/day02.zig | |
download | aoc2024-1c2490f5f2c9419ddb5035fc3a8967beef691e6c.tar.xz aoc2024-1c2490f5f2c9419ddb5035fc3a8967beef691e6c.zip |
solutions day1 and day2
Diffstat (limited to 'src/day02.zig')
-rw-r--r-- | src/day02.zig | 91 |
1 files changed, 91 insertions, 0 deletions
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}); +} |