Skip to content

Commit 8bf1f18

Browse files
committed
day 7, parse once, highlight what's diff in parts
1 parent 8b887ad commit 8bf1f18

File tree

1 file changed

+32
-26
lines changed

1 file changed

+32
-26
lines changed

2024/ruby/day07.rb

Lines changed: 32 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,31 @@
11
require_relative 'day'
22

33
class Day07 < Day # >
4+
def initialize(*args)
5+
super
6+
@equations =
7+
input
8+
.split("\n")
9+
.map { |line| line.scan(/\d+/).map(&:to_i) }
10+
.map { |nums| [ nums[0] , nums[1..-1] ] }
11+
end
412

513
# @example
614
# day.part1 #=> 3749
715
def part1
8-
input
9-
.split("\n")
10-
.map { |line| line.scan(/\d+/).map(&:to_i) }
11-
.map { |nums| [ nums[0] , nums[1..-1] ] }
16+
operators = [:+, :*]
17+
@equations
1218
.select { |test_value, operands|
13-
operator_combos = [:+, :*].repeated_permutation(operands.length - 1)
14-
operator_combos.find { |combo|
15-
test_value ==
16-
combo
17-
.each_with_index
18-
.reduce(operands[0]) { |result, (op, idx)|
19-
result = [ result, operands[idx+1] ].reduce(op)
20-
}
21-
}
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+
}
2229
}
2330
.map { |test_value, _| test_value }
2431
.reduce(&:+)
@@ -27,20 +34,19 @@ def part1
2734
# @example
2835
# day.part2 #=> 11387
2936
def part2
30-
input
31-
.split("\n")
32-
.map { |line| line.scan(/\d+/).map(&:to_i) }
33-
.map { |nums| [ nums[0] , nums[1..-1] ] }
37+
operators = [:+, :*, :concat]
38+
@equations
3439
.select { |test_value, operands|
35-
operator_combos = [:+, :*, :concat].repeated_permutation(operands.length - 1)
36-
operator_combos.find { |combo|
37-
test_value ==
38-
combo
39-
.each_with_index
40-
.reduce(operands[0]) { |result, (op, idx)|
41-
result = [ result, operands[idx+1] ].reduce(op)
42-
}
43-
}
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+
}
4450
}
4551
.map { |test_value, _| test_value }
4652
.reduce(&:+)

0 commit comments

Comments
 (0)