summary refs log tree commit diff homepage
path: root/2022/day11-2.awk
blob: 27a405d2c8713e731aa1b24143261d1b7576c47e (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
BEGIN {
	FS = "[ :,]+";
}
/^Monkey/ {
	m = $2;
}
/Starting items/ {
	for (i = 4; i <= NF; ++i) {
		items[m,len[m]++] = $i;
	}
}
/Operation/ {
	op[m] = $6;
	const[m] = $7;
}
/Test/ {
	test[m] = $5;
}
/If true/ {
	true[m] = $7;
}
/If false/ {
	false[m] = $7;
}
END {
	mod = 1;
	for (m = 0; test[m]; ++m) {
		mod *= test[m];
	}
	for (n = 1; n <= 10000; ++n) {
		for (m = 0; test[m]; ++m) {
			for (i = 0; i < len[m]; ++i) {
				insp[m]++;
				item = items[m,i];
				delete items[m,i];
				if (op[m] == "+") {
					item += const[m];
				} else if (op[m] == "*" && const[m] != "old") {
					item *= const[m];
				} else {
					item *= item;
				}
				item %= mod;
				if (item % test[m] == 0) {
					items[true[m],len[true[m]]++] = item;
				} else {
					items[false[m],len[false[m]]++] = item;
				}
			}
			len[m] = 0;
		}
	}
	for (m = 0; test[m]; ++m) {
		if (insp[m] > max1) {
			max2 = max1;
			max1 = insp[m];
		} else if (insp[m] > max2) {
			max2 = insp[m];
		}
	}
	print max1 * max2;
}