Day 7 part 2
This commit is contained in:
parent
0ba84fbee5
commit
d46d11ce76
1 changed files with 36 additions and 0 deletions
36
7/7_2.py
Executable file
36
7/7_2.py
Executable file
|
@ -0,0 +1,36 @@
|
||||||
|
#!/usr/bin/env python
|
||||||
|
# 2021 - Advent Of Code - 7 part 2
|
||||||
|
|
||||||
|
def parse_file(file):
|
||||||
|
with open(file) as f:
|
||||||
|
line = f.readline()
|
||||||
|
|
||||||
|
list_state = [int(x) for x in line.split(',')]
|
||||||
|
|
||||||
|
return list_state
|
||||||
|
|
||||||
|
|
||||||
|
def sum_n(n):
|
||||||
|
return int(n*(n+1) / 2)
|
||||||
|
|
||||||
|
|
||||||
|
# init_state = parse_file('input_example.txt')
|
||||||
|
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)
|
||||||
|
print(f'maximum horizontal position is {max_h}')
|
||||||
|
all_diff = [0] * max_h
|
||||||
|
|
||||||
|
min_fuel = sum_n(max_h) * nb_crabs
|
||||||
|
min_fuel_pos = 0
|
||||||
|
for m in range(max_h):
|
||||||
|
list_diff = [sum_n(abs(m-x)) for x in init_state]
|
||||||
|
if sum(list_diff) < min_fuel:
|
||||||
|
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}')
|
Loading…
Reference in a new issue