A famous set of computer problems involve verbal arithmetic. In these problems,
you are given equations of words like:

send
+ more
------
money

or:

forty
ten
+ ten
-------
sixty

The goal is to find a single digit for each letter that makes the equation true.
Normal rules of number construction apply, so the first digit of a multi-digit
number should be nonzero and each letter represents a different digit.

This week's quiz is to build a program that reads in equations and outputs
solutions. You can decide how complex of an equation you want to support, with
the examples above being the minimum implementation.

ohh I totally misunderstood the task here.. I thought the input would be
send+more and my app should give money as answer trough calculation..

James Edward Gray II wrote:
> On Jun 15, 2007, at 7:55 AM, anansi wrote:
>
>> I really don't get it How did you figured out that 2 = y in your
>> example?
>
> Well, a non-clever way is to try an exhaustive search of each digit for
> each letter.
>
> James Edward Gray II
>

--
greets

one must still have chaos in oneself to be able to
give birth to a dancing star

anansi wrote, On 6/15/2007 8:10 AM:
> ohh I totally misunderstood the task here.. I thought the input would
> be send+more and my app should give money as answer trough calculation..
>

For perhaps a reason to change the wording, that's what I thought as
well until I read the explanation to anansi's question.

Sam

> James Edward Gray II wrote:
>> On Jun 15, 2007, at 7:55 AM, anansi wrote:
>>
>>> I really don't get it How did you figured out that 2 = y in your
>>> example?
>>
>> Well, a non-clever way is to try an exhaustive search of each digit
>> for each letter.
>>
>> James Edward Gray II
>>
>
>

On Jun 15, 2007, at 8:17 AM, Sammy Larbi wrote:
> anansi wrote, On 6/15/2007 8:10 AM:
>> ohh I totally misunderstood the task here.. I thought the input
>> would be send+more and my app should give money as answer trough
>> calculation..
>>
>
> For perhaps a reason to change the wording, that's what I thought
> as well until I read the explanation to anansi's question.

Sorry for the confusion folks. You get both sides of the equation
and are expected to fine the digit to represent each letter.

My solution works with addition and multiplication of any sized list of words,
and subtraction of a list of exactly two words. Its also a fair bit faster
than brute force. Unfortunately it got pretty messy, and after some rough
debugging I'm not in the mood to clean it up just now.

I came up with the basic idea by noticing that the equations can be built
up and checked from simpler equations taken from the right-hand side. Er..
lemme give an example to explain better:

9567
+ 1085
------
10652

Start off by looking for ways to satisfy:
7
+ 5
---
2

Then move further to the left:

67
+ 85
----
152

The 52 is right, but not the 1. For addition and multiplication, we can just
take it mod 100, and if that works then its a possible partial solution.
For subtraction of two numbers, though, it doesn't work when it goes negative.
The trick in that case is to just mod the left-most digit:

9567
- 1085
------
8482

7
- 5
---
2 OK

67
- 85
----
-22 => 82 (-2 mod 10 = 8)

verbal_arithmetic.rb contains (old, ugly) code for generating permutations
and combinations. So the program works from right-to-left, finding partial
solutions that work by going through ways of mapping letters to numbers,
and for each one trying to move further left. Basically a depth-first search.

There are a number of other subteties, but like I said, I'm tired of messing
with this now, so I'll leave it there. Ask if you must.

# translate the next position back into a combination
next_combo = Array.new r
(0...next_combo.size).each do |i|
next_combo = self[positions - 1]
end
next_combo
end

# Yields every r-combination of the elements in this Array.
def each_combination r
combo = first_combination r
while not combo.nil?
yield combo
combo = next_combination combo
end
end

# Swap the elements at the two given positions.
def swap! i, j
self, self[j] = self[j], self
end

