Advent of Code 2022 - 1

感謝 idoleat 推薦這個神奇東西,每天都在家也是夠無聊的,有點新鮮的事情做也不錯,剛好也很久沒在這邊寫東西了,就簡單紀錄一下每天解 Advent of Code 的 code 吧,主要應該都會用 Python,寫起來比較舒服,複雜度什麼的就不要太挑剔了,反正就是寫開心的。

Day 1: Calorie Counting

https://adventofcode.com/2022/day/1

Part One

就找最大的而已,應該 O(n) 走一遍就好了。

1
2
3
4
5
6
7
8
9
10
11
max_cal = 0
cur_cal = 0
with open('01.txt', 'r') as fp:
for line in fp:
line = line.strip()
if len(line):
cur_cal += int(line)
else:
max_cal = max(max_cal, cur_cal)
cur_cal = 0
print(max_cal)

Answer: 70720

Part Two

取前 k 大的或前 k 小的這種用 heap 應該就可以了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import heapq

pq = []
cur_cal = 0
with open('01.txt', 'r') as fp:
for line in fp:
line = line.strip()
if len(line):
cur_cal += int(line)
else:
heapq.heappush(pq, -cur_cal)
cur_cal = 0
total = 0
for i in range(3):
total -= heapq.heappop(pq)
print(total)

Answer: 207148