Add day 5 solution

This commit is contained in:
Michal Kunc 2022-12-05 10:15:22 +01:00
parent 2aa9a6fcdc
commit f485dad5e9
2 changed files with 83 additions and 0 deletions

74
05/crates.py Normal file
View File

@ -0,0 +1,74 @@
import fileinput
from typing import Iterable,List
class Puzzle:
stacks: List[List[str]]
instructions: List[str]
def __init__(self):
self.stacks = []
self.instructions = []
def parse(lines: Iterable[str]) -> Puzzle:
count = None
stage = 0
puzzle = Puzzle()
for line in map(lambda x: x.replace('\n',''), lines):
if count is None: # Figure out how many stacks
count = len(line)//4 + 1
for _ in range(count):
puzzle.stacks.append([])
#puzzle.stacks = [[]]*count
if stage == 0:
if '[' not in line:
stage = 1
continue
chars = [line[i*4+1:i*4+2] for i in range(count)]
for idx in range(count):
if chars[idx] != ' ':
puzzle.stacks[idx].append(chars[idx])
elif stage == 1:
stage = 2
elif stage == 2:
puzzle.instructions.append(line)
for idx in range(count):
puzzle.stacks[idx] = puzzle.stacks[idx][::-1]
return puzzle
def solve(p: Puzzle) -> str:
for ins in p.instructions:
_, cnt, _, fr, _, to = ins.split(' ')
cnt = int(cnt)
fr = int(fr)
to = int(to)
for _ in range(cnt):
p.stacks[to-1].append(p.stacks[fr-1].pop())
out = ''
for st in p.stacks:
out += st[-1]
return out
def solveb(p: Puzzle) -> str:
for ins in p.instructions:
_, cnt, _, fr, _, to = ins.split(' ')
cnt = int(cnt)
fr = int(fr)
to = int(to)
load = []
for _ in range(cnt):
load.append(p.stacks[fr-1].pop())
load = load[::-1]
p.stacks[to-1] += load
out = ''
for st in p.stacks:
out += st[-1]
return out
if __name__ == "__main__":
puzzle = parse(fileinput.input())
print(solve(puzzle))
puzzle = parse(fileinput.input())
print(solveb(puzzle))

9
05/example Normal file
View File

@ -0,0 +1,9 @@
[D]
[N] [C]
[Z] [M] [P]
1 2 3
move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2