-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday05.py
executable file
·66 lines (49 loc) · 1.81 KB
/
day05.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
from parse import parse
from run_util import run_puzzle
def parse_input(data):
field_lines, instruction_lines = [segment.split('\n') for segment in data.split('\n\n')]
stacks = [[] for _ in range(len(field_lines[0]) // 4 + 1)]
for line in field_lines[-2::-1]:
for stack, crate in enumerate([line[char] for char in range(1, len(line), 4)]):
if crate == ' ':
continue
else:
stacks[stack].append(crate)
instructions = [
(number_of_crates, source_stack - 1, destination_stack - 1)
for number_of_crates, source_stack, destination_stack in
[
parse("move {:d} from {:d} to {:d}", line)
for line in instruction_lines
]
]
return stacks, instructions
def part_a(data):
stacks, instructions = parse_input(data)
for number_of_crates, source_stack, destination_stack in instructions:
moving_crates = [stacks[source_stack].pop() for _ in range(number_of_crates)]
stacks[destination_stack].extend(moving_crates)
solution = ''.join([stack[-1] for stack in stacks])
return solution
def part_b(data):
stacks, instructions = parse_input(data)
for number_of_crates, source_stack, destination_stack in instructions:
moving_crates = [stacks[source_stack].pop() for _ in range(number_of_crates)]
stacks[destination_stack].extend(reversed(moving_crates))
solution = ''.join([stack[-1] for stack in stacks])
return solution
def main():
examples = [
(""" [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""", "CMZ", "MCD")
]
day = int(__file__.split('/')[-1].split('.')[0][-2:])
run_puzzle(day, part_a, part_b, examples)
if __name__ == '__main__':
main()