Math challenge

Posted by Anton Katunin on 16 July 2016
Tags: code, ruby

Last friday one of my friend gave me a math challenge. You've given four numbers 6, 6, 5 and 2, you need to find 3 math operations to get 17 as a result. You have to use all four numbers and only once each. Order of numbers can be any.

I couldn't figure it out in my head so have to write a ruby script to iterate over all combinations, which turned out as a great coding exercise.

Solution

final_result = 17
numbers = [6, 6, 5, 2]
numbers.map!(&:to_f)

operations = [:+, :-, :*, :/]
operation_combinations = []

4.times do |a|
  4.times do |b|
    4.times do |c|
      operation_combinations << [operations[a-1], operations[b-1], operations[c-1]]
    end
  end
end

iteration_count = 0
results = []

numbers.permutation do |nums|

  operation_combinations.each do |ops|
    iteration_count += 1

    begin
      result = nums.each.with_index.reduce(nil) do |memo, (num, index)|
        if memo.nil?
          num
        else
          op = ops[index - 1]
          memo.send(op, num)
        end
      end

      if result == final_result
        results << [nums, ops]
      end

    rescue ZeroDivisionError
      0
    end
  end

end

puts iteration_count
puts results

Final Result

(5 / 6 + 2) * 6 = 17


Read next:

Bystander effect