summary refs log tree commit diff homepage
path: root/2021/day04.c
blob: c414f819005d79a8cf12bc6dac4bd91ee8b3ea40 (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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static struct Board {
	int mark;
	int nums[25];
} boards[128];
static int len;
static int win(const struct Board *board) {
	int row = 0x1F;
	int col = 0x108421;
	for (int i = 0; i < 5; ++i) {
		if ((board->mark & row) == row) return 1;
		if ((board->mark & col) == col) return 1;
		row <<= 5;
		col <<= 1;
	}
	return 0;
}
static int winner(void) {
	for (int i = 0; i < len; ++i) {
		if (win(&boards[i])) return i;
	}
	return -1;
}
int main(void) {
	char *buf = NULL;
	size_t cap = 0;
	getline(&buf, &cap, stdin);
	int n = 0;
	int nums[128];
	while (buf) {
		nums[n++] = strtol(strsep(&buf, ","), NULL, 10);
	}
	for (int i = 0;; ++i) {
		if (EOF == scanf(" %d", &boards[len].nums[i%25])) break;
		if (i%25 == 24) len++;
	}
	int i, w;
	for (i = 0; (w = winner()) < 0 && i < n; ++i) {
		for (int j = 0; j < len; ++j) {
			for (int k = 0; k < 25; ++k) {
				if (boards[j].nums[k] == nums[i]) boards[j].mark |= 1 << k;
			}
		}
	}
	int num = nums[i-1];
	int sum = 0;
	for (int i = 0; i < 25; ++i) {
		if (!(boards[w].mark & (1 << i))) sum += boards[w].nums[i];
	}
	printf("%d\n", sum * num);
	for (; i < n; ++i) {
		for (int j = 0; j < len; ++j) {
			for (int k = 0; k < 25; ++k) {
				if (boards[j].nums[k] == nums[i]) {
					int won = win(&boards[j]);
					boards[j].mark |= 1 << k;
					if (!won && win(&boards[j])) {
						w = j;
						num = nums[i];
						sum = 0;
						for (int i = 0; i < 25; ++i) {
							if (!(boards[w].mark & (1 << i))) {
								sum += boards[w].nums[i];
							}
						}
					}
				}
			}
		}
	}
	printf("%d\n", sum * num);
}