-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1_b.rb
92 lines (75 loc) · 1.91 KB
/
1_b.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
91
92
# typed: true
# frozen_string_literal: true
class Level
class << self
def run(input)
sonar = Sonar.from_raw(input)
puts "Depth Increases: #{sonar.count_depth_increases}"
puts "Window Increases: #{sonar.count_window_increases}"
end
end
end
class Sonar
extend T::Sig
attr_accessor :measurements, :measurement_windows
class << self
extend T::Sig
sig { params(data_string: String).returns(T::Array[Integer]) }
def parse_raw_measurements(data_string)
data_string.split.map(&:to_i)
end
sig { params(depths: T::Array[Integer]).returns(Sonar) }
def from_measurements(depths)
sonar = new
sonar.measurements = depths.map do |depth|
Measurement.new(depth)
end
sonar.generate_measurement_windows!
sonar
end
sig { params(data_string: String).returns(Sonar) }
def from_raw(data_string)
from_measurements(parse_raw_measurements(data_string))
end
end
sig { void }
def generate_measurement_windows!
@measurement_windows = measurements.each_cons(3).map do |tuple|
MeasurementWindow.new(tuple)
end
end
sig { returns(Integer) }
def count_depth_increases
measurements.each_cons(2).inject(0) do |acc, (a, b)|
acc += 1 if a.depth < b.depth
acc
end
end
sig { returns(Integer) }
def count_window_increases
measurement_windows.each_cons(2).inject(0) do |acc, (a, b)|
acc += 1 if a.total_depth < b.total_depth
acc
end
end
end
class MeasurementWindow
extend T::Sig
attr_accessor :measurements
sig { params(measurements: T::Array[Measurement]).void }
def initialize(measurements)
@measurements = measurements
end
sig { returns(Integer) }
def total_depth
measurements.map(&:depth).sum
end
end
class Measurement
extend T::Sig
attr_accessor :depth
sig { params(depth: Integer).void }
def initialize(depth)
@depth = depth
end
end