From c0877054bdbcb4739ecc842e37b0f1d6ba7af8d0 Mon Sep 17 00:00:00 2001 From: Julien Dessaux Date: Thu, 1 Dec 2022 13:05:31 +0100 Subject: 2022-01 in zig --- 2022/01/second.zig | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 2022/01/second.zig (limited to '2022/01/second.zig') 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]; +} -- cgit v1.2.3