summary refs log tree commit diff homepage
diff options
context:
space:
mode:
-rw-r--r--2021/day08-2.c84
1 files changed, 84 insertions, 0 deletions
diff --git a/2021/day08-2.c b/2021/day08-2.c
new file mode 100644
index 0000000..9aa67c5
--- /dev/null
+++ b/2021/day08-2.c
@@ -0,0 +1,84 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+static int segDigit(int seg) {
+	switch (seg) {
+		case 0x77: return 0;
+		case 0x12: return 1;
+		case 0x5D: return 2;
+		case 0x5B: return 3;
+		case 0x3A: return 4;
+		case 0x6B: return 5;
+		case 0x6F: return 6;
+		case 0x52: return 7;
+		case 0x7F: return 8;
+		case 0x7B: return 9;
+		default: return -1;
+	}
+}
+struct Map {
+	int m[7];
+};
+static int mapDigit(struct Map map, int seg) {
+	int x = 0;
+	for (int i = 0; i < 7; ++i) {
+		if (seg & (1 << map.m[i])) x |= 1 << i;
+	}
+	return segDigit(x);
+}
+static int mapValid(struct Map map, int segs[]) {
+	int got[10] = {0};
+	for (int i = 0; i < 10; ++i) {
+		int digit = mapDigit(map, segs[i]);
+		if (digit < 0) return 0;
+		got[digit]++;
+	}
+	for (int i = 0; i < 10; ++i) {
+		if (got[i] != 1) return 0;
+	}
+	return 1;
+}
+static void swap(int *a, int *b) {
+	int x = *a;
+	*a = *b;
+	*b = x;
+}
+static int mapPermute(struct Map *map, int i, int segs[]) {
+	for (int j = i; j < 7; ++j) {
+		swap(&map->m[i], &map->m[j]);
+		if (mapPermute(map, i+1, segs)) return 1;
+		swap(&map->m[i], &map->m[j]);
+	}
+	return mapValid(*map, segs);
+}
+static int segParse(const char *s) {
+	int x = 0;
+	for (; *s; ++s) {
+		x |= 1 << (*s - 'a');
+	}
+	return x;
+}
+int main(void) {
+	int sum = 0;
+	size_t cap = 0;
+	char *buf = NULL;
+	while (0 < getline(&buf, &cap, stdin)) {
+		int segs[10], outs[4];
+		char *ptr = buf;
+		for (int i = 0; i < 10; ++i) {
+			segs[i] = segParse(strsep(&ptr, " "));
+		}
+		strsep(&ptr, " ");
+		for (int i = 0; i < 4; ++i) {
+			outs[i] = segParse(strsep(&ptr, " \n"));
+		}
+		struct Map map = { { 0, 1, 2, 3, 4, 5, 6 } };
+		int valid = mapPermute(&map, 0, segs);
+		if (!valid) printf("oops!\n");
+		for (int i = 0; i < 4; ++i) {
+			outs[i] = mapDigit(map, outs[i]);
+		}
+		sum += outs[0]*1000 + outs[1]*100 + outs[2]*10 + outs[3];
+	}
+	printf("%d\n", sum);
+}