Wednesday, June 25, 2008

Puzzle on Ruby - Part 1

I like to play puzzles solving game, especially puzzles that related to numbers. In this post, I going to use Ruby to solve a puzzle. Here it is

ABC + BDE = CEF

Condition #1: Every alphabet is represent a digit between 0 to 9.

Based on the condition above, this puzzle can be came out a lot of solutions. Some of the solutions are

000 + 000 = 000 (haha...this is a solution too based on the condition #1)
123 + 202 = 325
639 + 348 = 987
...and so on

Okay! Let's get the Ruby rolling. I'm going to use a "brute-force" method to solve this puzzle, and find as much as possible available solutions. Here is the Ruby code

# abc loop
(0..999).each do abc
b = (abc % 100) / 10
c = abc % 10

# de loop
(0..99).each do de
bde = 100 * b + de
e = bde % 10

# f loop
(0..9).each do f
cef = 100 * c + 10 * e + f
if (abc + bde == cef)
print sprintf("%03d", abc) + " + "
print sprintf("%03d", bde) + " = "
puts sprintf("%03d", cef)
end
end
end
end


Even the solver is brute-force method, the Ruby program only tooks 5 seconds to finish. Wow! I'm so amazing. It's realy really fast.

Total is 500 solutions available!!! So, you might want to think that this puzzle was too EASY to you, and you probably can find out two or three dozen of solutions easily.

Okay! Let's make this puzzle more challenging by adding one more condition.

Condition #2: Whenever a digit has been used, that digit cannot be used anymore for other alphabets.

000 + 000 = 000 (this solution is no longer stands)
123 + 202 = 325 (this one too...)
639 + 348 = 987 (Oh...this one is perfect match for condition #2, so it's a solution!)

You may need some time to solve it. Total is 81 solutions available! GOOD LUCK!

--- Extra ---

Condition #3:
8 * ( ABC - BDE ) = CEF

ONLY a solution exists! Try it out. It's pretty easy I tell you. Send me a comment with this answer...

No comments: