Skip to content

Commit ebbe992

Browse files
committed
Day 7 - Puzzle 2
Ruby FTW
1 parent 5537431 commit ebbe992

File tree

2 files changed

+14
-7
lines changed

2 files changed

+14
-7
lines changed

β€Žlib/solutions/day_07.rbβ€Ž

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff 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
1220
end
1321

1422
class 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)

β€Žspec/solutions/day_07_spec.rbβ€Ž

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
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
1818
end

0 commit comments

Comments
Β (0)