day 15 golf more, 710 effective bytes
[aoc_eblake.git] / 2017 / advent5.c
blob7816632169719ac70ae3ad3b0e54bf2ec62f06bf
1 #define _GNU_SOURCE 1
2 #include <stdio.h>
3 #include <string.h>
4 #include <stdlib.h>
5 #include <unistd.h>
7 int main(void) {
8 /* slurp in all of stdin. Cheat - we know our input file size, so
9 pick a buffer larger than that */
10 static char buf[5000];
11 int len = 0;
12 while (len < sizeof buf) {
13 int ret = read(STDIN_FILENO, buf + len, sizeof buf - len);
14 if (ret < 0)
15 return 1;
16 if (!ret)
17 break;
18 len += ret;
20 if (len == sizeof buf)
21 return 2;
22 /* count lines */
23 int count = 0;
24 char *p = buf;
25 while ((p = memchr (p, '\n', buf + len - p)) && p++)
26 count++;
27 printf("found %d lines\n", count);
28 /* populate array */
29 int *array = calloc(sizeof(int), count);
30 p = buf;
31 char *q;
32 int i = 0;
33 while ((q = memchr (p, '\n', buf + len - p))) {
34 *q = '\0';
35 array[i++] = atoi(p);
36 p = q + 1;
38 if (getenv("DEBUG")) {
39 for (i = 0; i < count; i++)
40 printf("%d ", array[i]);
41 puts("\n");
43 /* run through maze */
44 int pc = 0;
45 int steps = 0;
46 while (pc >= 0 && pc < count) {
47 steps++;
48 #if 0 // part 1
49 pc += array[pc]++;
50 #else // part 2
51 int jump = array[pc];
52 if (jump >= 3)
53 array[pc]--;
54 else
55 array[pc]++;
56 pc += jump;
57 #endif
58 if (getenv("DEBUG"))
59 printf("moving to pc %d\n", pc);
61 printf("exited in %d steps\n", steps);
62 return 0;