-
Notifications
You must be signed in to change notification settings - Fork 0
/
day5.py
82 lines (63 loc) · 2.06 KB
/
day5.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import re
def read_from_file_5():
stacks = []
with open("inputs/input_day5.txt") as file:
crates = []
move = []
for line in file:
p = re.compile(r"\[[ \w]*\]")
result = p.findall(line)
if result is not []:
crates.append(list(map(lambda x: x[1], result)))
p = re.compile(r"\d{1,3}")
result = p.findall(line)
if result is not []:
move.append(p.findall(line))
crates = [x for x in crates if x != []]
moves = [x for x in move if x != []]
number_of_stacks = len(moves[0])
for i in range(number_of_stacks):
stacks.append([])
moves = moves[1:]
for i in range(len(crates)):
for j in range(len(crates[i])):
if crates[i][j] != " ":
stacks[j].append(crates[i][j])
return stacks, moves
def solution_1(stacks, moves):
for x in moves:
number_of_moves = int(x[0])
from_stack = int(x[1]) - 1
to_stack = int(x[2]) - 1
for i in range(number_of_moves):
crate = stacks[from_stack].pop(0)
if len(stacks[to_stack]) > 0:
stacks[to_stack].insert(0, crate)
else:
stacks[to_stack].append(crate)
result = []
for y in stacks:
if len(y) > 0:
result.append(y[0])
return "".join(result)
def solution_2(stacks, moves):
for x in moves:
number_of_moves = int(x[0])
from_stack = int(x[1]) - 1
to_stack = int(x[2]) - 1
for i in range(number_of_moves):
crate = stacks[from_stack].pop(0)
if len(stacks[to_stack]) > 0:
stacks[to_stack].insert(i, crate)
else:
stacks[to_stack].append(crate)
result = []
for y in stacks:
if len(y) > 0:
result.append(y[0])
return "".join(result)
def print_day5():
stacks, moves = read_from_file_5()
print(solution_1(stacks, moves))
stacks, moves = read_from_file_5()
print(solution_2(stacks, moves))