diff --git a/2024/day07.rb b/2024/day07.rb new file mode 100644 index 0000000..17b7eb6 --- /dev/null +++ b/2024/day07.rb @@ -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) diff --git a/2024/examples/day07.txt b/2024/examples/day07.txt new file mode 100644 index 0000000..fc6e099 --- /dev/null +++ b/2024/examples/day07.txt @@ -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