aboutsummaryrefslogtreecommitdiffstats
path: root/src/02/main.c
blob: ec63fdbc96a8e4c6ce33da83c518ff5e2a7528be (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 "aoc.h"
#include "icc.h"
#include "util.h"
#include "allocator.h"

#include <stdlib.h>
#include <stdio.h>

void
part1(void)
{
	struct icc icc;
	int res, rc;

	icc_init(&icc);
	icc_parse_inst(&icc, aoc.input, aoc.input_size);

	icc_set_inst(&icc, 1, 12);
	icc_set_inst(&icc, 2, 2);

	while (icc.state != ICC_HALT) {
		rc = icc_step_inst(&icc);
		if (rc) die("icc step failed");
	}

	icc_get_inst(&icc, 0, &res);
	aoc.answer = aprintf("%i", res);
	aoc.solution = "5098658";

	icc_deinit(&icc);
}

void
part2(void)
{
	struct icc icc;
	struct dvec inst;
	int a, b, c;
	int rc;

	icc_init(&icc);
	icc.abort_on_err = false;
	icc_parse_inst(&icc, aoc.input, aoc.input_size);

	dvec_init(&inst, sizeof(int), 0, &stdlib_heap_allocator);
	dvec_copy(&inst, &icc.instructions);
	icc_debug_dump(&icc, &inst);

	for (a = 0; a < 100; a++) {
		for (b = 0; b < 100; b++) {
			icc_reset(&icc, &inst);

			icc_set_inst(&icc, 1, a);
			icc_set_inst(&icc, 2, b);

			aoc_debug("\nTrying a:%i b:%i\n\n", a, b);
			while (icc.state != ICC_HALT) {
				rc = icc_step_inst(&icc);
				if (rc == ICC_OOB_WRITE) {
					dvec_reserve(&icc.instructions,
						(size_t) icc.write_addr + 1);
					icc.instructions.len = MAX(
						icc.instructions.len,
						(size_t) icc.write_addr + 1);
				} else if (rc != ICC_OK) {
					break;
				}
			}

			icc_debug_dump(&icc, &inst);

			icc_get_inst(&icc, 0, &c);
			if (c == 19690720)
				goto exit;
		}
	}

exit:
	aoc.answer = aprintf("%02i%02i", a, b);
	aoc.solution = "5064";

	dvec_deinit(&inst);
	icc_deinit(&icc);
}