Skip to content

Commit f576171

Browse files
author
Joth
committed
make clean version of part 1
1 parent bc4e4a3 commit f576171

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
# Advent Of Code 2019, Day 5, Part 1
2+
# Author: Joth (https://github.com/joth00)
3+
4+
from os import path
5+
6+
7+
def main():
8+
text_input = get_raw_input()
9+
int_code = IntCode(text_input)
10+
11+
int_code.execute()
12+
13+
14+
class IntCode:
15+
PARAMETER_COUNTS = {1: 3, 2: 3, 3: 1, 4: 1, 99: 0}
16+
17+
def __init__(self, raw_int_code):
18+
self._int_code = list(int(x) for x in raw_int_code.split(','))
19+
20+
def execute(self):
21+
i = 0
22+
while i < len(self._int_code):
23+
opcode, parameter_modes = self._get_instruction(i)
24+
25+
if opcode not in IntCode.PARAMETER_COUNTS.keys():
26+
i += 1
27+
continue
28+
29+
parameter_count = IntCode.PARAMETER_COUNTS[opcode]
30+
31+
parameter_modes = parameter_modes + [0]*(parameter_count - len(parameter_modes))
32+
parameters = self._get_parameters(i + 1, parameter_count)
33+
34+
for j in range(len(parameters)):
35+
if parameter_modes[j] == 1:
36+
# immediate mode, replace value by value index (location)
37+
parameters[j] = i + j + 1
38+
39+
if opcode == 1:
40+
self._int_code[parameters[2]] = self._int_code[parameters[0]] + self._int_code[parameters[1]]
41+
elif opcode == 2:
42+
self._int_code[parameters[2]] = self._int_code[parameters[0]] * self._int_code[parameters[1]]
43+
elif opcode == 3:
44+
self._int_code[parameters[0]] = int(input('INPUT: '))
45+
elif opcode == 4:
46+
print('OUTPUT:', self._int_code[parameters[0]])
47+
elif opcode == 99:
48+
break
49+
50+
i += parameter_count + 1
51+
52+
def _get_instruction(self, opcode_location):
53+
full_opcode = self._int_code[opcode_location]
54+
opcode = full_opcode % 100
55+
parameter_modes = [int(x) for x in str(full_opcode)[:-2][::-1]]
56+
return (opcode, parameter_modes)
57+
58+
def _get_parameters(self, location, parameter_count):
59+
return self._int_code[location:location + parameter_count]
60+
61+
62+
def get_raw_input():
63+
return open(retrieve_input_file_path(), 'r').read()
64+
65+
66+
def retrieve_input_file_path():
67+
return path.join(path.dirname(__file__), 'input.txt')
68+
69+
70+
main()

0 commit comments

Comments
 (0)