-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2-2.rb
executable file
·58 lines (47 loc) · 1020 Bytes
/
2-2.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
56
57
58
#!/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
attr_accessor :aim
def initialize
@horiz_pos = 0
@depth = 0
@aim = 0
end
def forward(steps)
@horiz_pos += steps
@depth += @aim * steps
if @depth.negative?
print "Illegal instruction: forward #{steps}"
exit
end
end
def down(steps)
@aim += steps
end
def up(steps)
@aim -= steps
end
def to_s
"<#{self.class}: (#{@horiz_pos}, #{@depth}, #{@aim})>"
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"