diff --git a/05/crates.py b/05/crates.py new file mode 100644 index 0000000..d6cfe79 --- /dev/null +++ b/05/crates.py @@ -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)) + diff --git a/05/example b/05/example new file mode 100644 index 0000000..84933bb --- /dev/null +++ b/05/example @@ -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