Skip to content

Commit

Permalink
Year 2024 Day 7
Browse files Browse the repository at this point in the history
  • Loading branch information
tudorpavel committed Dec 8, 2024
1 parent de18bb6 commit b7bd784
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
40 changes: 40 additions & 0 deletions 2024/day07.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
lines = STDIN.read.split("\n")

ADD = '+'
MUL = '*'
CON = '||'
P1_OPTS = [ADD, MUL]
P2_OPTS = [ADD, MUL, CON]

def total_calibration(equations, possible_operators)
result = 0
equations.each do |(test_value, operands)|
choices = possible_operators.repeated_permutation(operands.size - 1)
choices.each do |operators|
res = operators.zip(operands[1..]).reduce(operands.first) do |acc, (opt, opd)|
case opt
when ADD
acc += opd
when MUL
acc *= opd
else
acc = (acc.to_s + opd.to_s).to_i
end
end

if res == test_value
result += res
break
end
end
end
result
end

equations = lines.map do |line|
l, r = line.split(':')
[l.to_i, r.split.map(&:to_i)]
end

puts total_calibration(equations, P1_OPTS)
puts total_calibration(equations, P2_OPTS)
9 changes: 9 additions & 0 deletions 2024/examples/day07.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
190: 10 19
3267: 81 40 27
83: 17 5
156: 15 6
7290: 6 8 6 15
161011: 16 10 13
192: 17 8 14
21037: 9 7 18 13
292: 11 6 16 20

0 comments on commit b7bd784

Please sign in to comment.