diff options
| author | Lucas Ransan <lucas@ransan.tk> | 2021-06-15 15:08:12 +0200 |
|---|---|---|
| committer | Lucas Ransan <lucas@ransan.tk> | 2021-06-16 22:21:45 +0200 |
| commit | c9462a291535bf1694af25f7bd71e0902f7e1f09 (patch) | |
| tree | 2160ef6a129cce0f55ed7ff9f0642ec827a5567a | |
| parent | 451d82f90a59e5360751e7f97d82a99d45b331e6 (diff) | |
| download | perlweeklychallenge-club-c9462a291535bf1694af25f7bd71e0902f7e1f09.tar.gz perlweeklychallenge-club-c9462a291535bf1694af25f7bd71e0902f7e1f09.tar.bz2 perlweeklychallenge-club-c9462a291535bf1694af25f7bd71e0902f7e1f09.zip | |
Zig week 117 task 2
| -rw-r--r-- | challenge-117/luc65r/zig/ch-2.zig | 77 |
1 files changed, 77 insertions, 0 deletions
diff --git a/challenge-117/luc65r/zig/ch-2.zig b/challenge-117/luc65r/zig/ch-2.zig new file mode 100644 index 0000000000..dc513778ad --- /dev/null +++ b/challenge-117/luc65r/zig/ch-2.zig @@ -0,0 +1,77 @@ +const std = @import("std"); +const Allocator = std.mem.Allocator; + +const stdout = std.io.getStdOut().writer(); +var bufferedStdout = std.io.bufferedWriter(stdout); +const bufout = bufferedStdout.writer(); + +const Move = enum { + horizontal, + left, + right, + + fn toChar(self: Move) u8 { + return switch (self) { + Move.horizontal => 'H', + Move.left => 'L', + Move.right => 'R', + }; + } +}; + +const Position = struct { + y: u32, + x: u32, + + fn isBottomRight(self: Position) bool { + return self.y == 0 and self.x == 0; + } + + fn move(self: Position, m: Move) ?Position { + return switch (m) { + Move.horizontal => .{ + .y = self.y, + .x = if (self.x > 0) self.x - 1 else return null, + }, + Move.left => .{ + .y = if (self.y > 0) self.y - 1 else return null, + .x = self.x + 1, + }, + Move.right => .{ + .y = if (self.y > 0) self.y - 1 else return null, + .x = self.x, + }, + }; + } + + fn printDirs(self: Position, dirs: []u8, depth: u32) anyerror!void { + if (self.isBottomRight()) { + try bufout.print("{s}\n", .{dirs[0..depth]}); + return; + } + + for ([_]Move{ Move.horizontal, Move.left, Move.right }) |m| { + const pos = self.move(m) orelse continue; + dirs[depth] = m.toChar(); + try pos.printDirs(dirs, depth + 1); + } + } +}; + +pub fn main() !void { + const argv = std.os.argv; + if (argv.len != 2) + return error.InvalidArguments; + + const size = try std.fmt.parseInt(u32, std.mem.span(argv[1]), 10); + + var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); + defer arena.deinit(); + const allocator = &arena.allocator; + + const position = Position{ .y = size, .x = 0 }; + + var dirs = try allocator.alloc(u8, 2 * size); + try position.printDirs(dirs, 0); + try bufferedStdout.flush(); +} |
