Enigmatic Code

Programming Enigma Puzzles

Enigma 1584: Trisquare

From New Scientist #2749, 27th February 2010 [link]

I invite you to place a digit in each of the nine spaces in a 3 × 3 array so that each digit occurs its own number of times (e.g. if 3 occurs it must occur exactly three times). You can then read eight numbers: three across, three down, and two diagonals read from the top down.

What will be the sum of all the digits used if all these numbers are different and the sum cannot be written using digits from the square?

[enigma1584]

Advertisements

One response to “Enigma 1584: Trisquare

  1. jimrandell 31 January 2012 at 11:57 am

    Make sure you keep the distinction clear between the “digits” and the “numbers”.

    The following Python program runs in 481ms to find all possible squares.

    from itertools import permutations
    from enigma import irange, concat, split
    
    # generate n numbers such that each number occurs its own number of times
    def generate(n, m=1):
      if n == 0:
        yield []
      else:
        for i in irange(m, n):
          for j in generate(n - i, i + 1):
            yield [i] * i + j
        
    
    # fit the numbers into a square with the required properties
    def solve(s):
      # sum the digits
      t = sum(s)
      # (at least) one of the digits of the sum must not occur in s
      if set(split(t, int)).issubset(s): return 0
    
      done = 0
      for (a, b, c, d, e, f, g, h, i) in set(permutations(s)):
    
        # the numbers in the lines should be distinct
        lines = list(map(lambda x: int(concat(*x)), (
          (a, b, c), (d, e, f), (g, h, i),
          (a, d, g), (b, e, h), (c, f, i),
          (a, e, i), (c, e, g)
        )))
        if len(set(lines)) != 8: continue
    
        # we only need one example, but lets output all possibles
        print(sorted(lines))
        done = t
    
      return done
    
    
    for s in generate(9):
      t = solve(s)
      if t: print(t, s)
    

    Solution: The sum of the digits in the square is 29.

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: