summary refs log tree commit diff homepage
diff options
context:
space:
mode:
authorJune McEnroe <june@causal.agency>2021-12-08 16:13:15 -0500
committerJune McEnroe <june@causal.agency>2021-12-08 16:19:10 -0500
commite9f215d5af190f33c2f29d145b4b28785ba7400b (patch)
tree04f8314161293af49fd8664059e90de46cda4585
parentSolve day 8 part 1 (diff)
downloadaoc-e9f215d5af190f33c2f29d145b4b28785ba7400b.tar.gz
aoc-e9f215d5af190f33c2f29d145b4b28785ba7400b.zip
Solve day 8 part 2
That took me way too long from dumb mistakes.
Diffstat (limited to '')
-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);
+}