From ebbe992dead3deb36244d1d2f36c506ae298f76c Mon Sep 17 00:00:00 2001 From: Ariejan de Vroom Date: Sat, 7 Dec 2024 06:43:45 +0100 Subject: [PATCH] Day 7 - Puzzle 2 Ruby FTW --- lib/solutions/day_07.rb | 19 +++++++++++++------ spec/solutions/day_07_spec.rb | 2 +- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/lib/solutions/day_07.rb b/lib/solutions/day_07.rb index acc714e..d1ad1fb 100644 --- a/lib/solutions/day_07.rb +++ b/lib/solutions/day_07.rb @@ -2,20 +2,26 @@ 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 @@ -23,14 +29,15 @@ def valid? 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) diff --git a/spec/solutions/day_07_spec.rb b/spec/solutions/day_07_spec.rb index 53bb73b..f9707a5 100644 --- a/spec/solutions/day_07_spec.rb +++ b/spec/solutions/day_07_spec.rb @@ -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