-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday5.rb
More file actions
98 lines (78 loc) · 2.3 KB
/
day5.rb
File metadata and controls
98 lines (78 loc) · 2.3 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
class Ship
def initialize(input)
@stacks = initialize_stacks(input)
@stacks = make_moves(input, @stacks)
@top_containers = tops(@stacks)
end
attr_reader :top_containers, :stacks
def initialize_stacks(input)
stacks = Array.new(9){Array.new}
i = 0
File.foreach(input) do |line|
if line[0] == "["
puts "#{i}-------"
puts line
#Still in the initializing phase
stacks[0][i] = line[1]
stacks[1][i] = line[5]
stacks[2][i] = line[9]
stacks[3][i] = line[13]
stacks[4][i] = line[17]
stacks[5][i] = line[21]
stacks[6][i] = line[25]
stacks[7][i] = line[29]
stacks[8][i] = line[33]
end
i += 1
end
#delete empty slots
stacks.each do |stack|
stack.delete(' ')
end
# reverse stack
stacks.each do |stack|
stack.replace(stack.reverse)
end
return stacks.clone
end
def make_moves(input, stacks)
File.foreach(input) do |line|
if line[0] == "m"
# puts line
move_number = /^move (\d+)/.match(line).to_s.delete("move ").to_i
from_stack = /from (\d+)/.match(line).to_s.delete("from ").to_i
to_stack = /to (\d+)/.match(line).to_s.delete("to ").to_i
from_stack -= 1
to_stack -= 1
puts "move #{move_number}"
puts "from #{from_stack}"
puts "to #{to_stack}"
make_move(stacks, move_number, from_stack, to_stack)
end
end
return stacks.clone
end
def make_move(stacks, number, from, to)
number.times do |num|
stacks[to].push(stacks[from].pop)
end
end
def tops(stacks)
top = ""
stacks.each do |stack|
top << stack.last
end
return top
end
end
ship = Ship.new("day5i.txt")
ship.stacks.each do |stack|
p stack
puts "---_--_--_--_-__-_"
end
puts "+++++++++++++++++++++++++"
ship.stacks.each do |stack|
p stack.pop
puts "---_--_--_--_-__-_"
end
puts ship.top_containers