-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2-1.rb
executable file
·55 lines (44 loc) · 949 Bytes
/
2-1.rb
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
#!/usr/bin/env ruby
instructions = File.read('2.input').lines.map(&:strip)
instruction_format = /(?<inst>forward|down|up) (?<oper>[[:digit:]]+)/
class Submarine
attr_accessor :horiz_pos
attr_accessor :depth
def initialize
@horiz_pos = 0
@depth = 0
end
def forward(steps)
@horiz_pos += steps
end
def down(steps)
@depth += steps
end
def up(steps)
@depth -= steps
if @depth.negative?
print "Illegal instruction: up #{steps}"
exit
end
end
def to_s
"<#{self.class}: (#{@horiz_pos}, #{@depth})>"
end
end
sub = Submarine.new
instructions.each do |insn|
instruction_format.match(insn) do |m|
case m['inst']
when 'forward'
sub.forward(m['oper'].to_i)
when 'down'
sub.down(m['oper'].to_i)
when 'up'
sub.up(m['oper'].to_i)
else
print "Illegal instruction: #{insn}\n"
exit
end
end
end
print "#{sub.horiz_pos * sub.depth}\n"