all stats

at's stats

guessed the most

namecorrect guessesgames togetherratio

were guessed the most by

namecorrect guessesgames togetherratio

entries

round #58

submitted at
0 likes

guesses
comments 0

post a comment


dir zig
dir src
main.zig ASCII text
  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
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
const std = @import("std");
const stdout_file = std.io.getStdOut().writer();
var stdout_bw = std.io.bufferedWriter(stdout_file);
const stdout = stdout_bw.writer();

// const stdin_file = std.io.getStdOut().writer();
// var stdout_bw = std.io.bufferedWriter(stdout_file);
// const stdout = stdout_bw.writer();
const stdin = std.io.getStdIn().reader();

const Mark = enum {
    X,
    O,
    Nil,
    pub fn format(
        self: Mark,
        comptime fmt: []const u8,
        options: std.fmt.FormatOptions,
        writer: anytype,
    ) !void {
        _ = fmt;
        _ = options;
        try writer.writeAll(switch (self) {
            .X => "X",
            .O => "O",
            .Nil => " ",
        });
    }
};

const TTTColumnIter = struct {
    idx: u64 = 0,
    parent: *const TicTacToe,
    fn next(self: *@This()) ?Mark {
        const data: []const Mark = self.parent.data;
        const side_len = self.parent.side_len;
        defer self.idx += 1;
        if (self.idx < data.len) {
            return data[(self.idx % side_len) * side_len];
        } else {
            return null;
        }
    }
};

const TTTRowIter = struct {
    idx: u64 = 0,
    parent: *const TicTacToe,
    fn next(self: *@This()) ?Mark {
        defer self.idx += 1;
        if (self.idx < self.parent.data.len) {
            return self.parent.data[self.idx];
        } else {
            return null;
        }
    }
};

const TTTDiagonalIter = struct {
    idx: u64 = 0,
    parent: *const TicTacToe,
    fn next(self: *@This()) ?Mark {
        const data: []const Mark = self.parent.data;
        const side_len = self.parent.side_len;
        defer self.idx += 1;
        if (self.idx < side_len) {
            // Diagonal starting at top left and ending in bottom right
            return data[self.idx * side_len + self.idx];
        } else if (self.idx < 2 * side_len) {
            // Diagonal starting at top right and ending in bottom left
            const sub_idx = self.idx - side_len;
            return data[sub_idx * side_len + side_len - sub_idx - 1];
        } else {
            return null;
        }
    }
};

const TicTacToe = struct {
    side_len: u32,
    data: []Mark,

    // Interaction methods
    /// `move` expects to be passed an array of 0-indexed integers representing moves
    ///  0 | 1 | 2
    /// ---+---+---
    ///  3 | 4 | 5
    /// ---+---+---
    ///  6 | 7 | 8
    fn move(self: *TicTacToe, drill: []const u8, mark: Mark) void {
        std.debug.assert(drill.len == 1);
        self.data[drill[0]] = mark;
    }
    fn show(self: *const TicTacToe) !void {
        try stdout.print(" {} | {} | {}\n", .{ self.data[0], self.data[1], self.data[2] });
        try stdout.print("---+---+---\n", .{});
        try stdout.print(" {} | {} | {}\n", .{ self.data[3], self.data[4], self.data[5] });
        try stdout.print("---+---+---\n", .{});
        try stdout.print(" {} | {} | {}\n", .{ self.data[6], self.data[7], self.data[8] });
        try stdout.print("\n", .{});
        try stdout_bw.flush(); // don't forget to flush!
    }

    // Iterator methods
    fn rows(self: *const TicTacToe) TTTRowIter {
        return TTTRowIter{ .parent = self };
    }
    fn cols(self: *const TicTacToe) TTTColumnIter {
        return TTTColumnIter{ .parent = self };
    }
    fn diags(self: *const TicTacToe) TTTDiagonalIter {
        return TTTDiagonalIter{ .parent = self };
    }
};

fn ttt_new(side_len: u32, allocator: std.mem.Allocator) !TicTacToe {
    const data: []Mark = try allocator.alloc(Mark, side_len * side_len);
    return TicTacToe{ .side_len = side_len, .data = data };
}

fn ttt_free(p: *const TicTacToe, allocator: std.mem.Allocator) void {
    allocator.free(p.data);
}

/// If a slice of marks are all the same, return that mark. If there's no matching mark return .Nil.
/// Expects an iterator that returns `Mark`s as the first param, and the length of rows/columns/diagonals as the second param.
fn all_same(mark_iter: anytype, run_length: u32) Mark {
    var target = Mark.Nil;
    var run_idx: u32 = 0;
    while (mark_iter.next()) |mark| {
        if (run_idx >= run_length) {
            break;
        }
        run_idx += 1;
        if (target == .Nil) {
            target = mark;
        } else if (target != mark) {
            return .Nil;
        }
    }
    return target;
}

