Skip to content

Instantly share code, notes, and snippets.

@leeacto
Created December 7, 2021 14:00
Show Gist options
  • Save leeacto/3b18e5b876774a27180f670f0879abf0 to your computer and use it in GitHub Desktop.
Save leeacto/3b18e5b876774a27180f670f0879abf0 to your computer and use it in GitHub Desktop.
AOC Day 7 part 2
filename = '7.csv'
with open(filename, 'r') as f:
for line in f:
positions = map(int, line.split(','))
def build_costs(max_num):
costs = {}
for i in range(max_num):
if i == 0:
costs[0] = 0
else:
costs[i] = costs[i - 1] + i
return costs
def calc_fuel(val):
req_fuel = 0
for p in positions:
req_fuel += costs[abs(p - val)]
return req_fuel
costs = build_costs(max(positions) + 1)
avg = int(round(sum(positions) / float(len(positions))))
curr_fuel = calc_fuel(avg)
base = avg
min_found = False
while not min_found:
lt_fuel = calc_fuel(avg - 1)
rt_fuel = calc_fuel(avg + 1)
if rt_fuel < curr_fuel:
if lt_fuel < rt_fuel:
curr_fuel, base = lt_fuel, base - 1
else:
curr_fuel, base = rt_fuel, base + 1
elif lt_fuel < curr_fuel:
curr_fuel, base = lt_fuel, base - 1
else:
min_found = True
print(curr_fuel)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment