From 3587c73fea30ce6c8881be3708892fbcce044f86 Mon Sep 17 00:00:00 2001 From: Julien Dessaux Date: Wed, 9 Feb 2022 00:45:04 +0100 Subject: Added first day in zig --- 2021/01/example | 10 ++++++++++ 2021/01/first.zig | 26 ++++++++++++++++++++++++++ 2021/01/second.zig | 30 ++++++++++++++++++++++++++++++ 3 files changed, 66 insertions(+) create mode 100644 2021/01/example create mode 100644 2021/01/first.zig create mode 100644 2021/01/second.zig (limited to '2021/01') diff --git a/2021/01/example b/2021/01/example new file mode 100644 index 0000000..167e291 --- /dev/null +++ b/2021/01/example @@ -0,0 +1,10 @@ +199 +200 +208 +210 +200 +207 +240 +269 +260 +263 diff --git a/2021/01/first.zig b/2021/01/first.zig new file mode 100644 index 0000000..79dcc89 --- /dev/null +++ b/2021/01/first.zig @@ -0,0 +1,26 @@ +const std = @import("std"); + +const example = @embedFile("example"); +const input = @embedFile("input"); + +pub fn main() anyerror!void { + try std.testing.expectEqual(solve(example), 7); + const result = try solve(input); + try std.io.getStdOut().writer().print("{}\n", .{result}); +} + +fn solve(puzzle: []const u8) !u64 { + var it = std.mem.tokenize(u8, puzzle, " \n"); + var tot: u64 = 0; + var prev: ?u64 = null; + while (it.next()) |value| { + const n = try std.fmt.parseInt(u64, value, 10); + if (prev) |p| { + if (p < n) { + tot += 1; + } + } + prev = n; + } + return tot; +} diff --git a/2021/01/second.zig b/2021/01/second.zig new file mode 100644 index 0000000..eb6993e --- /dev/null +++ b/2021/01/second.zig @@ -0,0 +1,30 @@ +const std = @import("std"); + +const example = @embedFile("example"); +const input = @embedFile("input"); + +pub fn main() anyerror!void { + try std.testing.expectEqual(solve(example), 5); + const result = try solve(input); + try std.io.getStdOut().writer().print("{}\n", .{result}); +} + +fn solve(puzzle: []const u8) !u64 { + var it = std.mem.tokenize(u8, puzzle, " \n"); + var tot: u64 = 0; + var prev = [_]?u64{null} ** 3; + while (it.next()) |value| { + const n = try std.fmt.parseInt(u64, value, 10); + if (prev[0]) |p| { + if (p < n) { + tot += 1; + } + } + var i: usize = 0; + while (i < prev.len - 1) : (i += 1) { + prev[i] = prev[i + 1]; + } + prev[2] = n; + } + return tot; +} -- cgit v1.2.3