# Generates all permutations of this Array, yielding each one.
# Based on: http://www.geocities.com/permute_it/
# This does not generate them in lexicographic order, but it is fairly quick.
def each_permutation
# This is pretty ugly..
a, p, i = self.clone, (0..self.size).to_a, 0
while i < self.size
p -= 1
(i % 2) == 1 ? j = p : j = 0
a.swap! i, j
yield a
i = 1
while p.zero?
p = i
i += 1
end
end
end
end

# Generate possible ways of mapping the letters in words to numbers.
# - words: an array of words
# - determined: a previously-determined partial mapping which is to be filled
# out the rest of the way
def each_mapping words, determined = {}
letters = Set[]
words.each do |word|
word.each_byte { |b| letters << b.chr if not determined.has_key?(b.chr) }
end

# Find all arrangements of letters.size undetermined numbers and for each
# match them up with letters.
pool = (0...@base).to_a - determined.values
if pool.size.zero? or letters.size.zero?
yield determined.clone
else
pool.each_combination(letters.size) do |comb|
comb.each_permutation do |perm|
mapping = determined.clone
letters.each_with_index { |let, i| mapping[let] = perm }
yield mapping
end
end
end
end

[Note: this didn't seem to get through the first time. Apologies if it did.]

My solution works with addition and multiplication of any sized list of words,
and subtraction of a list of exactly two words. Its also a fair bit faster
than brute force. Unfortunately it got pretty messy, and after some rough
debugging I'm not in the mood to clean it up just now.

I came up with the basic idea by noticing that the equations can be built
up and checked from simpler equations taken from the right-hand side. Er..
lemme give an example to explain better:

9567
+ 1085
------
10652

Start off by looking for ways to satisfy:
7
+ 5
---
2

Then move further to the left:

67
+ 85
----
152

The 52 is right, but not the 1. For addition and multiplication, we can just
take it mod 100, and if that works then its a possible partial solution.
For subtraction of two numbers, though, it doesn't work when it goes negative.
The trick in that case is to just mod the left-most digit:

9567
- 1085
------
8482

7
- 5
---
2 OK

67
- 85
----
-22 => 82 (-2 mod 10 = 8)

verbal_arithmetic.rb contains (old, ugly) code for generating permutations
and combinations. So the program works from right-to-left, finding partial
solutions that work by going through ways of mapping letters to numbers,
and for each one trying to move further left. Basically a depth-first search.

There are a number of other subteties, but like I said, I'm tired of messing
with this now, so I'll leave it there. Ask if you must.

# translate the next position back into a combination
next_combo = Array.new r
(0...next_combo.size).each do |i|
next_combo = self[positions - 1]
end
next_combo
end

# Yields every r-combination of the elements in this Array.
def each_combination r
combo = first_combination r
while not combo.nil?
yield combo
combo = next_combination combo
end
end

# Swap the elements at the two given positions.
def swap! i, j
self, self[j] = self[j], self
end

# Generates all permutations of this Array, yielding each one.
# Based on: http://www.geocities.com/permute_it/
# This does not generate them in lexicographic order, but it is fairly quick.
def each_permutation
# This is pretty ugly..
a, p, i = self.clone, (0..self.size).to_a, 0
while i < self.size
p -= 1
(i % 2) == 1 ? j = p : j = 0
a.swap! i, j
yield a
i = 1
while p.zero?
p = i
i += 1
end
end
end
end

# Generate possible ways of mapping the letters in words to numbers.
# - words: an array of words
# - determined: a previously-determined partial mapping which is to be filled
# out the rest of the way
def each_mapping words, determined = {}
letters = Set[]
words.each do |word|
word.each_byte { |b| letters << b.chr if not determined.has_key?(b.chr) }
end

# Find all arrangements of letters.size undetermined numbers and for each
# match them up with letters.
pool = (0...@base).to_a - determined.values
if pool.size.zero? or letters.size.zero?
yield determined.clone
else
pool.each_combination(letters.size) do |comb|
comb.each_permutation do |perm|
mapping = determined.clone
letters.each_with_index { |let, i| mapping[let] = perm }
yield mapping
end
end
end
end

This program solves addition problems with any number of terms. It
finds and displays all solutions to the problem.

The solving process is broken up into a sequence of simple steps all
derived from class Step. A Step can be something such as 1) choosing
an available digit for a given letter or 2) summing up a column and
seeing if the result matches an already-assigned letter. As steps
succeed the process continues with the following steps. But if a step
fails (i.e., there's a contradiction) then the system backs up to a
point where another choice can be made. This is handled by recursing
through the sequence of steps. In fact, even when a solution is
found, the program still backtracks to find other solutions.

The expectation is that by testing for contradictions as early as
possible in the process we'll tend to avoid dead ends and the result
will be much better than an exhaustive search.

For example, here are the steps for a sample equation:

send
+more
-----
money

1. Choose a digit for "d".
2. Choose a digit for "e".
3. Sum the column using letters "d", "e" (and include carry).
4. Set the digit for "y" based on last column summed.
5. Choose a digit for "n".
6. Choose a digit for "r".
7. Sum the column using letters "n", "r" (and include carry).
8. Verify that last column summed matches current digit for "e".
9. Choose a digit for "o".
10. Sum the column using letters "e", "o" (and include carry).
11. Verify that last column summed matches current digit for "n".
12. Choose a digit for "s".
13. Verify that "s" has not been assigned to zero.
14. Choose a digit for "m".
15. Verify that "m" has not been assigned to zero.
16. Sum the column using letters "s", "m" (and include carry).
17. Verify that last column summed matches current digit for "o".
18. Sum the column using letters (and include carry).
19. Verify that last column summed matches current digit for "m".
20. Display a solution (provided carry is zero)!

Eric
----
Are you interested in on-site Ruby training that's been highly
reviewed by former students? http://LearnRuby.com

====

# This is a solution to Ruby Quiz #128. As input it takes a "word
# equation" such as "send+more=money" and determines all possible
# mappings of letters to digits that yield a correct result.
#
# The constraints are: 1) a given digit can only be mapped to a single
# letter, 2) the first digit in any term cannot be zero.
#
# The solving process is broken up into a sequence of simple steps all
# derived from class Step. A Step can be something such as 1)
# choosing an available digit for a given letter or 2) summing up a
# column and seeing if the result matches an already-assigned letter.
# As steps succeed the process continues with the following steps.
# But if a step fails (i.e., there's a contradiction) then the system
# backs up to a point where another choice can be made. This is
# handled by recursing through the sequence of steps. In fact, even
# when a solution is found, the program still backtracks to find other
# solutions.

require 'set'

# State represents the stage of a partially solved word equation. It
# keeps track of what digits letters map to, which digits have not yet
# been assigned to letters, and the results of the last summed column,
# including the resulting digit and any carry if there is one.
class State
attr_accessor :sum, :carry
attr_reader :letters

# Return the available digits as an array copied from the set.
def available_digits
@available_digits.to_a
end

# Tests whether a given digit is still available.
def available?(digit)
@available_digits.member? digit
end

# Receives the total for a column and keeps track of it as the
# summed-to digit and any carry.
def column_total=(total)
@sum = total % 10
@carry = total / 10
end
end

# Step is an "abstract" base level class from which all the "concrete"
# steps can be deriveds. It simply handles the storage of the next
# step in the sequence. Subclasses should provide 1) a to_s method to
# describe the step being performed and 2) a perform method to
# actually perform the step.
class Step
attr_writer :next_step
end

# This step tries assigning each available digit to a given letter and
# continuing from there.
class ChooseStep < Step
def initialize(letter)
@letter = letter
end

def to_s
"Choose a digit for \"#{@letter}\"."
end

def perform(state)
state.available_digits.each do |v|
state[@letter] = v
@next_step.perform(state)
end
state.clear(@letter)
end
end

# This step sums up the given letters and changes to state to reflect
# the sum. Because we may have to backtrack, it stores the previous
# saved sum and carry for later restoration.
class SumColumnStep < Step
def initialize(letters)
@letters = letters
end

# This step determines the digit for a letter given the last column
# summed. If the digit is not available, then we cannot continue.
class AssignOnSumStep < Step
def initialize(letter)
@letter = letter
end

def to_s
"Set the digit for \"#{@letter}\" based on last column summed."
end

def perform(state)
if state.available? state.sum
state[@letter] = state.sum
@next_step.perform(state)
state.clear(@letter)
end
end
end

# This step will occur after a column is summed, and the result must
# match a letter that's already been assigned.
class CheckOnSumStep < Step
def initialize(letter)
@letter = letter
end

def to_s
"Verify that last column summed matches current " +
"digit for \"#{@letter}\"."
end

def perform(state)
@next_step.perform(state) if state[@letter] == state.sum
end
end

# This step will occur after a letter is assigned to a digit if the
# letter is not allowed to be a zero, because one or more terms begins
# with that letter.
class CheckNotZeroStep < Step
def initialize(letter)
@letter = letter
end

def to_s
"Verify that \"#{@letter}\" has not been assigned to zero."
end

# This step represents finishing the equation. The carry must be zero
# for the perform to have found an actual result, so check that and
# display a digit -> letter conversion table and dispaly the equation
# with the digits substituted in for the letters.
class FinishStep < Step
def initialize(equation)
@equation = equation
end

terms[0..-2].each do |term| # for each term that's being added...
letter = term[index, 1]
next if letter.nil? # skip term if no letter in column
letters << letter # note that this letter is part of sum

# if the letter does not have a digit, create a ChooseStep
unless chosen_letters.member? letter
steps << ChooseStep.new(letter)
chosen_letters.add(letter)
steps << CheckNotZeroStep.new(letter) if
nonzero_letters.member? letter
end
end

# create a SumColumnStep for the column
steps << SumColumnStep.new(letters)

summed_letter = terms[-1][index, 1] # the letter being summed to

# check whether the summed to letter should already have a digit
if chosen_letters.member? summed_letter
# should already have a digit, check that summed digit matches it
steps << CheckOnSumStep.new(summed_letter)
else
# doesn't already have digit, so create a AssignOnSumStep for
# letter
steps << AssignOnSumStep.new(summed_letter)
chosen_letters.add(summed_letter)

# check whether this letter cannot be zero and if so add a
# CheckNotZeroStep
steps << CheckNotZeroStep.new(summed_letter) if
nonzero_letters.member? summed_letter
end
end

# should be done, so add a FinishStep
steps << FinishStep.new(display)

Here is my solution for Ruby Quiz 128. It's a little rough, but I
can't afford to spend any more time working on it. One thing I didn't
have time to do was to provide a user interface. Another thing I
didn't do was proper commenting. I apologize for the latter.

I thought a Darwinian search (aka genetic algorithm) would be an
interesting way to tackle this quiz. I have been looking for a excuse
to write such a search in Ruby for quite awhile and this seemed to be
it.

<code>
# lib/solver.rb
# Quiz 128
#
# Created by Morton Goldberg on 2007-06-18.
#
# Attempts to a solve cryptarithm puzzle by applying a Darwinian search
# (aka genetic algorithm). It can thought of as a stochastic breadth-
first
# search. Although this method doesn't guarantee a solution will be
# found, it often finds one quite quickly.

The first is a script which poses the problems to their own solving-
program. The second shows the solutions that their program produces.

Some of the sample equations have multiple solutions, such as 'eins
+eins=zwei'. 'united+states=america' has no solutions. And of the
few that I've tested with my own solution, 'saturn+pluto+uranus
+neptune=planets' takes the longest to solve.

Eric
----
Interested in hands-on, on-site Ruby training? See http://LearnRuby.com
for information about a well-reviewed class.

<code>
# lib/solver.rb
# Quiz 128
#
# Created by Morton Goldberg on 2007-06-18.
#
# Attempts to a solve cryptarithm puzzle by applying a Darwinian search
# (aka genetic algorithm). It can thought of as a stochastic breadth-
first
# search. Although this method doesn't guarantee a solution will be
# found, it often finds one quite quickly.

Ruby Quiz wrote:
> This week's quiz is to build a program that reads in equations and outputs
> solutions. You can decide how complex of an equation you want to support, with
> the examples above being the minimum implementation.
>

This solution requires Gecode/R[1] 0.2.0 (need to install Gecode[3,4]
followed by Gecode/R[2]). Gecode does the actual search, so we just
specify the constraints. Two important aspects that are used to make the
solution quick to compute are:

== Propagation rather than branching (deduction rather than exploration)

Branching (i.e. testing a guess, i.e. exploring the search space) costs
since we have to save the old state and start a new one. Rather Gecode
tries to prune as much of the search space as it can before resorting to
exploration. In the case of linear constraints (e.g. a + 10*b + c= 10*d
+ e, which corresponds to the problem

a
+ bc
----
de

) it takes each variable and considers the smallest and largest values
it can possibly take. E.g. if we consider a in the above example we can
rewrite the linear equation to

a = 10*(d - b) + e - c

From that equation we can check how large and small the right hand side
can be and then remove all other possibilities from the domain of a. We
can end up pruning quite a lot if we do this for each variable until
there are no more possibilities left to remove (coupled with the
distinct constraint).

In fact when we use this for send+more=money, without doing any sort of
exploration we can directly reduce the domains of the variables down to

s=9, e=4..7, n=5..8, d=2..8, m=1, o=0, r=2..8, y=2..8

So without any guessing at all we already know the value of three
letters and have pruned the domains of the others (i.e. pruned the
number of possibilities left, i.e. reduced the search space).

Since we now have to start exploring the search space we make a guess
that e=4. Propagating the constraints once again with e given the domain
4 will directly result in a failure, so we backtrack and now know that
e!=4. With that information we redo the propagation and directly end up
at the solution with no need to explore any further. So in total we only
need to explore 4 out of 9^2*10^6 nodes in the search space.

== Branching with a good heuristic

We don't randomly select where to go next in the search space, rather we
use a fail-first heuristic to try to cut down the search space faster.
The heuristic is to simply try to fixate a value for the variable with
the smallest domain. The reason that it works well is that we exhaust
domains quicker, hence forcing failures quicker (hence fail-first)

== The code

require 'rubygems'
require 'gecoder'

# Solves verbal arithmetic problems
# ( http://en.wikipedia.org/wiki/Verbal_arithmetic ). Only supports
# addition.
class VerbalArithmetic < Gecode::Model
# Creates a model for the problem where the left and right hand sides
# are given as an array with one element per term. The terms are given
# as strings
def initialize(lhs_terms, rhs_terms)
super()

Andreas Launila wrote:
> Since we now have to start exploring the search space we make a guess
> that e=4. Propagating the constraints once again with e given the domain
> 4 will directly result in a failure, so we backtrack and now know that
> e!=4. With that information we redo the propagation and directly end up
> at the solution with no need to explore any further. So in total we only
> need to explore 4 out of 9^2*10^6 nodes in the search space.
>

The last part is probably a bit misleading/incorrect. We are not
directly exploring the space of all possible assignments when we branch,
so saying that we have explored 4 nodes in that space is incorrect (i.e.
we have not just explored 4 possible assignments, but we have visited
just 4 nodes in our search space).

On 6/15/07, Ruby Quiz <> wrote:
>
> This week's quiz is to build a program that reads in equations and outputs
> solutions. You can decide how complex of an equation you want to support, with
> the examples above being the minimum implementation.
>

Share This Page

Welcome to The Coding Forums!

Welcome to the Coding Forums, the place to chat about anything related to programming and coding languages.

Please join our friendly community by clicking the button below - it only takes a few seconds and is totally free. You'll be able to ask questions about coding or chat with the community and help others.
Sign up now!