## Same Five Digits

### April 19, 2011

I chose to use Python to solve this problem.

The brute force solution is to enumerate all the perfect squares with five digits. Then try them in all combinations taken three at a time.

`from itertools import count, takewhile`

```
```squares = filter(lambda s: len(s) == 5,

takewhile(lambda s: len(s) <= 5,

(str(s**2) for s in count())))

`for a, b, c in combinations(squares, 3):`

# ...

Each trio of numbers has to meet three criteria.

- C1. five different digits occur in the trio.
- C2. each digit occurs a different number of times (has a different count).
- C3. the five counts are the same as the five digits.

A digit count histogram would help with all of those. Let’s define a function to build it.

`from collections import defaultdict`

```
```

`def histogram(s):`

d = defaultdict(int)

for c in s:

d[c] += 1

return d

That returns a dictionary mapping each digit to the number of times it occurs. For example, `hist('31415')`

would return `{1: 2, 3: 1, 4: 1, 5: 1}`

, meaning 1 occurs twice and 3, 4 and 5 each occur once.

Now we can test for the three criteria like this.

`hist = histogram(a + b + c)`

digits = set(hist.keys())

counts = set(hist.values())

if (len(digits) == 5 and # five different digits

digits == counts and # digits == counts

not any(hist[k] == k for k in hist)): # k does not occur k times.

# then a, b, c meet the criteria.

We need to find all trios that meet the criteria, then find the one whose singleton digit is unique. So we’ll build a map from singleton digit to the set of trios with that singleton.

`matches = defaultdict(list)`

for a, b, c in combinations(squares, 3):

# ...

if «criteria met»:

inverse_hist = dict((hist[k], k) for k in hist)

singleton = inverse_hist[1]

matches[singleton].append((a, b, c))

Now we need to find the entry in matches that has length one. We’ll do that by creating yet another map, this time from number of matches to the list of matches. Then we can extract the answer directly.

`match_counts = dict((len(ls), ls) for ls in matches.values())`

print(*match_counts[1][0])

On my computer, this solution runs for about 30 seconds. It is a brute force solution, and was coded with the barest minimum amount of analysis of the problem. So 30 seconds is not unreasonable. But we can do much better.

We can determine what digits the solution will use. Since the three numbers have 15 digits total, the five counts must sum to 15. Since the digits match the counts, the digits must sum to 15 as well. The only possible set of five unique digits is {1, 2, 3, 4, 5}. So let’s discard all the candidate squares that have digits outside that set. We can refine the way we collect the list of squares like this.

`squares = filter(lambda s: len(s) == 5 and all(c in '12345' for c in s),`

takewhile(lambda s: len(s) <= 5,

(str(s**2) for s in count())))

That small change reduces the number of candidate squares from 217 to 9, and the number of combinations from 1,679,580 to 84. The program now runs in under 20 milliseconds, which is more than 10,000 times faster.

To run either program, save the program text into a file `enigma_1638.py`

and say:

`$ python enigma_1638.py`

12321 33124 34225

You can run the program at http://programmingpraxis.codepad.org/l2hDGwBm, where a definition of the `combinations`

function is provided for backward compatibility to versions of Python prior to 2.6.

Pages: 1 2

[…] today’s Programming Praxis exercise, our goal is to solve a numeric riddle. Let’s get started, shall […]

My Haskell solution (see http://bonsaicode.wordpress.com/2011/04/19/programming-praxis-same-five-digits/ for a version with comments):

Here is my solution:

`(list-of (list a b c s)`

(x is (list-of x2

(x range 100 236) (x2 is (* x x))

(not (= (apply min (digits x2)) 0))

(< (apply max (digits x2)) 6)))

(a in x) (b in x) (c in x) (< a b) (< b c)

(d is (sort < (mappend digits (list a b c))))

(s is (uniq-c = d))

(= (length (unique = (sort < (map cdr s)))) 5)

(equal? (unique = d) (unique = (sort < (map cdr s))))

(ok? s))

Let’s look at that slowly. X is a list of all five-digit squares that contain only the digits 1 through 5. The inner x ranges from 100 (because 100

^{2}is the smallest 5-digit number) to 236 (because 236^{2}is the smallest square greater than 55555). Then the predicate (< 0 (apply max (digits x2)) 6) passes only those numbers with the digits 1 through 5. There are 9 such numbers, the squares of 111, 112, 115, 182, 185, 188, 211, 229, and 235.On the next line, the three "in" clauses form the cross product of the nine squares, a total of 9

^{3}=729 triplets. The remaining two clauses on that line eliminate duplicates, reducing the number of triplets from 729 to 84, which by the binomial theorem is the number of ways 3 items can be chosen from a list of 9:`(define (choose n k)`

(if (zero? k) 1

(* n (/ k) (choose (- n 1) (- k 1)))))

`> (choose 9 3)`

84

Next we want to calculate the “signature” of the digit counts in the solution. We calculate the fifteen digits in

d, and the signature of the counts ins.Now we return to the puzzle. Each of the five digits is used a different number of times, which is tested by the predicate (= (length (unique = (sort < (map cdr s)))) 5). The counts have to be the same as the digits, which is tested by the predicate (equal? (unique = d) (unique = (sort < (map cdr s)))); the solution works if you omit that predicate, but I couldn't articulate a clear reason why, so I included it. Finally, no digit may be used its own number of times, which is tested by the

