Skip to content

Commit a13d770

Browse files
committed
Day 07, Part 2
1 parent 1ea2b26 commit a13d770

File tree

1 file changed

+7
-3
lines changed

1 file changed

+7
-3
lines changed

day_07/__main__.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,20 @@ def read_input(textio: TextIO) -> List[int]:
55
positions = [int(num) for num in textio.readlines()[0].split(',')]
66
return positions
77

8-
def cost(positions:List[int], target_position:int) -> int:
9-
return sum(abs(position-target_position) for position in positions)
8+
def cost(position: int, target_position: int) -> int:
9+
diff = abs(position-target_position)
10+
return int((diff+1)*diff/2)
11+
12+
def total_cost(positions:List[int], target_position:int) -> int:
13+
return sum(cost(position, target_position) for position in positions)
1014

1115
def find_cheapest(positions:List[int]):
1216
min_pos = min(positions)
1317
max_pos = max(positions)
1418

1519
costs = dict()
1620
for pos in range(min_pos, max_pos+1):
17-
costs[pos] = cost(positions, pos)
21+
costs[pos] = total_cost(positions, pos)
1822

1923
min_cost_pos = min(costs, key=costs.get)
2024
return min_cost_pos, costs[min_cost_pos]

0 commit comments

Comments
 (0)