2022 day 5
This commit is contained in:
51
2022/05/part2
Executable file
51
2022/05/part2
Executable file
@@ -0,0 +1,51 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
import re
|
||||
|
||||
crates = []
|
||||
|
||||
def process_crates(spec):
|
||||
for i in range(0, len(spec), 4):
|
||||
pos = i // 4
|
||||
if len(crates) < pos + 1:
|
||||
crates.append([])
|
||||
|
||||
if spec[i] != '[':
|
||||
continue
|
||||
|
||||
crates[pos].append(spec[i+1])
|
||||
|
||||
def process_instruction(spec):
|
||||
m = re.search('^move (\d+) from (\d+) to (\d+)$', spec)
|
||||
count = int(m.group(1))
|
||||
src = int(m.group(2)) - 1
|
||||
dst = int(m.group(3)) - 1
|
||||
|
||||
items = []
|
||||
for i in range(0, count):
|
||||
items.append(crates[src].pop())
|
||||
items.reverse()
|
||||
crates[dst] = crates[dst] + items
|
||||
|
||||
with open('input') as f:
|
||||
# Read the diagram + separating line
|
||||
for line in f:
|
||||
if line[0] == ' ':
|
||||
continue
|
||||
if line == "\n":
|
||||
break
|
||||
process_crates(line.rstrip())
|
||||
|
||||
# We filled the lines upside down, so flip them
|
||||
for pos in crates:
|
||||
pos.reverse()
|
||||
|
||||
for line in f:
|
||||
process_instruction(line.rstrip())
|
||||
|
||||
out = ""
|
||||
for pos in crates:
|
||||
out = out + pos[-1]
|
||||
|
||||
print(out)
|
||||
|
Reference in New Issue
Block a user