@@ -22,75 +22,48 @@ def neighbours(x, y, arr)
22
22
SQUARE . map { |k , l | neighbour ( x + k , y + l , arr ) } . compact
23
23
end
24
24
25
- # stars 1
26
- class Stars1
27
- def initialize ( arr )
28
- @arr = arr
29
- @current_str = ''
30
- @neighbours = [ ]
31
- @result = 0
32
- end
25
+ # main
26
+ class Main
27
+ attr_reader :stars1
33
28
34
- def call
35
- @arr . each_with_index do |row , j |
36
- row . each_char . with_index do |state , i |
37
- update_current ( state , i , j )
38
- check_current ( row , state , i , j )
39
- end
40
- end
41
- @result
42
- end
43
-
44
- def update_current ( state , i , j )
45
- return unless state [ /\d / ]
46
-
47
- @current_str += state
48
- @neighbours += neighbours ( i , j , @arr )
49
- end
50
-
51
- def check_current ( row , state , i , _j )
52
- return unless @current_str . length . positive? && ( row [ i + 1 ] . nil? || !state [ /\d / ] )
53
-
54
- @result += @current_str . to_i if @neighbours . any? { |v | v [ :value ] [ /[^\d .]/ ] }
55
- @current_str = ''
56
- @neighbours = [ ]
57
- end
58
- end
59
-
60
- # stars 2
61
- class Stars2
62
29
def initialize ( arr )
63
30
@arr = arr
64
31
@current_str = ''
65
32
@neighbours = [ ]
33
+ @stars1 = 0
66
34
@gears = { }
67
35
end
68
36
69
37
def call
70
38
loop
71
- @gears . filter { | _ , v | v . length == 2 } . map { | _ , v | v . reduce ( & :* ) } . sum
39
+ self
72
40
end
73
41
74
42
def loop
75
43
@arr . each_with_index do |row , j |
76
44
row . each_char . with_index do |state , i |
77
- update_current ( state , i , j )
78
- check_current ( row , state , i , j )
45
+ update ( state , i , j )
46
+ checks ( row , state , i , j )
79
47
end
80
48
end
81
49
end
82
50
83
- def update_current ( state , i , j )
51
+ def stars2
52
+ @gears . filter { |_ , v | v . length == 2 } . map { |_ , v | v . reduce ( &:* ) } . sum
53
+ end
54
+
55
+ def update ( state , i , j )
84
56
return unless state [ /\d / ]
85
57
86
58
@current_str += state
87
59
@neighbours += neighbours ( i , j , @arr )
88
60
end
89
61
90
- def check_current ( row , state , i , _j )
62
+ def checks ( row , state , i , _j )
91
63
return unless @current_str . length . positive? && ( row [ i + 1 ] . nil? || !state [ /\d / ] )
92
64
93
65
update_gears
66
+ @stars1 += @current_str . to_i if @neighbours . any? { |v | v [ :value ] [ /[^\d .]/ ] }
94
67
@current_str = ''
95
68
@neighbours = [ ]
96
69
end
@@ -104,5 +77,5 @@ def update_gears
104
77
end
105
78
end
106
79
107
- puts Stars1 . new ( arr1 ) . call
108
- puts Stars2 . new ( arr1 ) . call
80
+ puts Main . new ( arr1 ) . call . stars1
81
+ puts Main . new ( arr1 ) . call . stars2
0 commit comments