day 25 solved in C
[aoc_eblake.git] / 2017 / advent11.c
blob7f8204cf87c1aedc6fb0828c49c81af48751d551
1 #define _GNU_SOURCE 1
2 #include <stdio.h>
3 #include <string.h>
4 #include <stdlib.h>
5 #include <unistd.h>
7 int distance(int nw, int n, int ne) {
8 // rotating path so all steps are positive results in same distance...
9 while (nw < 0 || n < 0 || ne < 0) {
10 int tnw = -ne, tn = nw, tne = n;
11 nw = tnw;
12 n = tn;
13 ne = tne;
15 if (nw < ne) {
16 n += nw;
17 ne -= nw;
18 nw = 0;
19 } else {
20 n += ne;
21 nw -= ne;
22 ne = 0;
24 return nw + n + ne;
27 int main(int argc, char **argv)
29 if (argc != 2)
30 return 1;
31 int nw = 0, n = 0, ne = 0;
32 char *p = argv[1];
33 char *next = p;
34 int count = 0;
35 int max = 0, dist = 0;
36 while (*next && (next = strchrnul(p, ','))) {
37 count++;
38 if ((next - p) == 1)
39 n += *p == 'n' ? 1 : -1;
40 else if (p[1] == 'e')
41 if (*p == 'n')
42 ne++;
43 else
44 nw--;
45 else if (*p == 'n')
46 nw++;
47 else
48 ne--;
49 dist = distance(nw, n, ne);
50 if (max < dist)
51 max = dist;
52 p = next + 1;
54 printf("after %d steps, nw=%d n=%d ne=%d\n", count, nw, n, ne);
55 printf("max distance %d, final distance %d\n", max, dist);
56 return 0;