|
| 1 | +def _parse_crates(inputs: str): |
| 2 | + def split(s: str, n=4): |
| 3 | + return [s[i : i + n][1].strip() for i in range(0, len(s), n)] |
| 4 | + |
| 5 | + crates = list(map(split, inputs.splitlines()[:-1])) |
| 6 | + crates: list[list[str]] = list(map(list, zip(*crates[::-1]))) |
| 7 | + return [list(filter(bool, x)) for x in crates] |
| 8 | + |
| 9 | + |
| 10 | +def _parse_procedure(inputs: str): |
| 11 | + def parse(moving: str): |
| 12 | + m = moving.split(' ') |
| 13 | + return list(map(int, (m[i] for i in range(1, len(m), 2)))) |
| 14 | + |
| 15 | + return list(map(parse, inputs.splitlines())) |
| 16 | + |
| 17 | + |
| 18 | +def cast_input(inputs: str): |
| 19 | + crates, procedure = inputs.split('\n' * 2) |
| 20 | + return _parse_crates(crates), _parse_procedure(procedure) |
| 21 | + |
| 22 | + |
| 23 | +def crane(crates: list[list[str]], move: int, from_: int, to: int): |
| 24 | + [crates[to - 1].append(crates[from_ - 1].pop()) for _ in range(move)] |
| 25 | + |
| 26 | + |
| 27 | +def part1(inputs: tuple[list[list[str]], list[list[int]]]): |
| 28 | + crates, procedure = inputs |
| 29 | + [crane(crates, *x) for x in procedure] |
| 30 | + return ''.join([x[-1] for x in crates]) |
| 31 | + |
| 32 | + |
| 33 | +def crane9001(crates: list[list[str]], move: int, from_: int, to: int): |
| 34 | + stack = [] |
| 35 | + [stack.append(crates[from_ - 1].pop()) for _ in range(move)] |
| 36 | + [crates[to - 1].append(stack.pop()) for _ in range(move)] |
| 37 | + |
| 38 | + |
| 39 | +def part2(inputs: tuple[list[list[str]], list[list[int]]]): |
| 40 | + crates, procedure = inputs |
| 41 | + [crane9001(crates, *x) for x in procedure] |
| 42 | + return ''.join([x[-1] for x in crates]) |
0 commit comments