summary refs log tree commit diff homepage
path: root/2021/day08-2.c
blob: 9aa67c50f08c39a6f6889241e7f4bbbce1be74cb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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);
}