66 lines
1.7 KiB
Python
66 lines
1.7 KiB
Python
import re
|
|
|
|
BUTTON_A_COST = 3
|
|
BUTTON_B_COST = 1
|
|
MAX_PRESSES = 100
|
|
|
|
with open('input.txt', 'r') as file:
|
|
data: list[str] = file.readlines()
|
|
|
|
machines = []
|
|
|
|
for i in range(0, len(data), 4):
|
|
button_a = [int(n) for n in re.findall('[0-9]+', data[i])]
|
|
button_b = [int(n) for n in re.findall('[0-9]+', data[i+1])]
|
|
prize = [int(n) for n in re.findall('[0-9]+', data[i+2])]
|
|
|
|
machines.append([button_a, button_b, prize])
|
|
|
|
# Very simple niave solution for part 1
|
|
|
|
print('<', '-' * 10, ' Part 1 ', '-' * 10, '>')
|
|
|
|
total_cost = 0
|
|
for machine in machines:
|
|
ax, ay = machine[0]
|
|
bx, by = machine[1]
|
|
x, y = machine[2]
|
|
|
|
smallest_a, smallest_b = float('inf'), float('inf')
|
|
for a in range(MAX_PRESSES):
|
|
for b in range(MAX_PRESSES):
|
|
if (a * ax) + (b * bx) == x and (a * ay) + (b * by) == y:
|
|
if a < smallest_a:
|
|
smallest_a = a
|
|
|
|
if b < smallest_b:
|
|
smallest_b = b
|
|
|
|
if smallest_a == float('inf') or smallest_b == float('inf'):
|
|
continue
|
|
|
|
cost = (smallest_a * BUTTON_A_COST) + (smallest_b * BUTTON_B_COST)
|
|
total_cost += cost
|
|
|
|
print('Total cost: ', total_cost)
|
|
|
|
print('<', '-' * 10, ' Part 2 ', '-' * 10, '>')
|
|
|
|
# Part 2 (unfortunately lifted this formula from A.P. (https://github.com/CodingAP) )
|
|
|
|
total_cost = 0
|
|
for machine in machines:
|
|
ax, ay = machine[0]
|
|
bx, by = machine[1]
|
|
x, y = [n + 10000000000000 for n in machine[2]]
|
|
|
|
b: float = ((ax * y) - (ay * x)) / ((ax * by) - (ay * bx))
|
|
a: float = (x - (bx * b)) / ax
|
|
|
|
if b.is_integer() and a.is_integer():
|
|
cost = (a * BUTTON_A_COST) + (b * BUTTON_B_COST)
|
|
total_cost += cost
|
|
|
|
print('Total cost: ', int(total_cost))
|
|
|