summary refs log tree commit diff homepage
path: root/2019/day07.c
blob: c27aacd75bf994c6e1119e57a9ce803530d3b002 (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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

enum {
	Halt,
	Input,
	Output,
};

struct Intcode {
	int ip;
	int mode[3];
	int mem[1024];
	int in;
	int out;
};

static int *p(struct Intcode *m, int i) {
	return (m->mode[i - 1] ? &m->mem[m->ip + i] : &m->mem[m->mem[m->ip + i]]);
}

static int run(struct Intcode *m) {
	for (;;) {
		m->mode[0] = m->mem[m->ip] / 100 % 10;
		m->mode[1] = m->mem[m->ip] / 1000 % 10;
		m->mode[2] = m->mem[m->ip] / 10000 % 10;
		switch (m->mem[m->ip] % 100) {
			break; case 1: *p(m, 3) = *p(m, 1) + *p(m, 2); m->ip += 4;
			break; case 2: *p(m, 3) = *p(m, 1) * *p(m, 2); m->ip += 4;
			break; case 3: *p(m, 1) = m->in; m->ip += 2; return Input;
			break; case 4: m->out = *p(m, 1); m->ip += 2; return Output;
			break; case 5: m->ip = (*p(m, 1) ? *p(m, 2) : m->ip + 3);
			break; case 6: m->ip = (*p(m, 1) ? m->ip + 3 : *p(m, 2));
			break; case 7: *p(m, 3) = (*p(m, 1) < *p(m, 2)); m->ip += 4;
			break; case 8: *p(m, 3) = (*p(m, 1) == *p(m, 2)); m->ip += 4;
			break; case 99: return Halt;
			break; default: abort();
		}
	}
}

int main(void) {
	int mem[1024] = {0};
	for (int i = 0; EOF != scanf("%d,", &mem[i]); ++i);

	struct Intcode amp[5] = {0};
	int max = 0;
	for (int p = 0; p <= 044444; ++p) {
		int x = p;
		for (int i = 0; i < 5; ++i) {
			amp[i].in = x & 7;
			x >>= 3;
		}
		for (int i = 0; i < 5; ++i) {
			if (amp[i].in > 4) goto skip;
			for (int j = 0; j < 5; ++j) {
				if (i != j && amp[i].in == amp[j].in) goto skip;
			}
		}
		for (int i = 0; i < 5; ++i) {
			amp[i].ip = 0;
			memcpy(amp[i].mem, mem, sizeof(amp[i].mem));
			while (run(&amp[i]) != Input);
			amp[i].in = (i ? amp[i - 1].out : 0);
			while (run(&amp[i]) != Halt);
		}
		if (amp[4].out > max) max = amp[4].out;
skip:;
	}
	printf("%d\n", max);

	max = 0;
	for (int p = 0; p <= 044444; ++p) {
		int x = p;
		for (int i = 0; i < 5; ++i) {
			amp[i].in = 5 + (x & 7);
			amp[i].out = 0;
			x >>= 3;
		}
		for (int i = 0; i < 5; ++i) {
			if (amp[i].in > 9) goto skip2;
			for (int j = 0; j < 5; ++j) {
				if (i != j && amp[i].in == amp[j].in) goto skip2;
			}
		}
		for (int i = 0; i < 5; ++i) {
			amp[i].ip = 0;
			memcpy(amp[i].mem, mem, sizeof(amp[i].mem));
			run(&amp[i]);
		}
		amp[0].in = 0;
		for (int i = 0;;) {
			int x = run(&amp[i]);
			if (x == Output) {
				int out = amp[i].out;
				i = (i + 1) % 5;
				amp[i].in = out;
			} else if (x == Halt) {
				break;
			}
		}
		if (amp[4].out > max) max = amp[4].out;
skip2:;
	}
	printf("%d\n", max);
}