aboutsummaryrefslogtreecommitdiff
path: root/2022/01/second.zig
diff options
context:
space:
mode:
authorJulien Dessaux2022-12-01 13:05:31 +0100
committerJulien Dessaux2022-12-01 13:07:37 +0100
commitc0877054bdbcb4739ecc842e37b0f1d6ba7af8d0 (patch)
tree9a06fd81a80fcfda45c7686ea25c1b4e5ed5f292 /2022/01/second.zig
parentAdded first part of the third day in zig (diff)
downloadadvent-of-code-c0877054bdbcb4739ecc842e37b0f1d6ba7af8d0.tar.gz
advent-of-code-c0877054bdbcb4739ecc842e37b0f1d6ba7af8d0.tar.bz2
advent-of-code-c0877054bdbcb4739ecc842e37b0f1d6ba7af8d0.zip
2022-01 in zig
Diffstat (limited to '')
-rw-r--r--2022/01/second.zig33
1 files changed, 33 insertions, 0 deletions
diff --git a/2022/01/second.zig b/2022/01/second.zig
new file mode 100644
index 0000000..9863ee8
--- /dev/null
+++ b/2022/01/second.zig
@@ -0,0 +1,33 @@
+const std = @import("std");
+
+const example = @embedFile("example");
+const input = @embedFile("input");
+
+pub fn main() anyerror!void {
+ try std.testing.expectEqual(solve(example), 45000);
+ const result = try solve(input);
+ try std.io.getStdOut().writer().print("{}\n", .{result});
+}
+
+fn solve(puzzle: []const u8) !u64 {
+ var it = std.mem.split(u8, puzzle, "\n");
+ var top3 = [_]u64{ 0, 0, 0 };
+ var tot: u64 = 0;
+ while (it.next()) |value| {
+ const n = std.fmt.parseInt(u64, value, 10) catch 0;
+ if (n == 0) {
+ for (top3) |*max| {
+ if (tot > max.*) {
+ // this swapping will keep the array sorted
+ const prev = max.*;
+ max.* = tot;
+ tot = prev;
+ }
+ }
+ tot = 0;
+ } else {
+ tot += n;
+ }
+ }
+ return top3[0] + top3[1] + top3[2];
+}