day 1 golfed M4 500 significant bytes
[aoc_eblake.git] / 2016 / advent21.c
blob229ff6e995db3a00af8567f49c402e88aebbbad7
1 #define _GNU_SOURCE 1
2 #include <stdio.h>
3 #include <string.h>
4 #include <stdlib.h>
5 #include <unistd.h>
6 #include <assert.h>
8 #define MAX 100 // cheat by using wc on input file
9 char buf[30 * MAX];
10 char *lines[MAX];
12 int main(int argc, char **argv)
14 char array[9] = "fbgdceah";
15 char tmp[9];
16 int limit = strlen (array);
17 if (argc > 1)
18 limit = atoi (argv[1]);
19 if (argc > 2)
20 freopen (argv[2], "r", stdin);
21 array[limit] = '\0';
22 int nread = fread (buf, 1, sizeof buf, stdin);
23 char *p = buf;
24 int count = 0;
25 do {
26 lines[count++] = p;
27 p = strchr (p, '\n');
28 *p++ = '\0';
29 } while (p - buf < nread);
30 printf ("parsed %d lines, now reversing them\n", count);
31 int a, b;
32 char c, x, y;
33 for (int i = count; i--; ) {
34 printf ("iteration %d %s: ", i, lines[i]);
35 if (!strncmp (lines[i], "swap", 4)) {
36 a = sscanf (lines[i], "swap %c%*s %c with %*s %c", &c, &x, &y);
37 assert (a == 3);
38 if (c == 'p') {
39 c = array[x - '0'];
40 array[x - '0'] = array[y - '0'];
41 array[y - '0'] = c;
42 } else {
43 assert (c == 'l');
44 for (a = 0; a < limit; a++)
45 if (array[a] == x)
46 array[a] = y;
47 else if (array[a] == y)
48 array[a] = x;
50 } else if (!strncmp (lines[i], "rotate", 6)) {
51 a = sscanf (lines[i], "rotate %c", &c);
52 assert (a == 1);
53 if (c == 'b') {
54 a = sscanf (&lines[i][7], "%*s on position of letter %c", &c);
55 assert (a == 1);
56 b = strchr (array, c) - array;
57 assert (b < limit);
58 b = (b & 1) ? limit - (b + 1) / 2 : b ? 3 - b / 2 : 7;
59 } else {
60 a = sscanf (&lines[i][7], "%*s %d s%*s", &b);
61 assert (a == 1);
62 if (c == 'r')
63 b = limit - b;
65 for (a = 0; a < limit; a++)
66 tmp[(a + b) % limit] = array[a];
67 memcpy (array, tmp, limit);
68 } else if (!strncmp (lines[i], "reverse", 7)) {
69 c = sscanf (lines[i], "reverse positions %d through %d", &a, &b);
70 assert (c == 2);
71 for (c = 0; c < (b - a + 1) / 2; c++) {
72 x = array[c + a];
73 array[c + a] = array[b - c];
74 array[b - c] = x;
76 } else {
77 assert (!strncmp (lines[i], "move", 4));
78 c = sscanf (lines[i], "move position %d to position %d", &b, &a);
79 assert (c == 2);
80 x = array[a];
81 if (a < b)
82 memmove (array + a, array + a + 1, b - a);
83 else
84 memmove (array + b + 1, array + b, a - b);
85 array[b] = x;
87 printf ("%s\n", array);
89 printf ("original string: %s\n", array);
90 return 0;