@@ -6,52 +6,58 @@ def initialize(*args)
6
6
@equations =
7
7
input
8
8
. split ( "\n " )
9
- . map { |line | line . scan ( /\d +/ ) . map ( &:to_i ) }
10
- . map { |nums | [ nums [ 0 ] , nums [ 1 ..-1 ] ] }
9
+ . map { |line | CalibrationEquation . new ( line ) }
11
10
end
12
11
13
12
# @example
14
13
# day.part1 #=> 3749
15
14
def part1
16
- operators = [ :+ , :* ]
17
15
@equations
18
- . select { |test_value , operands |
19
- operators
20
- . repeated_permutation ( operands . length - 1 )
21
- . find { |combo |
22
- test_value ==
23
- combo
24
- . each_with_index
25
- . reduce ( operands [ 0 ] ) { |result , ( op , idx ) |
26
- result = [ result , operands [ idx +1 ] ] . reduce ( op )
27
- }
28
- }
29
- }
30
- . map { |test_value , _ | test_value }
16
+ . select { _1 . possibly_true ( [ :+ , :* ] ) }
17
+ . map ( &:test_value )
31
18
. reduce ( &:+ )
32
19
end
33
20
34
21
# @example
35
22
# day.part2 #=> 11387
36
23
def part2
37
- operators = [ :+ , :* , :concat ]
38
24
@equations
39
- . select { |test_value , operands |
40
- operators
41
- . repeated_permutation ( operands . length - 1 )
42
- . find { |combo |
43
- test_value ==
44
- combo
45
- . each_with_index
46
- . reduce ( operands [ 0 ] ) { |result , ( op , idx ) |
47
- result = [ result , operands [ idx +1 ] ] . reduce ( op )
48
- }
49
- }
50
- }
51
- . map { |test_value , _ | test_value }
25
+ . select { _1 . possibly_true ( [ :+ , :* , :concat ] ) }
26
+ . map ( &:test_value )
52
27
. reduce ( &:+ )
53
28
end
54
29
30
+ class CalibrationEquation
31
+ attr_reader :test_value , :operands
32
+
33
+ # @example
34
+ # e = new("190: 10 19")
35
+ # e.test_value #=> 190
36
+ # e.operands #=> [10, 19]
37
+ def initialize ( input )
38
+ @test_value , *@operands =
39
+ input
40
+ . scan ( /\d +/ )
41
+ . map ( &:to_i )
42
+ end
43
+
44
+ def possibly_true ( operators )
45
+ operators
46
+ . repeated_permutation ( operands . length - 1 )
47
+ . find { |combo |
48
+ test_value == eval_with_operators ( combo )
49
+ }
50
+ end
51
+
52
+ def eval_with_operators ( operator_combo )
53
+ operator_combo
54
+ . each_with_index
55
+ . reduce ( operands [ 0 ] ) { |result , ( op , idx ) |
56
+ result = [ result , operands [ idx +1 ] ] . reduce ( op )
57
+ }
58
+ end
59
+ end
60
+
55
61
EXAMPLE_INPUT = File . read ( "../inputs/day07-example-input.txt" )
56
62
end
57
63
0 commit comments