|
@@ -0,0 +1,64 @@
|
|
1
|
+import math, sequtils, strutils, tables
|
|
2
|
+
|
|
3
|
+type instr = tuple[op: string, a,b,c: int]
|
|
4
|
+
|
|
5
|
+let ops = {
|
|
6
|
+ "addi": proc(regs: seq[int], a,b: int): int = regs[a] + b,
|
|
7
|
+ "addr": proc(regs: seq[int], a,b: int): int = regs[a] + regs[b],
|
|
8
|
+
|
|
9
|
+ "muli": proc(regs: seq[int], a,b: int): int = regs[a] * b,
|
|
10
|
+ "mulr": proc(regs: seq[int], a,b: int): int = regs[a] * regs[b],
|
|
11
|
+
|
|
12
|
+ "bani": proc(regs: seq[int], a,b: int): int = regs[a] and b,
|
|
13
|
+ "banr": proc(regs: seq[int], a,b: int): int = regs[a] and regs[b],
|
|
14
|
+
|
|
15
|
+ "bori": proc(regs: seq[int], a,b: int): int = regs[a] or b,
|
|
16
|
+ "borr": proc(regs: seq[int], a,b: int): int = regs[a] or regs[b],
|
|
17
|
+
|
|
18
|
+ "seti": proc(regs: seq[int], a,b: int): int = a,
|
|
19
|
+ "setr": proc(regs: seq[int], a,b: int): int = regs[a],
|
|
20
|
+
|
|
21
|
+ "gtir": proc(regs: seq[int], a,b: int): int = cast[int](a > regs[b]),
|
|
22
|
+ "gtri": proc(regs: seq[int], a,b: int): int = cast[int](regs[a] > b),
|
|
23
|
+ "gtrr": proc(regs: seq[int], a,b: int): int = cast[int](regs[a] > regs[b]),
|
|
24
|
+
|
|
25
|
+ "eqir": proc(regs: seq[int], a,b: int): int = cast[int](a == regs[b]),
|
|
26
|
+ "eqri": proc(regs: seq[int], a,b: int): int = cast[int](regs[a] == b),
|
|
27
|
+ "eqrr": proc(regs: seq[int], a,b: int): int = cast[int](regs[a] == regs[b]),
|
|
28
|
+}.toTable
|
|
29
|
+
|
|
30
|
+var
|
|
31
|
+ instructions: seq[instr]
|
|
32
|
+ ip: int
|
|
33
|
+
|
|
34
|
+for line in readFile("data/19.txt").strip.splitlines:
|
|
35
|
+ var parts = line.split(' ')
|
|
36
|
+ if parts[0] == "#ip":
|
|
37
|
+ ip = parts[1].parseInt
|
|
38
|
+ else:
|
|
39
|
+ instructions.add((parts[0], parts[1].parseInt, parts[2].parseInt, parts[3].parseInt))
|
|
40
|
+
|
|
41
|
+proc findTarget(part2: bool): int =
|
|
42
|
+ # The instructions calculate the sum of all factors of a target number. The
|
|
43
|
+ # target is initialised first, and then execution jumps back to near the
|
|
44
|
+ # start of the program to perform the calculation. To find the target
|
|
45
|
+ # number, we evaluate until a backwards jump and then just take the largest
|
|
46
|
+ # register. (Yuck.)
|
|
47
|
+ var registers = @[if part2: 1 else: 0, 0, 0, 0, 0, 0]
|
|
48
|
+ while true:
|
|
49
|
+ let
|
|
50
|
+ i = registers[ip]
|
|
51
|
+ instr = instructions[i]
|
|
52
|
+ registers[instr.c] = ops[instr.op](registers, instr.a, instr.b)
|
|
53
|
+ registers[ip].inc
|
|
54
|
+ if registers[ip] < i:
|
|
55
|
+ return registers.max
|
|
56
|
+
|
|
57
|
+proc factors(n: int): seq[int] =
|
|
58
|
+ for x in 1 .. int(sqrt(float(n))):
|
|
59
|
+ if n mod x == 0:
|
|
60
|
+ result.add(x)
|
|
61
|
+ result.add(n div x)
|
|
62
|
+
|
|
63
|
+echo findTarget(false).factors.sum
|
|
64
|
+echo findTarget(true).factors.sum
|