#!/usr/bin/env ruby class Integer define_method(:"||") do |v| to_s.concat(v.to_s).to_i end end problem = 7 input = File.readlines("#{problem}.input").map(&:strip) #input = DATA.read.split("\n") .map do |line| solution, expression = line.split(": ") [ solution.to_i, expression.split(" ").map { _1.strip.to_i } ] end OPERATIONS = [:+, :*, :"||"] def solve(equation) equation[1..].each_slice(2).to_a .reduce(equation[0]) do |acc, (operation, number)| acc = acc.public_send(operation, number); acc end end def possibilities(solution, numbers) OPERATIONS.repeated_permutation(numbers.size - 1) .map { numbers.zip(_1).flatten.compact } .any? { solve(_1) == solution } end result = input .select { possibilities(_1.first, _1.last) } .map { _1.first } .sum p result __END__ 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