fn winner(g: TicTacToe) Mark {
    // Check for winning rows
    var row_iter = g.rows();
    for (0..g.side_len) |row_idx| {
        const winning_mark = all_same(&row_iter, g.side_len);
        if (winning_mark != .Nil) {
            std.debug.print("Won on row {d}.\n", .{row_idx});
            return winning_mark;
        }
    }

    // Check for winning columns
    var col_iter = g.cols();
    for (0..g.side_len) |col_idx| {
        const winning_mark = all_same(&col_iter, g.side_len);
        if (winning_mark != .Nil) {
            std.debug.print("Won on col {d}.\n", .{col_idx});
            return winning_mark;
        }
    }

    // Check for winning diagonals
    var diag_iter = g.diags();
    for (0..2) |diag_idx| {
        const winning_mark = all_same(&diag_iter, g.side_len);
        if (winning_mark != .Nil) {
            std.debug.print("Won on diagonal {d}.\n", .{diag_idx});
            return winning_mark;
        }
    }
    return .Nil;
}

fn gauntlet(g: TicTacToe) void {
    var row_iter = g.rows();
    while (row_iter.next()) |row| {
        std.log.info("got row {}", .{std.json.fmt(row, .{})});
    }
    var col_iter = g.cols();
    while (col_iter.next()) |col| {
        std.log.info("got col {}", .{std.json.fmt(col, .{})});
    }
    var diag_iter = g.diags();
    while (diag_iter.next()) |diag| {
        std.log.info("got diags {}", .{std.json.fmt(diag, .{})});
    }
    std.log.info("checking winner: {}", .{std.json.fmt(winner(g), .{})});
}

pub fn main() !void {
    // Prints to stderr (it's a shortcut based on `std.io.getStdErr()`)
    std.debug.print("All your {s} are belong to us.\n", .{"codebase"});
    const alloc = std.heap.c_allocator;

    var g = try ttt_new(4, alloc);
    defer ttt_free(&g, alloc);

    // Main game loop
    try g.show();
    var current_mark: Mark = .O;
    var winning_mark: Mark = .Nil;
    while (winning_mark == .Nil) {
        current_mark = switch (current_mark) {
            .X => .O,
            .O => .X,
            .Nil => .Nil,
        };
        try stdout.print("It's your turn, {}!\n", .{current_mark});
        try stdout_bw.flush();

        var in_buf = [_]u8{0} ** 256;
        var in_buf_stream = std.io.fixedBufferStream(&in_buf);
        try stdin.streamUntilDelimiter(in_buf_stream.writer(), '\n', 256);
        const move_choice = try std.fmt.charToDigit(in_buf[0], 10);
        g.move(&[1]u8{move_choice}, current_mark);
        try g.show();

        winning_mark = winner(g);
    }
    try stdout.print("You win, {}! Good job!\n", .{winning_mark});
    try stdout_bw.flush();
    // I'm bored, fuck Zig, there are 3 hours left, I'm so sleepy..... uwu
}
root.zig ASCII text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const std = @import("std");
const testing = std.testing;

export fn add(a: i32, b: i32) i32 {
    return a + b;
}

test "basic add functionality" {
    try testing.expect(add(3, 7) == 10);
}
build.zig ASCII text
 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
const std = @import("std");

