Implement a verbal arithmetic solver of several same sequence of numbers added together:




There are some restrictions: each letter should represent different digits, and no letter can be zero.

Implement the solver as a function of the operands, the sum and number of repetitions returns a list of solutions (solution: the tuple of resulting operand and sum). For example:

f(['T','W','O'], ['F','O','U','R'], 2) == [(734, 1468)]

You do not need to represent variables as letters, and you do not need to use a hash in the solution. Brute-force search allowed.

Shortest code wins.

  • \$\begingroup\$ Can you give a sample solution for the other two cases? \$\endgroup\$ – fR0DDY Mar 18 '11 at 8:08
  • \$\begingroup\$ SPEED:= 29331, 58662:= KILLS, code follows, needs to be golfed. \$\endgroup\$ – user unknown Apr 23 '11 at 5:25


Spaces added for clarity. Not much golfed.
Need to use greek letters because the input letters are treated as symbols.

F[σ_ ,ρ_ ,τ_]:=
 (φ = FromDigits;
   If [ τ * φ@σ == φ@ρ, {φ@σ,φ@ρ} ] /.#& /@
 (Thread[Rule[ σ ∪ ρ , # ] ] & /@ Permutations[Range@9, {Length[σ ∪ ρ] }])])





It didn't find any solution for the SPEED+SPEED+SPEED = KILLS ... is that a bug?


Allowing zero, it finds the following solutions for the SPEED+SPEED+SPEED = KILLS equation:



According to comment:

F[{s, p, e, e, d}, {k, i, l, l, s}, 2]  

| improve this answer | |
  • \$\begingroup\$ meta-comment ... Is there a way to show greek letters in code blocks? \$\endgroup\$ – Dr. belisarius Mar 18 '11 at 16:12
  • \$\begingroup\$ EDIT: the one shown on the paper has only two SPEED's \$\endgroup\$ – Ming-Tang Mar 18 '11 at 22:38
  • \$\begingroup\$ belisarius: Th trick is not to use HTML escapes. Since those represent only characters using characters directly is not forbidden ;-). You may have to fix your indenting, though; I'm not sure I kept that correct. \$\endgroup\$ – Joey Mar 24 '11 at 17:04
  • \$\begingroup\$ @Joey The escaped chars are not used in Mathematica source, I used them just for rendering here. But it seems not all browsers render the chars equal. I see your code and mine exactly the same :) \$\endgroup\$ – Dr. belisarius Mar 24 '11 at 19:46


def f(A,B,N):
 for j in A:D[j]=0
 for j in B:D[j]=0
 for i in xrange(10**(x-1),10**x):
        for j in c:s[j]=0
        if(len(s)-x or '0' in c):continue
        for j in D:D[j]=int(c[k]);k+=1
        for j in A:P=P*10+D[j]
        for j in B:Q=Q*10+D[j]
 return r
print f(['T','W','O'], ['F','O','U','R'], 2)


| improve this answer | |

scala: 333 289

type S=String
def d(x:S,m:Map[Char,Int])={var s=0
def s(t:Int,f:S,p:S):Unit={
def c(m:Map[Char,Int])=d(f,m)*t==d(p,m)
val g=f.toSet++p
val m=g.zip(util.Random.shuffle((1 to 9).toSeq).take(g.size))
if(c(m.toMap))print(m)else s(t,f,p)}


s (2,"SPEED","KILLS")
Set((D,7), (K,8), (I,5), (E,6), (S,4), (L,3), (P,2))

// endless loop :)
| improve this answer | |

PHP (200)

This function takes a very long time to execute and uses lots of memory, but it satisfies the criteria.

function f($o,$s,$n){$w=count_chars(($c=join($o)).$d=join($s),3);while(++$i<pow(10,9)){if(($u=count_chars($i,3))&&$u[0]*$u[8]&&($n*$a=strtr($c,$w,$i))==$b=strtr($d,$w,$i))$x[]=array($a,$b);}return$x;}

Sample usage:

$c=f($a, $b, 2); // returns an array of tuples that satisfy the equation

Un-golfed explanation:

function solve($operand, $sum, $num) {
  // convert the operand and sum arrays into strings, join them, then get a string containing the unique characters
  $operand_string = join($operand);
  $sum_string = join($sum);
  $unique_chars = count_chars($operand_string . $sum_string, 3);

  // loop from 1 to 10^9
  while (++$i < pow(10,9)) {
    // get the unique digits in $i
    $unique_digits = count_chars($i, 3);
    // check whether the first digit is non-zero (count_chars sorts in ascending order)
    // and whether the ninth digit is non-zero, these conditions guarantee that $i
    // is a permutation of 1...9 
    if ($u[0] * $u[8]) {
      // translate the operand and sum into numbers, then check if the operand * num = sum
      $translated_operand = strtr($operand_string, $unique_chars, $i);
      $translated_sum = strtr($sum_string, $unique_chars, $i);
      if ($num * $translated_operand == $translated_sum) {
        // add the solution to the solutions array
        $solutions[] = array($translated_operand, $translated_sum);
  // return the solutions array
  return $solutions;

If we're allowed to input the operand and sum as strings instead of arrays, then I can skip the join operations and save 20 characters to put the total at 180.

| improve this answer | |

05AB1E, 24 bytes


Takes two loose inputs, the first being the integer and the second as a pair of words (i.e. first input = 4, second input = ["ANDSTOP","REPEAT"]).

Try it online. Brute-force approach, so unfortunately it's extremely slow; it's barely able to output the result for the first test case in ~45 seconds on TIO.


žh       # Push builtin "0123456789"
  œ      # Get all 3628800 (10!) permutations of this string of digits
   ï     # Cast each to an integer to remove leading 0s from some items
         # (otherwise ["0264","132"] would be the output for the first test case)
²        # Push the second input-pair
 J       # Join them together
  Ù      # Uniquify the letters
   ©     # Store it in variable `®` (without popping)
    g    # Pop and push its length to get the amount of unique letters
     δ   # For each permutation:
      £  #  Only keep the first unique-length amount of digits
ε        # Map each shortened string of digits to:
 U       #  Pop and store the current string of digits in variable `X`
  ε      #  Map over the two words of the (implicit) second input-pair
   ®     #   Push the unique letters from variable `®`
    X    #   Push the current digits we're mapping over from variable `X`
     ‡   #   Transliterate the letters to digits in the input-string we're mapping over
]        # Close the nested maps
 .Δ      # Find the first pair of integers which is truthy for:
   `     #  Pop and push them separated to the stack
    ¹*   #  Multiply the second (top) value by the first input
      Q  #  And check if it's now equal to the first value
         # (after which the result is output implicitly)
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.