advent_of_code/2021/7/7.py

32 lines
738 B
Python
Raw Normal View History

2021-12-07 12:19:41 +01:00
#!/usr/bin/env python
# 2021 - Advent Of Code - 7
def parse_file(file):
2022-04-05 13:27:24 +02:00
with open(file, encoding="utf-8") as f:
2021-12-07 12:19:41 +01:00
line = f.readline()
list_state = [int(x) for x in line.split(',')]
return list_state
2021-12-12 17:23:29 +01:00
# init_state = parse_file('input_example.txt')
2021-12-07 12:19:41 +01:00
init_state = parse_file('input.txt')
nb_crabs = len(init_state)
print(f'Initial state with {nb_crabs} crabs: {init_state}')
max_h = max(init_state)
all_diff = [0] * max_h
min_fuel = max_h * nb_crabs
min_fuel_pos = 0
for m in range(max_h):
list_diff = [abs(m-x) for x in init_state]
2021-12-12 17:23:29 +01:00
if sum(list_diff) < min_fuel:
2021-12-07 12:19:41 +01:00
min_fuel = sum(list_diff)
min_fuel_pos = m
all_diff[m] = list_diff
print(f'min fuel {min_fuel} for position {min_fuel_pos}')