advent_of_code/2022/5/5.py

57 lines
1.4 KiB
Python
Raw Permalink Normal View History

2022-12-05 11:15:29 +01:00
#!/usr/bin/env python
# 2022 - Advent Of Code 5
# file = 'input_example.txt'
file = 'input.txt'
parsed_stack = []
num_crates = 0 # num crates by line
moves = []
with open(file, encoding="utf-8") as f:
while True:
line = f.readline()
if line[1] == '1':
break
num_crates = int(len(line)/4)
crates = []
for crate in range(0, num_crates):
letter = line[1 + crate * 4]
crates.append(letter)
parsed_stack.append(crates)
line = f.readline()
for line in f.readlines():
split = line.strip().split(' ')
moves.append((int(split[1]), int(split[3]), int(split[5])))
print(f'moves: {moves}')
print(f'num crates by line: {num_crates}')
# print(parsed_stack)
print(f'init stack height: {len(parsed_stack)}')
stacks = []
for s in range(0, num_crates):
stack = []
for h in range(len(parsed_stack)-1, -1, -1):
if parsed_stack[h][s] == ' ':
break
stack.append(parsed_stack[h][s])
stacks.append(stack)
for s in stacks:
print(s)
for move in moves:
# print(move)
num_move = move[0]
from_stack = stacks[move[1] - 1]
dest_stack = stacks[move[2] - 1]
for n in range(0, num_move):
popped = from_stack.pop()
print(f'move {popped} from {move[1]} to {move[2]}')
dest_stack.append(popped)
# dest_stack.append(from_stack.pop())
print(stacks)
result = ''.join([s[-1] for s in stacks])
print(result)