diff options
author | Julien Dessaux | 2022-02-09 19:19:43 +0100 |
---|---|---|
committer | Julien Dessaux | 2022-02-09 19:19:43 +0100 |
commit | 2d8480491eab8ef82b8bfe30f3f2f72611f8f153 (patch) | |
tree | d5dd535cc72febdfc48a894ba6abbcc50c6cbfed | |
parent | Added first day in zig (diff) | |
download | advent-of-code-2d8480491eab8ef82b8bfe30f3f2f72611f8f153.tar.gz advent-of-code-2d8480491eab8ef82b8bfe30f3f2f72611f8f153.tar.bz2 advent-of-code-2d8480491eab8ef82b8bfe30f3f2f72611f8f153.zip |
Added second day in zig
-rw-r--r-- | 2021/02/example | 6 | ||||
-rw-r--r-- | 2021/02/first.zig | 31 | ||||
-rw-r--r-- | 2021/02/second.zig | 35 |
3 files changed, 72 insertions, 0 deletions
diff --git a/2021/02/example b/2021/02/example new file mode 100644 index 0000000..b7172ac --- /dev/null +++ b/2021/02/example @@ -0,0 +1,6 @@ +forward 5 +down 5 +forward 8 +up 3 +down 8 +forward 2 diff --git a/2021/02/first.zig b/2021/02/first.zig new file mode 100644 index 0000000..774cb53 --- /dev/null +++ b/2021/02/first.zig @@ -0,0 +1,31 @@ +const std = @import("std"); + +const example = @embedFile("example"); +const input = @embedFile("input"); + +pub fn main() anyerror!void { + 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 pos: u64 = 0; + var depth: u64 = 0; + while (it.next()) |line| { + var it2 = std.mem.tokenize(u8, line, " "); + const step = it2.next() orelse unreachable; + const n: u64 = std.fmt.parseInt(u64, it2.next().?, 10) catch unreachable; + switch (step[0]) { + 'f' => pos += n, + 'd' => depth += n, + 'u' => depth -= n, + else => unreachable, + } + } + return pos * depth; +} + +test "solve" { + try std.testing.expectEqual(solve(example), 150); +} diff --git a/2021/02/second.zig b/2021/02/second.zig new file mode 100644 index 0000000..3126118 --- /dev/null +++ b/2021/02/second.zig @@ -0,0 +1,35 @@ +const std = @import("std"); + +const example = @embedFile("example"); +const input = @embedFile("input"); + +pub fn main() anyerror!void { + 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 aim: u64 = 0; + var pos: u64 = 0; + var depth: u64 = 0; + while (it.next()) |line| { + var it2 = std.mem.tokenize(u8, line, " "); + const step = it2.next() orelse unreachable; + const n: u64 = std.fmt.parseInt(u64, it2.next().?, 10) catch unreachable; + switch (step[0]) { + 'f' => { + pos += n; + depth += n * aim; + }, + 'd' => aim += n, + 'u' => aim -= n, + else => unreachable, + } + } + return pos * depth; +} + +test "solve" { + try std.testing.expectEqual(solve(example), 900); +} |