File tree Expand file tree Collapse file tree 4 files changed +58
-1
lines changed
Expand file tree Collapse file tree 4 files changed +58
-1
lines changed Original file line number Diff line number Diff line change 33
44| Year | Stars |
55| ------| ------:|
6- | 2021 | 12 ⭐ |
6+ | 2021 | 14 ⭐ |
77| 2020 | 50 ⭐ |
88| 2019 | 44 ⭐ |
99| 2018 | 8 ⭐ |
Original file line number Diff line number Diff line change 1+ 16,1,2,0,4,2,7,1,2,14
Original file line number Diff line number Diff line change 1+ # https://adventofcode.com/2021/day/7
2+
3+
4+ from math import inf
5+ from statistics import median
6+
7+
8+ SAMPLE_PATH = "../../input/2021-07-sample.txt"
9+ INPUT_PATH = "../../input/2021-07-input.txt"
10+
11+
12+ def get_data (filename ):
13+ with open (filename ) as file :
14+ return [int (x ) for x in file .read ().split ("," )]
15+
16+
17+ def part_1 (positions ):
18+ best_position = int (median (positions ))
19+ return sum (abs (pos - best_position ) for pos in positions )
20+
21+
22+ def calc_fuel (steps ):
23+ return steps * (steps + 1 ) // 2
24+
25+
26+ def part_2 (positions ):
27+ """Just a simple search from min to max position. I could improve it but this one
28+ is fast enough. There should be only one minimum so no need to search the other
29+ positions after it is found.
30+ """
31+ min_fuel = inf
32+ for best_pos in range (min (positions ), max (positions ) + 1 ):
33+ fuel = sum (calc_fuel (abs (pos - best_pos )) for pos in positions )
34+ if fuel >= min_fuel :
35+ return min_fuel
36+ min_fuel = fuel
37+
38+
39+ if __name__ == "__main__" :
40+ sample_data = get_data (SAMPLE_PATH )
41+ assert part_1 (sample_data ) == 37
42+ assert part_2 (sample_data ) == 168
43+
44+ challenge_data = get_data (INPUT_PATH )
45+ print (part_1 (challenge_data )) # 352331
46+ print (part_2 (challenge_data )) # 99266250
Original file line number Diff line number Diff line change 66import day04
77import day05
88import day06
9+ import day07
910
1011
1112class Test2021 (unittest .TestCase ):
@@ -58,6 +59,15 @@ def test_06(self):
5859 self .assertEqual (challenge_part_1 , 372300 )
5960 self .assertEqual (challenge_part_2 , 1675781200288 )
6061
62+ def test_07 (self ):
63+ sample_data = day07 .get_data (day07 .SAMPLE_PATH )
64+ self .assertEqual (day07 .part_1 (sample_data ), 37 )
65+ self .assertEqual (day07 .part_2 (sample_data ), 168 )
66+
67+ challenge_data = day07 .get_data (day07 .INPUT_PATH )
68+ self .assertEqual (day07 .part_1 (challenge_data ), 352331 )
69+ self .assertEqual (day07 .part_2 (challenge_data ), 99266250 )
70+
6171
6272if __name__ == "__main__" :
6373 unittest .main ()
You can’t perform that action at this time.
0 commit comments