all stats

at's stats

guessed the most

namecorrect guessesgames togetherratio
LyricLy140.250
kimapr040.000

were guessed the most by

namecorrect guessesgames togetherratio
LyricLy140.250
kimapr040.000

entries

round #62

submitted at
1 like

guesses
comments 0

post a comment


Makefile ASCII text, with CRLF line terminators
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
CC?=clang

all:
	$(CC) -pedantic -Wall -g -o drill main.c

nr: all
	./drill
	
dbg: all
	gdb drill
main.c Unicode text, UTF-8 text, with CRLF line terminators
  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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
// DRILL.
// WRITTEN BY OLUS2000.
// INSPIRED BY SAM. http://sam.cat-v.org/ 
// COMES WITH NO WARRANTY.
// WILL EAT YOUR CAT.
// HACK THE PLANET.
// YOU WANT TO USE IT? EDIT MAIN.
// COMES WITH LOVENSE INTEGRATION.
// BORN TO DIE.
// WORLD IS A FUCK.
// 鬼䘥 KILL EM ALL 1989.
// I AM TRASH MAN.
// 410,757,864,530 DEAD COPS.
// THE ONLY WINNING MOVE IS NOT TO PLAY.
// REST IN PEACE AUGUST 20, 2018.

// BUILD WITH `make`. RUN WITH `./drill`.
// IT'S NOTHING BUT PURE COCAINE AND C99.
// I LOVE YOU.

// HERE'S A FUCKING PHILOSOPHY FOR YOU: 
// https://12ft.io/proxy?q=https%3A%2F%2Fwww.theatlantic.com%2Fscience%2Farchive%2F2017%2F08%2Fannie-dillards-total-eclipse%2F536148%2F
// READ 'EM AND WEEP.

#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#define MAX(a,b) ((a) > (b) ? (a) : (b))
#define MIN(a,b) ((a) < (b) ? (a) : (b))

#define DEBUG
// Remove the below line for debug mode.
#undef DEBUG

/* ~~~~~~~~~~~ VM ~~~~~~~~~~~ */
// walk the bytecode now
// sweet machine, focus on the text
// iterate quickly.
typedef struct Span {
    char* start;
    char* end;
} Span;

typedef struct Foci {
    unsigned long cnt;         // how many foci exist
    unsigned long contiguousc; // size of the foci arena.
    Span* s;                   // the foci
} Foci;

void foci_init(Foci* uninitialized) {
    *uninitialized = (Foci){ .cnt = 0, .contiguousc = 0, .s = NULL };
}

void foci_free(Foci in) {
    free(in.s);
}

typedef enum BytecodeTag {
    BCT_SUBSTITUTE, // Replace the foci with a given string
    BCT_DRILL,      // Narrow the foci to a given regex (well, string)
    BCT_AROUND,     // Narrow the foci to their 0-length beginnings and ends
    BCT_STARTS,     // Narrow the foci to their 0-length beginnings
    BCT_ENDS,       // Narrow the foci to their 0-length ends
    BCT_COMPLEMENT  // Invert focus
} BytecodeTag;

typedef struct Bytecode {
    BytecodeTag* tag;
    char** data;
    unsigned int cnt;         // count of elements in tags and data
    unsigned int contiguousc; // size of allocated arenas for tags and data
} Bytecode;

