This repository has been archived by the owner on Oct 18, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday07_test.py
67 lines (40 loc) · 1.92 KB
/
day07_test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# https://adventofcode.com/2021/day/7
from statistics import median
with open("day07.input.txt", "r") as f:
input = f.read()
example_input = """16,1,2,0,4,2,7,1,2,14"""
def parse_input(raw_input):
return [int(raw_crab) for raw_crab in raw_input.split(",")]
def test_parse_input():
assert parse_input(example_input) == [16, 1, 2, 0, 4, 2, 7, 1, 2, 14]
def calculate_cheapest_horizontal_position(crab_horizontal_positions):
return median(crab_horizontal_positions)
def test_calculate_cheapest_horizontal_position():
assert calculate_cheapest_horizontal_position(parse_input(example_input)) == 2
def calculate_minimal_fuel(crab_horizontal_positions):
final_position = calculate_cheapest_horizontal_position(crab_horizontal_positions)
total_fuel = 0
for horizontal_position in crab_horizontal_positions:
total_fuel += abs(horizontal_position - final_position)
return int(total_fuel)
def test_calculate_minimal_fuel():
assert calculate_minimal_fuel(parse_input(example_input)) == 37
# Solve AoC 7 part 1
assert calculate_minimal_fuel(parse_input(input)) == 343605
def calculate_fuel_fixed(crab_horizontal_positions, final_position):
total_fuel = 0
for horizontal_position in crab_horizontal_positions:
distance = abs(horizontal_position - final_position)
total_fuel += distance * (distance + 1) // 2
return total_fuel
def calculate_minimal_fuel_fixed(crab_horizontal_positions):
max_position = max(crab_horizontal_positions)
minimal_fuel = float("inf")
for position in range(max_position):
fuel = calculate_fuel_fixed(crab_horizontal_positions, position)
minimal_fuel = min(minimal_fuel, fuel)
return minimal_fuel
def test_calculate_minimal_fuel_fixed():
assert calculate_minimal_fuel_fixed(parse_input(example_input)) == 168
# Solve AoC 7 part 2
assert calculate_minimal_fuel_fixed(parse_input(input)) == 96744904