File tree Expand file tree Collapse file tree 2 files changed +14
-7
lines changed
Expand file tree Collapse file tree 2 files changed +14
-7
lines changed Original file line number Diff line number Diff line change @@ -2,35 +2,42 @@ class Day07
22 attr_accessor :equations
33
44 def part_one ( input )
5- @equations = input . split ( "\n " ) . map { |l | Equation . new ( l ) }
5+ @equations = input . split ( "\n " ) . map { |l | Equation . new ( l , %i[ + * ] ) }
66 @equations . select { |e | e . valid? } . map ( &:result ) . sum
77 end
88
99 def part_two ( input )
10- 0
10+ @equations = input . split ( "\n " ) . map { |l | Equation . new ( l , %i[ + * pipes ] ) }
11+ @equations . select { |e | e . valid? } . map ( &:result ) . sum
12+ end
13+ end
14+
15+ class Numeric
16+ # Monkey patching to add a pipe method to numbers
17+ def pipes ( other )
18+ ( to_s + other . to_s ) . to_i
1119 end
1220end
1321
1422class Equation
1523 attr_accessor :result , :inputs
1624
17- OPERATORS = %i[ + * ]
18-
1925 def valid?
2026 try_combinations ( @inputs [ 0 ] , 1 )
2127 end
2228
2329 def try_combinations ( total , idx )
2430 return total == @result if idx == @inputs . size
2531
26- OPERATORS . each do |op |
32+ @operators . each do |op |
2733 new_value = total . send ( op , @inputs [ idx ] )
2834 return true if try_combinations ( new_value , idx + 1 )
2935 end
3036 false
3137 end
3238
33- def initialize ( input )
39+ def initialize ( input , operators )
40+ @operators = operators
3441 parts = input . split ( ':' )
3542 @result = parts [ 0 ] . to_i
3643 @inputs = parts [ 1 ] . split ( ' ' ) . map ( &:to_i )
Original file line number Diff line number Diff line change 1212
1313 describe '#part_two' do
1414 it 'calculates the correct solutions for part two' do
15- expect ( subject . part_two ( input ) ) . to eq ( 0 )
15+ expect ( subject . part_two ( input ) ) . to eq ( 11_387 )
1616 end
1717 end
1818end
You canβt perform that action at this time.
0 commit comments