-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2_a.rb
90 lines (73 loc) · 1.87 KB
/
2_a.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
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
# typed: true
# frozen_string_literal: true
class Level
class << self
def run(input)
instructions = Instruction.parse_raw(input)
puts "Multiplied Position & Depth: #{Submarine.new.follow_instructions(instructions).dead_reckoning}"
end
end
end
class Instruction
extend T::Sig
sig { returns(Symbol) }
attr_accessor :direction
sig { returns(Integer) }
attr_accessor :units
class << self
extend T::Sig
sig { params(data_string: String).returns(T::Array[Instruction]) }
def parse_raw(data_string)
data_string.split("\n").map(&:split).map do |(raw_direction, raw_units)|
Instruction.new(T.must(raw_direction).to_sym, raw_units.to_i)
end
end
end
sig { params(direction: Symbol, units: Integer).void }
def initialize(direction, units)
@direction = direction
@units = units
end
end
class Submarine
extend T::Sig
AXIS = {
forward: :position,
up: :depth,
down: :depth
}.freeze
DIRECTIONS = {
forward: 1,
up: -1,
down: 1
}.freeze
sig { returns(Integer) }
attr_accessor :depth
sig { returns(Integer) }
attr_accessor :position
sig { params(depth: Integer, position: Integer).void }
def initialize(depth: 0, position: 0)
@depth = depth
@position = position
end
sig { params(instruction: Instruction).returns(T.self_type) }
def follow_instruction(instruction)
magnitude = DIRECTIONS[instruction.direction] * instruction.units
case AXIS[instruction.direction]
when :position
@position += magnitude
else # depth
@depth += magnitude
end
self
end
sig { params(instructions: T::Array[Instruction]).returns(T.self_type) }
def follow_instructions(instructions)
instructions.each { |instruction| follow_instruction(instruction) }
self
end
sig { returns(Integer) }
def dead_reckoning
@depth * @position
end
end