-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathday21.py
94 lines (82 loc) · 2.65 KB
/
day21.py
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
import os.path
import re
import math
from collections import defaultdict
import itertools
import md5
import msvcrt
import operator
import sys
def get_input(filename=None):
if not filename:
filename = os.path.splitext(os.path.basename(__file__))[0]+'.txt'
with open(filename) as fp:
input = fp.read().rstrip()
lines = input.split('\n')
ip = int(re.search(r'^#ip (\d)$', lines[0]).group(1))
return ip, [(opcode, int(a), int(b), int(c)) for opcode, a, b, c in [line.split(' ') for line in lines[1:]]]
def register(registers, value):
return registers[value]
def immediate(registers, value):
return value
OPCODES = {
'addr': {'op':operator.add,'a':register,'b':register},
'addi': {'op':operator.add,'a':register,'b':immediate},
'mulr': {'op':operator.mul,'a':register,'b':register},
'muli': {'op':operator.mul,'a':register,'b':immediate},
'banr': {'op':operator.and_,'a':register,'b':register},
'bani': {'op':operator.and_,'a':register,'b':immediate},
'borr': {'op':operator.or_,'a':register,'b':register},
'bori': {'op':operator.or_,'a':register,'b':immediate},
'setr': {'op':(lambda a,b: a),'a':register,'b':immediate},
'seti': {'op':(lambda a,b: a),'a':immediate,'b':immediate},
'gtir': {'op':operator.gt,'a':immediate,'b':register},
'gtri': {'op':operator.gt,'a':register,'b':immediate},
'gtrr': {'op':operator.gt,'a':register,'b':register},
'eqir': {'op':operator.eq,'a':immediate,'b':register},
'eqri': {'op':operator.eq,'a':register,'b':immediate},
'eqrr': {'op':operator.eq,'a':register,'b':register},
}
def executeasm(ip, instructions, registers = None):
if not registers:
registers = defaultdict(int)
while registers[ip] >= 0 and registers[ip] < len(instructions):
instruction = instructions[registers[ip]]
## print '%d: %s\t%r' %(registers[ip], ' '.join(map(str,instruction)), [registers[i] for i in xrange(6)])
opcode = OPCODES[instruction[0]]
registers[instruction[3]] = opcode['op'](opcode['a'](registers,instruction[1]),opcode['b'](registers,instruction[2]))
registers[ip] += 1
return registers[0]
def part1(input):
r5 = 0
while True:
r4 = r5 | 0x10000
r5 = 3935295
while r4:
r4, r2 = divmod(r4, 256)
r5 += r2
r5 &= 0xffffff
r5 *= 65899
r5 &= 0xffffff
return r5
def part2(input):
r5s = []
r5 = 0
while True:
r4 = r5 | 0x10000
r5 = 3935295
while r4:
r4, r2 = divmod(r4, 256)
r5 += r2
r5 &= 0xffffff
r5 *= 65899
r5 &= 0xffffff
if r5 in r5s:
return r5s[-1]
else:
## print r5
r5s.append(r5)
if __name__ == '__main__':
input = get_input()
print part1(input)
print part2(input)