Math Quiz Ruby

Here's some ruby code to demonstrate an exhaustive search for a candidate solution to the following problem from MathQuizOne:

"The expression 9*7-4*8-2 (where * is the multiplication operator) has value 29 (since multiplication takes precedence over subtraction). Now suppose you evaluate using a calculator of the older type which implements add, subtract, multiply and divide in the order they are entered, so that the expression has value 470. Replace each multiplication and subtraction symbol with a mathematical symbol of your choice (without using letters, brackets, or digits) so that the value of the expression becomes 29 again."

The code itself makes certain assumptions about the shape of an acceptable solution. If you have other ideas, you'll have to change the code.


 #!/usr/bin/env ruby

add = Proc.new { |a, b| a+b } sub = Proc.new { |a, b| a-b } mul = Proc.new { |a, b| a*b } div = Proc.new { |a, b| a/b }

@ops = {'+'=>add, '-'=>sub, '*'=>mul, '/'=>div}

@sols = []

def f(num, lst, str) if lst.empty? then @sols << [str, num] else head = lst[0] tail = lst[1, lst.length - 1] @ops.each do |ch, op| try = op.call(num, head) f(try, tail, str+ch) end end end

f(9.0, [7, 4, 8, 2], '')

p @sols


For the impatient: This code does not output the number 29 (though it does output 29.5 a couple times.)

This doesn't say anything important on the feasibility of getting 29. What is says a lot about is the insanity of the question. The answer depends on the requirements, which themselves are deliberately unclear enough to make the problem into a riddle. Perhaps Vicky feels clever or superior.

You are invited to fiddle with the code here and post results below. Outright removal of the page is offensive, OTOH.

Perhaps Vicki, etc.

Actually, no. The mathematical knowledge needed is fairly mundane, but it's interesting to see the ways in which the question is tackled, with various people confidently reaching mutually incompatible conclusions about individual tasks, and also about how easy the tasks are. They are not riddles, and (as already stated) the assessment of answers takes into account the minor problems of interpretation alluded to. -- vk


EditText of this page (last edited February 8, 2004) or FindPage with title or text search