Skip to content

Commit 14256da

Browse files
committed
day 7, mmm objects
Still slow (now 22s), but duplication removed
1 parent 8bf1f18 commit 14256da

File tree

1 file changed

+36
-30
lines changed

1 file changed

+36
-30
lines changed

2024/ruby/day07.rb

Lines changed: 36 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -6,52 +6,58 @@ def initialize(*args)
66
@equations =
77
input
88
.split("\n")
9-
.map { |line| line.scan(/\d+/).map(&:to_i) }
10-
.map { |nums| [ nums[0] , nums[1..-1] ] }
9+
.map { |line| CalibrationEquation.new(line) }
1110
end
1211

1312
# @example
1413
# day.part1 #=> 3749
1514
def part1
16-
operators = [:+, :*]
1715
@equations
18-
.select { |test_value, operands|
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-
}
29-
}
30-
.map { |test_value, _| test_value }
16+
.select{ _1.possibly_true([:+, :*]) }
17+
.map(&:test_value)
3118
.reduce(&:+)
3219
end
3320

3421
# @example
3522
# day.part2 #=> 11387
3623
def part2
37-
operators = [:+, :*, :concat]
3824
@equations
39-
.select { |test_value, operands|
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-
}
50-
}
51-
.map { |test_value, _| test_value }
25+
.select{ _1.possibly_true([:+, :*, :concat]) }
26+
.map(&:test_value)
5227
.reduce(&:+)
5328
end
5429

30+
class CalibrationEquation
31+
attr_reader :test_value, :operands
32+
33+
# @example
34+
# e = new("190: 10 19")
35+
# e.test_value #=> 190
36+
# e.operands #=> [10, 19]
37+
def initialize(input)
38+
@test_value, *@operands =
39+
input
40+
.scan(/\d+/)
41+
.map(&:to_i)
42+
end
43+
44+
def possibly_true(operators)
45+
operators
46+
.repeated_permutation(operands.length - 1)
47+
.find { |combo|
48+
test_value == eval_with_operators(combo)
49+
}
50+
end
51+
52+
def eval_with_operators(operator_combo)
53+
operator_combo
54+
.each_with_index
55+
.reduce(operands[0]) { |result, (op, idx)|
56+
result = [ result, operands[idx+1] ].reduce(op)
57+
}
58+
end
59+
end
60+
5561
EXAMPLE_INPUT = File.read("../inputs/day07-example-input.txt")
5662
end
5763

0 commit comments

Comments
 (0)