summaryrefslogtreecommitdiff
path: root/day_01.zig
diff options
context:
space:
mode:
authorChristian Segundo2022-12-05 17:00:08 +0100
committerChristian Segundo2022-12-05 22:16:11 +0100
commit061a5bae272f45db6dcde99746922735f9769d25 (patch)
treee4dd9b6d903930c5c1b76286b4a08beea6f59162 /day_01.zig
parent8817203517907ef4248bde7474e6fb566515d6a7 (diff)
downloadadvent-of-zig-2022-061a5bae272f45db6dcde99746922735f9769d25.tar.gz
add day 5
Diffstat (limited to 'day_01.zig')
-rw-r--r--day_01.zig61
1 files changed, 61 insertions, 0 deletions
diff --git a/day_01.zig b/day_01.zig
new file mode 100644
index 0000000..80bb649
--- /dev/null
+++ b/day_01.zig
@@ -0,0 +1,61 @@
+const std = @import("std");
+const math = std.math;
+const Result = @import("util/aoc.zig").Result;
+
+pub fn puzzle_1(input: []const u8) !Result {
+ var iter = std.mem.split(u8, input, "\n");
+ var count: i32 = 0;
+ var max: i32 = 0;
+
+ while (iter.next()) |line| {
+ if (line.len == 0) {
+ if (count > max) {
+ max = count;
+ }
+ count = 0;
+ } else {
+ count += try std.fmt.parseInt(i32, line, 0);
+ }
+ }
+
+ return .{ .int = max };
+}
+
+pub fn puzzle_2(input: []const u8) !Result {
+ var iter = std.mem.split(u8, input, "\n");
+ var count: i32 = 0;
+ var max: [3]i32 = std.mem.zeroes([3]i32);
+
+ while (iter.next()) |line| {
+ if (line.len == 0) {
+ const lowest_u = min_idx(i32, &max);
+ if (count > max[lowest_u]) {
+ max[lowest_u] = count;
+ }
+ count = 0;
+ } else {
+ count += try std.fmt.parseInt(i32, line, 0);
+ }
+ }
+
+ count = 0;
+ for (max) |v| {
+ count += v;
+ }
+
+ return .{ .int = count };
+}
+
+fn min_idx(comptime T: type, slice: []const T) usize {
+ var best = slice[0];
+ var idx: usize = 0;
+
+ for (slice[1..]) |item, i| {
+ const possible_best = math.min(best, item);
+ if (best > possible_best) {
+ best = possible_best;
+ idx = i + 1;
+ }
+ }
+ return idx;
+}