diff options
Diffstat (limited to '2017')
-rw-r--r-- | 2017/03/Makefile | 6 | ||||
-rw-r--r-- | 2017/03/input | 1 | ||||
-rw-r--r-- | 2017/03/puzzle-1.c | 50 | ||||
-rwxr-xr-x | 2017/03/puzzle-2.awk | 38 |
4 files changed, 95 insertions, 0 deletions
diff --git a/2017/03/Makefile b/2017/03/Makefile new file mode 100644 index 0000000..fd82d57 --- /dev/null +++ b/2017/03/Makefile @@ -0,0 +1,6 @@ +all: + ${CC} ${CFLAGS} -o puzzle-1 puzzle-1.c + +.PHONY: clean +clean: + rm -f puzzle-1 diff --git a/2017/03/input b/2017/03/input new file mode 100644 index 0000000..e079a50 --- /dev/null +++ b/2017/03/input @@ -0,0 +1 @@ +265149 diff --git a/2017/03/puzzle-1.c b/2017/03/puzzle-1.c new file mode 100644 index 0000000..00cebd7 --- /dev/null +++ b/2017/03/puzzle-1.c @@ -0,0 +1,50 @@ +#include <err.h> +#include <stdio.h> +#include <stdlib.h> + +#define ODD(x) (x & 1) +#define MOVE(x) \ + do { \ + for (int k = 0; k < j; k++) { \ + x; \ + if (++m == n) \ + goto out; \ + } \ + } while (0) + +int +main(void) +{ + int n, x, y; + FILE *fp; + + if (!(fp = fopen("input", "r"))) + err(EXIT_FAILURE, "fopen"); + + fscanf(fp, "%d", &n); + fclose(fp); + + x = y = 0; + for (int i = 1, m = 1, j = 1; i < n; i++) { + if (ODD(i)) { + if (ODD(j)) + MOVE(x++); + else + MOVE(x--); + } else { + if (ODD(j)) + MOVE(y++); + else + MOVE(y--); + j++; + } + } +out: + if (x < 0) + x = -x; + if (y < 0) + y = -y; + + printf("%d\n", x + y); + return EXIT_SUCCESS; +} diff --git a/2017/03/puzzle-2.awk b/2017/03/puzzle-2.awk new file mode 100755 index 0000000..0758658 --- /dev/null +++ b/2017/03/puzzle-2.awk @@ -0,0 +1,38 @@ +#!/usr/bin/env -S awk -f + +function move(xi, yi) +{ + for (k = 0; k < j; k++) { + if (xi) + x += xi + else + y += yi + + spiral[y][x] = spiral[y][x - 1] + spiral[y][x + 1] + spiral[y + 1][x + 1] \ + + spiral[y + 1][x] + spiral[y + 1][x - 1] + spiral[y - 1][x + 1] \ + + spiral[y - 1][x] + spiral[y - 1][x - 1] + if (spiral[y][x] > n) + return spiral[y][x] + } + return 0 +} + +{ n = $1 } + +END { + spiral[0][0] = 1 + x = y = 0 + j = 1 + for (i = 1; 1; i++) { + if (i % 2) + if (r = move(j % 2 ? 1 : -1, 0)) + break + else { + if (r = move(0, j % 2 ? 1 : -1)) + break + j++ + } + } + + print r +} |