#define _print_bytecode_branch(idx, name) case name:\
    printf("%ld " #name, ip);\
    break;

void print_single_bytecode(Bytecode in, unsigned long ip) {
    switch (in.tag[ip]) {
        _print_bytecode_branch(ip, BCT_SUBSTITUTE)
        _print_bytecode_branch(ip, BCT_DRILL)
        _print_bytecode_branch(ip, BCT_AROUND)
        _print_bytecode_branch(ip, BCT_STARTS)
        _print_bytecode_branch(ip, BCT_ENDS)
        _print_bytecode_branch(ip, BCT_COMPLEMENT)
    }
    if (in.data[ip] == NULL) {
        printf(" (no data)\n");
    } else {
        printf(" \"%s\"\n", in.data[ip]);
    }
}

void print_bytecode(Bytecode in) {
    for (unsigned int i = 0; i < in.cnt; i++) {
        print_single_bytecode(in, i);
    }
}

void bytecode_recursive_free(Bytecode* bc) {
    for (unsigned int i = 0; i < bc->cnt; i++) {
        free(bc->data[i]);
    }
    free(bc->tag);
    free(bc);
}

void bytecode_init(Bytecode* uninitialized) { 
    *uninitialized = (Bytecode){ .tag = NULL, .data = NULL, .cnt = 0, .contiguousc = 0 };
}

// Reallocs the bytecode if it overflows with `newelems` entries added
void bytecode_realloc(Bytecode* in, unsigned int newelems) {
    while ((in->cnt + newelems) * sizeof(void*) > in->contiguousc) {
        in->contiguousc = (in->contiguousc + 1) * 2;
        in->tag = realloc(in->tag, in->contiguousc);
        in->data = realloc(in->data, in->contiguousc);
    }
}

// void* data should live until the deallocation of the bytecode
void bytecode_append(Bytecode* in, BytecodeTag tag, char* data) {
    bytecode_realloc(in, 1);
    in->tag[in->cnt] = tag;
    in->data[in->cnt] = data;
    in->cnt++;
}

void bytecode_concat(Bytecode* in, Bytecode other) {
    // realloc to get more space if we've run out
    bytecode_realloc(in, other.cnt);
    for (unsigned int i = 0; i < other.cnt; i++) {
        in->tag[in->cnt + i] = other.tag[i];
        in->data[in->cnt + i] = other.data[i];
    }
    in->cnt += other.cnt;
}


// once all appending actions have been done, make sure
// to call foci_merge_overlapping to deduplicate spans
void foci_append(Foci* foci, char* start, char* end) {    
    if (foci->contiguousc <= (foci->cnt + 1) * sizeof(Span)) {
        foci->contiguousc = (foci->cnt + 1) * sizeof(Span) * 2;
        foci->s = realloc(foci->s, foci->contiguousc);
    }
    foci->s[foci->cnt].start = start;
    foci->s[foci->cnt].end = end;
    foci->cnt++;
}

char* foci_min_start(Foci foci) {
    char* min_start = foci.s[0].start;
    for (unsigned long i = 1; i < foci.cnt; i++) {
        if (foci.s[i].start < min_start) {
            min_start = foci.s[i].start;
        }
    }
    return min_start;
}

char* foci_max_end(Foci foci) {
    char* max_end = foci.s[0].end;
    for (unsigned long i = 1; i < foci.cnt; i++) {
        if (foci.s[i].end > max_end) {
            max_end = foci.s[i].end;
        }
    }
    return max_end;
}

// returns the index of the first span focusing on the ptr, or -1.
long foci_check(Foci in, char* ptr) {
    for (unsigned long i = 0; i < in.cnt; i++) {
        Span tester = in.s[i];
        if (ptr >= tester.start && ptr < tester.end) {
            return i;
        }
    }
    return -1;
}

// this creates a distinct copy, it's safe to call foci_free on the input afterwards
// TODO: support distinct foci bordering each other... iterate and check if we're in two spans?
// TODO: this breaks 0 length spans
// TODO: can some sweet, silly code guesser fix this function for me? thx...
Foci foci_merge_overlapping(Foci in) {
    Foci out;
    foci_init(&out);
    if (in.cnt == 0) {
        return out;
    }
    char* min_start = foci_min_start(in);
    char* max_end = foci_max_end(in);
    foci_append(&out, min_start, min_start+1);
    char scanning = 1;
    for (char* ptr = min_start; ptr < max_end; ptr++) {
        if (foci_check(in, ptr) >= 0) {
            if (scanning) {
                out.s[out.cnt - 1].end = ptr+1;
            } else {
                foci_append(&out, ptr, ptr+1);
                scanning = 1;
            }
        } else {
            if (scanning) {
                scanning = 0;
            }
        }
    }
    return out;
}

void print_span(Span s) {
    printf("\"%.*s\"\n", (int)(s.end - s.start), s.start);
}

void print_foci(Foci f) {
    printf("Foci cnt: %ld\n", f.cnt);
    for (unsigned long i = 0; i < f.cnt; i++) {
        printf("%ld ", i);
        print_span(f.s[i]);
    }
}

// the core of the brain
// oh! watch the pointer move right
// implementing logic
typedef struct VM {            // Execution model
    unsigned long ip;          // current execution offset into Bytecode tag+data
    Bytecode bc;               // the bytecode we're executing
    char* text;                // the text to mutate
    Foci foci;                 // what text is currently focused?
} VM;

void vm_init(VM* uninitialized, char* in, Bytecode bc) {
    Foci foci;
    foci_init(&foci);
    // VMs start with everything focused
    foci_append(&foci, in, strchr(in, '\0'));
    *uninitialized = (VM){ .ip = 0, .bc = bc, .text = in, .foci = foci };
}

void vm_merge_overlapping_foci(VM* vm) {
    Foci old_foci = vm->foci;
    vm->foci = foci_merge_overlapping(vm->foci);
    foci_free(old_foci);
}

// expects vm->ip to be pointing to a BCT_DRILL tag and a regex in data
// drill drill drill drill drill
// drill drill drill drill drill drill drill
// drill drill drill drill drill
void vm_run_drill(VM* vm) {
    char* regex = vm->bc.data[vm->ip];
    unsigned long match_length = strlen(regex);
    Foci new_foci;
    foci_init(&new_foci);
    for (unsigned long i = 0; i < vm->foci.cnt; i++) {
        Span focus = vm->foci.s[i];
        unsigned long focus_length = focus.end - focus.start;
        char* haystack = focus.start;
        while (*haystack != '\0') {
            #ifdef DEBUG
            printf("calling strncmp with %s, %s, %ld, got %d\n", haystack, regex, match_length, strncmp(haystack, regex, match_length));
            #endif
            if (strncmp(haystack, regex, MIN(match_length, focus_length)) == 0) { // TODO: regex
                foci_append(&new_foci, haystack, haystack + match_length);
            } 
            haystack++;
        }
    }
    foci_free(vm->foci);
    vm->foci = new_foci;
}

// expects vm->ip to be pointing to a BCT_SUBSTITUTE tag and the sub string in data
void vm_run_substitute(VM* vm) {
    char* subby = vm->bc.data[vm->ip];
    // calculate length of string post-substitution
    unsigned long foci_length = 0;
    for (unsigned long i = 0; i < vm->foci.cnt; i++) {
        foci_length += vm->foci.s[i].end - vm->foci.s[i].end;
    }
    char* new_text = calloc(strlen(vm->text) - foci_length + strlen(subby) * vm->foci.cnt, sizeof(char));
    // copy focus structure
    Foci new_foci;
    foci_init(&new_foci);
    for (unsigned int i = 0; i < vm->foci.cnt; i++) {
        char* new_start = new_text + (vm->foci.s[i].start - vm->text);
        char* new_end = new_text + (vm->foci.s[i].end - vm->text);
        foci_append(&new_foci, new_start, new_end);
    }
    // build new_text from successive concatenations
    char* done = vm->text;
    unsigned long i = 0;
    for (; i < vm->foci.cnt; i++) {
        Span focus = vm->foci.s[i];
        strncat(new_text, done, focus.start - done);
        strcat(new_text, subby);
        done = focus.end;
        // adjust foci affected by this substitution, including pointing them to new_text
        unsigned long text_length_change = strlen(subby) - (focus.end - focus.start);
        new_foci.s[i].end += text_length_change;
        for (unsigned long j = i+1; j < vm->foci.cnt; j++) {
            new_foci.s[j].start += text_length_change;
            new_foci.s[j].end += text_length_change;
        }
    }
    strcat(new_text, done);
    free(vm->text);
    vm->text = new_text;
    foci_free(vm->foci);
    vm->foci = new_foci;
}

// expects vm->ip to be pointing to a BCT_AROUND tag
void vm_run_around(VM* vm) {    
    Foci new_foci;
    foci_init(&new_foci);
    for (unsigned long i = 0; i < vm->foci.cnt; i++) {
        Span focus = vm->foci.s[i];
        foci_append(&new_foci, focus.start, focus.start);
        foci_append(&new_foci, focus.end, focus.end);
    }
    foci_free(vm->foci);
    vm->foci = new_foci;
}

// expects vm->ip to be pointing to a BCT_STARTS tag
void vm_run_starts(VM* vm) {    
    Foci new_foci;
    foci_init(&new_foci);
    for (unsigned long i = 0; i < vm->foci.cnt; i++) {
        Span focus = vm->foci.s[i];
        foci_append(&new_foci, focus.start, focus.start);
    }
    foci_free(vm->foci);
    vm->foci = new_foci;
}

// expects vm->ip to be pointing to a BCT_ENDS tag
void vm_run_ends(VM* vm) {    
    Foci new_foci;
    foci_init(&new_foci);
    for (unsigned long i = 0; i < vm->foci.cnt; i++) {
        Span focus = vm->foci.s[i];
        foci_append(&new_foci, focus.end, focus.end);
    }
    foci_free(vm->foci);
    vm->foci = new_foci;
}

// expects vm->ip to be pointing to a BCT_COMPLEMENT tag
void vm_run_complement(VM* vm) {    
    Foci new_foci;
    foci_init(&new_foci);
    char* done = vm->text;
    for (unsigned long i = 0; i < vm->foci.cnt; i++) {
        Span focus = vm->foci.s[i];
        foci_append(&new_foci, done, focus.start);
        done = focus.end;
    }
    foci_append(&new_foci, done, strchr(vm->text, '\0')); 
    foci_free(vm->foci);
    vm->foci = new_foci;
}


void print_vm(VM vm) {
    printf("Text: %s\n", vm.text);
    printf("Bytecode:\n");
    print_bytecode(vm.bc);
    printf("IP: %ld\n", vm.ip);
    printf("Foci:\n");
    print_foci(vm.foci);
    puts("");
    puts("");
}

// returns pointer to mutated text on success, NULL on error
char* vm_run(VM vm) {
    #ifdef DEBUG
    printf("Initial state:\n");
    print_vm(vm);
    #endif
    for (; vm.ip < vm.bc.cnt; vm.ip++) {
        switch (vm.bc.tag[vm.ip]) {
            case BCT_DRILL:
                vm_run_drill(&vm);
                // TODO: figure out if merging overlapping foci is needed here
                // TODO: can test with a drill like /ss/ and a string like "sss"
                // vm_merge_overlapping_foci(&vm);
                break;
            case BCT_SUBSTITUTE:
                vm_run_substitute(&vm);
                break;
            case BCT_AROUND:
                vm_run_around(&vm);
                break;
            case BCT_STARTS:
                vm_run_starts(&vm);
                break;
            case BCT_ENDS:
                vm_run_ends(&vm);
                break;
            case BCT_COMPLEMENT:
                vm_run_complement(&vm);
                break;
            default:
                printf("Got unimplemented bytecode ");
                print_single_bytecode(vm.bc, vm.ip);
        }
        #ifdef DEBUG
        print_vm(vm);
        #endif
    }
    return vm.text;
}



/* ~~~~~~~~~~~ Parser ~~~~~~~~~~~ */
// let her speak! a voice
// feminine, or masculine,
// booming from heaven
#define PAD_SIZE 1024
typedef struct ParseState {
    Bytecode out; // Did this parser produce output? "No" represented by a zero-length Bytecode
    char* altout; // Some parsers produce strings instead
    char* rest; // The rest of the input stream
} ParseState;

void parsestate_init(ParseState* uninitialized, char* unparsed) {
    Bytecode bc;
    bytecode_init(&bc);
    *uninitialized = (ParseState){ .out = bc, .altout = NULL, .rest = unparsed };
}

void parsestate_free(ParseState ps) {
    free(ps.altout);
}

void die(const char* fmt,...) {
    va_list args;
    va_start(args, fmt);
    vprintf(fmt, args);
    va_end(args);
    exit(1);
}

void consume_subparse(ParseState* p, ParseState subparse) {
    if (subparse.out.cnt > 0) {
        bytecode_concat(&p->out, subparse.out);
    }
    p->rest = subparse.rest;
}

// parses regexp/, so like a regexp missing the leading slash & ending on a slash, places it in altout
ParseState parse_regexp(char* in) {
    ParseState o = { .altout = "", .rest = in };
    char pad[PAD_SIZE] = "";
    unsigned int padc = 0;
    while (padc < PAD_SIZE) {
        char c = *o.rest;
        switch (c) {
            case '\0':
                die("EOF while parsing regexp");
                break;
            case '/':
                goto done;
            default:
                pad[padc++] = *o.rest;
                pad[padc] = '\0';
                o.rest++;
        }
    } done:
    o.altout = strdup(pad);
    return o;
}

// parses quote", so like a string missing the leading quote & ending on a quote, places it in altout
ParseState parse_quote(char* in) {
    ParseState o = { .altout = "", .rest = in };
    char pad[PAD_SIZE] = "";
    unsigned int padc = 0;
    while (padc < PAD_SIZE) {
        char c = *o.rest;
        switch (c) {
            case '\0':
                die("EOF while parsing quote");
                break;
            case '"':
                goto done;
            default:
                pad[padc++] = *o.rest;
                pad[padc] = '\0';
                o.rest++;
        }
    } done:
    o.altout = strdup(pad);
    return o;
}

// parses s/regexp/
ParseState parse_substitute(char* in) {
    ParseState o;
    parsestate_init(&o, in);
    if (*(o.rest++) != 's') {
        die("Expected s at start of substitution");
    }
    if (*(o.rest++) != '/') {
        die("Expected s/ at start of substitution");
    }
    ParseState sub = parse_regexp(o.rest);
    consume_subparse(&o, sub);
    bytecode_append(&o.out, BCT_SUBSTITUTE, strdup(sub.altout));
    parsestate_free(sub);
    if (*(o.rest++) != '/') {
        die("Expected / at the end of substitution");
    }
    return o;
}

// parses /regexp/
ParseState parse_drill(char* in) {
    ParseState o;
    parsestate_init(&o, in);
    if (*(o.rest++) != '/') {
        die("Expected / at start of drill");
    }
    ParseState sub = parse_regexp(o.rest);
    consume_subparse(&o, sub);
    bytecode_append(&o.out, BCT_DRILL, strdup(sub.altout));
    parsestate_free(sub);
    if (*(o.rest++)!= '/') {
        die("Expected / at end of drill");
    }

    return o;
}


ParseState parse_root(char* in) {
    ParseState o;
    parsestate_init(&o, in);
    while (1) {
        char c = *o.rest;
        ParseState sub;
        switch (c) {
            case '\0':
                goto done;
            case 's':
                sub = parse_substitute(o.rest);
                consume_subparse(&o, sub);
                parsestate_free(sub);
                break;
            case '/':
                sub = parse_drill(o.rest);
                consume_subparse(&o, sub);
                parsestate_free(sub);
                break;
            case '^':
                o.rest++;
                bytecode_append(&o.out, BCT_STARTS, NULL);
                break;
            case '$':
                o.rest++;
                bytecode_append(&o.out, BCT_ENDS, NULL);
                break;
            // Philomena Cunk wuz here
            case '%':
                o.rest++;
                bytecode_append(&o.out, BCT_AROUND, NULL);
                break;
            case '@':
                o.rest++;
                bytecode_append(&o.out, BCT_COMPLEMENT, NULL);
                break;
            case ' ':
            case '\t':
            case '\n':
                o.rest++;
                break;
            default:
                die("Unexpected %c in root parser", c);
                break;
        }
    } done:
    return o;
}

Bytecode parse(char* in) {
    return parse_root(in).out;
}

// requires a heap-allocated text
char* run(char* progstr, char* text) {
    Bytecode prog = parse(progstr);
    #ifdef DEBUG
    print_bytecode(prog);
    puts("");
    #endif
    VM vm;
    vm_init(&vm, text, prog);
    return vm_run(vm);
}

// woag
int main(int argc, char** argv) {
    printf("%s\n", run("/hello,/ s// s/I'm ready to conquer the/", strdup("hello, world!")));
    printf("%s\n", run("^ s/This text is at the start /", strdup("hello, world!")));
    printf("%s\n", run("$ s/ This text is at the end/", strdup("hello, world!")));
    printf("%s\n", run("% s/ This text is at the start and the end /", strdup("hello, world!")));
    printf("%s\n", run("/l/ % s/ol/", strdup("hello, world!")));
    printf("%s\n", run("/,/ @ s/lol/", strdup("hello,,,  world! i love to sing, dance, and play video games!")));
    return 0;
}

// two men walk abreast
// into the dark night sky ablaze with
// ten thousand dying stars

round #61

submitted at
0 likes

guesses
comments 0

post a comment


image-of-a-cat.py ASCII text, with CRLF line terminators
1
2
3
import random
print(random.choice("MI"))
print(random.choice("ULDR"))

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;}