Skip to content

Commit 23e5403

Browse files
committed
day 7, part 2
Brute force! It's slow—39s for both parts—but it works.
1 parent f94c70d commit 23e5403

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

2024/ruby/day07.rb

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,34 @@ def part1
2525
end
2626

2727
# @example
28-
# day.part2 #=> 'how are you'
28+
# day.part2 #=> 11387
2929
def part2
30+
input
31+
.split("\n")
32+
.map { |line| line.scan(/\d+/).map(&:to_i) }
33+
.map { |nums| [ nums[0] , nums[1..-1] ] }
34+
.select { |test_value, operands|
35+
operator_combos = [:+, :*, :concat].repeated_permutation(operands.length - 1)
36+
operator_combos.map { |combo|
37+
combo
38+
.each_with_index
39+
.reduce(operands[0]) { |result, (op, idx)|
40+
result = [ result, operands[idx+1] ].reduce(op)
41+
}
42+
}
43+
.any? { |result| result == test_value }
44+
}
45+
.map { |test_value, _| test_value }
46+
.reduce(&:+)
3047
end
3148

3249
EXAMPLE_INPUT = File.read("../inputs/day07-example-input.txt")
3350
end
51+
52+
class Integer
53+
# @example
54+
# 12.concat(345) #=> 12345
55+
def concat(other)
56+
"#{self}#{other}".to_i
57+
end
58+
end

0 commit comments

Comments
 (0)