Days 1 and 2 parts 2

This commit is contained in:
Dece 2019-12-15 15:55:57 +01:00
parent 2d9bba8a15
commit aeaec72182
2 changed files with 38 additions and 28 deletions

View file

@ -1,11 +1,17 @@
def get_fuel(mass):
return mass // 3 - 2
return max(0, mass // 3 - 2)
needed_fuel = 0
with open("day1.txt", "rt") as input_file:
for line in input_file.readlines():
mass = int(line.strip())
fuel = get_fuel(mass)
# Part 2. Comment from line 11 to 14 included for part 1.
fuel_for_fuel = fuel
while fuel_for_fuel > 0:
fuel_for_fuel = get_fuel(fuel_for_fuel)
fuel += fuel_for_fuel
needed_fuel += fuel
print(needed_fuel)

View file

@ -1,31 +1,35 @@
import sys
import itertools
CODES = None
from intcode import Intcode
def main():
with open("day2.txt", "rt") as input_file:
CODES = [int(i) for i in input_file.read().strip().split(",")]
text = input_file.readlines()[0].rstrip()
codes = Intcode.parse_input(text)
CODES[1] = 12
CODES[2] = 2
# Part 1
codes_p1 = codes.copy()
codes_p1[1] = 12
codes_p1[2] = 2
ic = Intcode(codes_p1)
ic.run()
print(f"Value at pos 0: {ic._memory[0]}.")
ip = 0
while True:
code = CODES[ip]
if code == 1:
operand1_pos = CODES[ip + 1]
operand2_pos = CODES[ip + 2]
output_pos = CODES[ip + 3]
CODES[output_pos] = CODES[operand1_pos] + CODES[operand2_pos]
ip += 4
elif code == 2:
operand1_pos = CODES[ip + 1]
operand2_pos = CODES[ip + 2]
output_pos = CODES[ip + 3]
CODES[output_pos] = CODES[operand1_pos] * CODES[operand2_pos]
ip += 4
elif code == 99:
# Part 2
noun, verb = 0, 0
for x, y in itertools.permutations(range(1, 100), 2):
codes_p2 = codes.copy()
codes_p2[1] = x
codes_p2[2] = y
ic = Intcode(codes_p2)
ic.run()
if ic._memory[0] == 19690720:
noun, verb = x, y
break
else:
print("Wrong opcode:", code)
sys.exit()
print(f"Found noun={noun} and verb={verb}.")
print(f"Answer: {100 * noun + verb}")
print("Value at pos0:", CODES[0])
if __name__ == "__main__":
main()