// Although this function looks imperative, note that its job is to
// declaratively construct a build graph that will be executed by an external
// runner.
pub fn build(b: *std.Build) void {
    // Standard target options allows the person running `zig build` to choose
    // what target to build for. Here we do not override the defaults, which
    // means any target is allowed, and the default is native. Other options
    // for restricting supported target set are available.
    const target = b.standardTargetOptions(.{});

    // Standard optimization options allow the person running `zig build` to select
    // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. Here we do not
    // set a preferred release mode, allowing the user to decide how to optimize.
    const optimize = b.standardOptimizeOption(.{});

    const lib = b.addStaticLibrary(.{
        .name = "cg58",
        // In this case the main source file is merely a path, however, in more
        // complicated build scripts, this could be a generated file.
        .root_source_file = b.path("src/root.zig"),
        .target = target,
        .optimize = optimize,
    });

    // This declares intent for the library to be installed into the standard
    // location when the user invokes the "install" step (the default step when
    // running `zig build`).
    b.installArtifact(lib);

    const exe = b.addExecutable(.{
        .name = "cg58",
        .root_source_file = b.path("src/main.zig"),
        .target = target,
        .optimize = optimize,
    });
    exe.linkLibC();

    // This declares intent for the executable to be installed into the
    // standard location when the user invokes the "install" step (the default
    // step when running `zig build`).
    b.installArtifact(exe);

    // This *creates* a Run step in the build graph, to be executed when another
    // step is evaluated that depends on it. The next line below will establish
    // such a dependency.
    const run_cmd = b.addRunArtifact(exe);

    // By making the run step depend on the install step, it will be run from the
    // installation directory rather than directly from within the cache directory.
    // This is not necessary, however, if the application depends on other installed
    // files, this ensures they will be present and in the expected location.
    run_cmd.step.dependOn(b.getInstallStep());

    // This allows the user to pass arguments to the application in the build
    // command itself, like this: `zig build run -- arg1 arg2 etc`
    if (b.args) |args| {
        run_cmd.addArgs(args);
    }

    // This creates a build step. It will be visible in the `zig build --help` menu,
    // and can be selected like this: `zig build run`
    // This will evaluate the `run` step rather than the default, which is "install".
    const run_step = b.step("run", "Run the app");
    run_step.dependOn(&run_cmd.step);

    // Creates a step for unit testing. This only builds the test executable
    // but does not run it.
    const lib_unit_tests = b.addTest(.{
        .root_source_file = b.path("src/root.zig"),
        .target = target,
        .optimize = optimize,
    });

    const run_lib_unit_tests = b.addRunArtifact(lib_unit_tests);

    const exe_unit_tests = b.addTest(.{
        .root_source_file = b.path("src/main.zig"),
        .target = target,
        .optimize = optimize,
    });

    const run_exe_unit_tests = b.addRunArtifact(exe_unit_tests);

    // Similar to creating the run step earlier, this exposes a `test` step to
    // the `zig build --help` menu, providing a way for the user to request
    // running the unit tests.
    const test_step = b.step("test", "Run unit tests");
    test_step.dependOn(&run_lib_unit_tests.step);
    test_step.dependOn(&run_exe_unit_tests.step);
}
build.zig.zon ASCII text
 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
.{
    .name = "cg58",
    // This is a [Semantic Version](https://semver.org/).
    // In a future version of Zig it will be used for package deduplication.
    .version = "0.0.0",

    // This field is optional.
    // This is currently advisory only; Zig does not yet do anything
    // with this value.
    //.minimum_zig_version = "0.11.0",

    // This field is optional.
    // Each dependency must either provide a `url` and `hash`, or a `path`.
    // `zig build --fetch` can be used to fetch all dependencies of a package, recursively.
    // Once all dependencies are fetched, `zig build` no longer requires
    // internet connectivity.
    .dependencies = .{
        // See `zig fetch --save <url>` for a command-line interface for adding dependencies.
        //.example = .{
        //    // When updating this field to a new URL, be sure to delete the corresponding
        //    // `hash`, otherwise you are communicating that you expect to find the old hash at
        //    // the new URL.
        //    .url = "https://example.com/foo.tar.gz",
        //
        //    // This is computed from the file contents of the directory of files that is
        //    // obtained after fetching `url` and applying the inclusion rules given by
        //    // `paths`.
        //    //
        //    // This field is the source of truth; packages do not come from a `url`; they
        //    // come from a `hash`. `url` is just one of many possible mirrors for how to
        //    // obtain a package matching this `hash`.
        //    //
        //    // Uses the [multihash](https://multiformats.io/multihash/) format.
        //    .hash = "...",
        //
        //    // When this is provided, the package is found in a directory relative to the
        //    // build root. In this case the package's hash is irrelevant and therefore not
        //    // computed. This field and `url` are mutually exclusive.
        //    .path = "foo",

        //    // When this is set to `true`, a package is declared to be lazily
        //    // fetched. This makes the dependency only get fetched if it is
        //    // actually used.
        //    .lazy = false,
        //},
    },

    // Specifies the set of files and directories that are included in this package.
    // Only files and directories listed here are included in the `hash` that
    // is computed for this package.
    // Paths are relative to the build root. Use the empty string (`""`) to refer to
    // the build root itself.
    // A directory listed here means that all files within, recursively, are included.
    .paths = .{
        // This makes *all* files, recursively, included in this package. It is generally
        // better to explicitly list the files and directories instead, to insure that
        // fetching from tarballs, file system paths, and version control all result
        // in the same contents hash.
        "",
        // For example...
        //"build.zig",
        //"build.zig.zon",
        //"src",
        //"LICENSE",
        //"README.md",
    },
}

round #56

submitted at
2 likes

guesses
comments 1
at *known at the time as [author of #4] ΒΆ

it does terminate i swear


post a comment


sIllylIttleguy.rb ASCII text
1
2
3
f=->s{s.gsub /(?<!\\)\(((?<z>(\\.|[^()|])*|\g<0>*)|\g<z>(\|\g<z>)+)(?<!\\)\)\*?/x,'\k<z>'}
i=->(n){loop{p=n;n=f[n];break if p==n};n;}
loop{k=Kernel.gets;k ?puts(i[k].gsub /\\(.)/,'\1'): break;}