Ruby Puzzler

March 24, 2007 Alex Chaffee

puzzler I was just sitting around my living room listening to NPR, and heard the following Car Talk puzzler:

I want you to get a pencil and write down the numbers, 1 – 9, inclusive, and leave enough space between them. At your disposal you have one plus sign and two minus signs. You can insert those plus and minus signs wherever you want, to make the total come out to 100.

Naturally, I thought, “Gee, that would be tedious to solve it by hand. But it would be fun to write a Ruby program to solve it!” 9 minutes later I was sending the result (and the source code) to Car Talk Plaza.

So here’s your challenge: can you write a program to solve this puzzle? And can you beat my time?

My solution is below the fold… don’t click “more” until you’ve taken a stab at it yourself.


(1..8).each do |plus|
  (1..8).each do |minus1|
    next if minus1 == plus
    ((minus1+1)..8).each do |minus2|
      next if minus2 == minus1 or minus2 == plus
      exp = ""
      (1..9).each do |digit|
        exp = "#{exp}#{digit}"
        exp = "#{exp}+" if digit==plus
        exp = "#{exp}-" if digit==minus1 or digit==minus2
      x = eval(exp)
      if x == 100
        puts "#{exp}=#{x}"

And a follow-on challenge: can you refactor my code to make it either clearer or more concise (i.e. obfuscated)?

About the Author


The Joy Of Deleting Code
The Joy Of Deleting Code

Mark and I were just waxing poetic about how great it is to delete code, especially code you just wrote. ...

The best thing I’ve heard all day
The best thing I’ve heard all day

"This is either the stupidest or best idea I've ever heard"

SpringOne 2021

Register Now