`ok?`

function:`(define (ok? s)`

(cond ((null? s) #t)

((= (caar s) (cdar s)) #f)

(else (ok? (cdr s)))))

At this point the list comprehension gives us seven remaining triplets:

`((12321 12544 55225 ((1 . 3) (2 . 5) (3 . 1) (4 . 2) (5 . 4)))`

(12321 33124 34225 ((1 . 3) (2 . 5) (3 . 4) (4 . 2) (5 . 1)))

(12321 44521 55225 ((1 . 3) (2 . 5) (3 . 1) (4 . 2) (5 . 4)))

(12321 52441 55225 ((1 . 3) (2 . 5) (3 . 1) (4 . 2) (5 . 4)))

(12544 34225 44521 ((1 . 2) (2 . 4) (3 . 1) (4 . 5) (5 . 3)))

(12544 34225 52441 ((1 . 2) (2 . 4) (3 . 1) (4 . 5) (5 . 3)))

(34225 44521 52441 ((1 . 2) (2 . 4) (3 . 1) (4 . 5) (5 . 3))))

I was going to invert the

`s`

matrix to determine the correct answer, but it is obvious by inspection that there is only one triplet where the digit used once is unique, and I am lazy. The solution to the puzzle is the triplet 111^{2}= 12321, 182^{2}= 33124, and 185^{2}= 34225.I used list comprehensions, digits, unique, uniq-c, and mappend from the Standard Prelude. You can run the program at http://programmingpraxis.codepad.org/ujS7gS9I.

Here’s a ruby version with some of the ideas from above incorporated. In a couple of places I use inject() to figure out if something is true for all elements of a hash. In this case inject() will return an array of two values (a pair) with the key the first element and the value as the second element. In both cases we initialize with “true” and then “and” with our test.

Here’s the results …

Solution: [12321, 12544, 55225] {“1″=>”3”, “2”=>”5″, “3”=>”1″, “5”=>”4″, “4”=>”2″}

Solution: [12321, 33124, 34225] {“1″=>”3”, “2”=>”5″, “3”=>”4″, “4”=>”2″, “5”=>”1″}

Solution: [12321, 44521, 55225] {“1″=>”3”, “2”=>”5″, “3”=>”1″, “4”=>”2″, “5”=>”4″}

Solution: [12321, 52441, 55225] {“1″=>”3”, “2”=>”5″, “3”=>”1″, “5”=>”4″, “4”=>”2″}

Solution: [12544, 34225, 44521] {“1″=>”2”, “2”=>”4″, “5”=>”3″, “4”=>”5″, “3”=>”1″}

Solution: [12544, 34225, 52441] {“1″=>”2”, “2”=>”4″, “5”=>”3″, “4”=>”5″, “3”=>”1″}

Solution: [34225, 44521, 52441] {“3″=>”1”, “4”=>”5″, “2”=>”4″, “5”=>”3″, “1”=>”2″}

Let’s see what Prolog looks like when formatted as lang=”css”.

It’s been many years since I used Prolog, but I installed

SWI-Prolog for this now and found its help system helpful.

I didn’t bother to find the least upper bound for the square

roots. It is easy to see that 300 is a safe choice. (I even

started at 99 instead of 100 to make the columns align.)

I got one constraint wrong at first – the one that each of the

five counts be used – and thought the unique single digit was 4.

After correcting that, the following interaction prints the

possible pairs of the single digit and the sequence of the

fifteen digits, from which the three numbers can be read.

@Jussi, Nice! I was thinking this would be a good Prolog problem as I was working on my version.

I love using Python’s built-in set() object to “uniquify” and also to compare if two sequences have the same stuff irrespective of order. And, as much fun as it to write an combination-generator, here I rely on the combinations() function from Python’s itertools library.

Yields the seven candidates from 217 possibilities:

Visual inspection shows 6 of these 7 candidates have the digit 3 occurring only once… so the last clue implies that the answer must be the set where that is not 1 of those 6:

(‘12321’, ‘33124’, ‘34225’)

Fun!

An uncommented Python version; I’ll put up a github gist later if people are interested.

My solution in vimscript:

I too found seven such numbers (and not one as specified).

Another optimization may be that none of the numbers can contain the zero digit (since no appearing number can appear zero times). That should cut down overall runtime a bit further.

12321 12544 55225

3 = 1

2 = 5

4 = 2

1 = 3

5 = 4

12321 33124 34225

3 = 4

2 = 5

4 = 2

1 = 3

5 = 1

12321 44521 55225

3 = 1

2 = 5

4 = 2

1 = 3

5 = 4

12321 52441 55225

3 = 1

2 = 5

4 = 2

1 = 3

5 = 4

12544 34225 44521

3 = 1

2 = 4

1 = 2

4 = 5

5 = 3

12544 34225 52441

3 = 1

2 = 4

1 = 2

4 = 5

5 = 3

34225 44521 52441

3 = 1

2 = 4

1 = 2

4 = 5

5 = 3

This Forth program is not very elegant, but it finds the single solution in about 0.7 seconds.