aboutsummaryrefslogtreecommitdiff
path: root/challenge-117/luc65r/zig/ch-2.zig
blob: dc513778ad4136c14bf1b53f73cd4371bcb212ef (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
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();
}