Advent of Code 2022 - 5

Day 5: Supply Stacks

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

第一部分跟第二部份根本一樣,所以寫了一個函數給他們用。

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
def rearrange(model_9001):
stacks = {
1: ['F','T','N','Z','M','G','H','J'],
2: ['J','W','V'],
3: ['H','T','B','J','L','V','G'],
4: ['L','V','D','C','N','J','P','B'],
5: ['G','R','P','M','S','W','F'],
6: ['M','V','N','B','F','C','H','G'],
7: ['R','M','G','H','D'],
8: ['D','Z','V','M','N','H'],
9: ['H','F','N','G'],
}

with open('05.txt', 'r') as fp:
steps = [[int(x) for x in line.split() if x.isdigit()] for line in fp.read().split('\n')]

for step in steps:
n = step[0]
src = step[1]
dst = step[2]
crates = [stacks[src].pop(0) for _ in range(n)]
if not model_9001:
crates.reverse()
stacks[dst] = crates + stacks[dst]

return ''.join([stacks[i][0] for i in range(1, 10)])

Part One

1
print(rearrange(False))

Answer: TDCHVHJTG

Part Two

1
print(rearrange(True))

Answer: NGCMPJLHV