Skip to content

Commit

Permalink
Day 7 - Puzzle 2
Browse files Browse the repository at this point in the history
Ruby FTW
  • Loading branch information
ariejan committed Dec 7, 2024
1 parent 5537431 commit ebbe992
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 7 deletions.
19 changes: 13 additions & 6 deletions lib/solutions/day_07.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,35 +2,42 @@ class Day07
attr_accessor :equations

def part_one(input)
@equations = input.split("\n").map { |l| Equation.new(l) }
@equations = input.split("\n").map { |l| Equation.new(l, %i[+ *]) }
@equations.select { |e| e.valid? }.map(&:result).sum
end

def part_two(input)
0
@equations = input.split("\n").map { |l| Equation.new(l, %i[+ * pipes]) }
@equations.select { |e| e.valid? }.map(&:result).sum
end
end

class Numeric
# Monkey patching to add a pipe method to numbers
def pipes(other)
(to_s + other.to_s).to_i
end
end

class Equation
attr_accessor :result, :inputs

OPERATORS = %i[+ *]

def valid?
try_combinations(@inputs[0], 1)
end

def try_combinations(total, idx)
return total == @result if idx == @inputs.size

OPERATORS.each do |op|
@operators.each do |op|
new_value = total.send(op, @inputs[idx])
return true if try_combinations(new_value, idx + 1)
end
false
end

def initialize(input)
def initialize(input, operators)
@operators = operators
parts = input.split(':')
@result = parts[0].to_i
@inputs = parts[1].split(' ').map(&:to_i)
Expand Down
2 changes: 1 addition & 1 deletion spec/solutions/day_07_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

describe '#part_two' do
it 'calculates the correct solutions for part two' do
expect(subject.part_two(input)).to eq(0)
expect(subject.part_two(input)).to eq(11_387)
end
end
end

0 comments on commit ebbe992

Please sign in to comment.