1
1
require_relative 'day'
2
2
3
3
class Day07 < Day # >
4
+ def initialize ( *args )
5
+ super
6
+ @equations =
7
+ input
8
+ . split ( "\n " )
9
+ . map { |line | line . scan ( /\d +/ ) . map ( &:to_i ) }
10
+ . map { |nums | [ nums [ 0 ] , nums [ 1 ..-1 ] ] }
11
+ end
4
12
5
13
# @example
6
14
# day.part1 #=> 3749
7
15
def part1
8
- input
9
- . split ( "\n " )
10
- . map { |line | line . scan ( /\d +/ ) . map ( &:to_i ) }
11
- . map { |nums | [ nums [ 0 ] , nums [ 1 ..-1 ] ] }
16
+ operators = [ :+ , :* ]
17
+ @equations
12
18
. select { |test_value , operands |
13
- operator_combos = [ :+ , :* ] . repeated_permutation ( operands . length - 1 )
14
- operator_combos . find { |combo |
15
- test_value ==
16
- combo
17
- . each_with_index
18
- . reduce ( operands [ 0 ] ) { |result , ( op , idx ) |
19
- result = [ result , operands [ idx +1 ] ] . reduce ( op )
20
- }
21
- }
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
+ }
22
29
}
23
30
. map { |test_value , _ | test_value }
24
31
. reduce ( &:+ )
@@ -27,20 +34,19 @@ def part1
27
34
# @example
28
35
# day.part2 #=> 11387
29
36
def part2
30
- input
31
- . split ( "\n " )
32
- . map { |line | line . scan ( /\d +/ ) . map ( &:to_i ) }
33
- . map { |nums | [ nums [ 0 ] , nums [ 1 ..-1 ] ] }
37
+ operators = [ :+ , :* , :concat ]
38
+ @equations
34
39
. select { |test_value , operands |
35
- operator_combos = [ :+ , :* , :concat ] . repeated_permutation ( operands . length - 1 )
36
- operator_combos . find { |combo |
37
- test_value ==
38
- combo
39
- . each_with_index
40
- . reduce ( operands [ 0 ] ) { |result , ( op , idx ) |
41
- result = [ result , operands [ idx +1 ] ] . reduce ( op )
42
- }
43
- }
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
+ }
44
50
}
45
51
. map { |test_value , _ | test_value }
46
52
. reduce ( &:+ )
0 commit comments