Enigmatic Code

Programming Enigma Puzzles

Enigma 1441: The missing link

From New Scientist #2602, 5th May 2007

I sent in the Enigma below, and it was accepted for publication.

Enigma 1441

Unfortunately in the meantime the digit that should have been printed in the shaded square has become smudged and is illegible. However, that should not stop you doing the puzzle. Please send in the intended answer to the original puzzle: “Fill in each of the empty spaces with a non-zero digit so that the rows, columns and main diagonals add up to the totals shown”.

[enigma1441]

Advertisements

One response to “Enigma 1441: The missing link

  1. Jim Randell 14 April 2013 at 9:20 am

    This Python program runs in 46ms.

    # consider the square as:
    #
    #  a b c d
    #  e f g h
    #  i j k m
    #  n p q r
    
    from collections import defaultdict
    from enigma import chunk
    
    # decompose the number <n> into <p> non-zero digits
    def decompose(n, p):
      if n < 1:
        pass
      elif p == 1:
        if 0 < n < 10: yield [n]
      else:
        for i in range(1, min(n, 9)):
          for j in decompose(n - i, p - 1):
            yield [i] + j
    
    # collect solutions
    s = defaultdict(list)
    
    # initial squares
    (a, h, j) = (1, 3, 7)
    
    # row 2
    for (e, f, g) in decompose(8 - h, 3):
      # reverse diagonal
      for (k, r) in decompose(9 - (a + f), 2):
        # row 3
        for (i, m) in decompose(20 - (j + k), 2):
          # column 4
          d = 15 - (h + m + r)
          if not(0 < d < 10): continue
          # column 1
          n = 20 - (a + e + i)
          if not(0 < n < 10): continue
          # forward diagonal
          if not(n + j + g + d == 20): continue
          # row 1
          for (b, c) in decompose(15 - (a + d), 2):
            # column 2
            p = 22 - (b + f + j)
            if not(0 < p < 10): continue
            # column 3
            q = 15 - (c + g + k)
            if not(0 < q < 10): continue
            # row 4
            if not(n + p + q + r == 29): continue
    
            # accumulate the results by q (the smudged square)
            s[q].append((a, b, c, d, e, f, g, h, i, j, k, m, n, p, q, r))
    
    # find unique values for q
    for (k, v) in s.items():
      if len(v) > 1: continue
      print(tuple(chunk(v[0], 4)))
    

    Solution: The completed grid is:

    1 5 7 2
    2 1 2 3
    8 7 1 4
    9 9 5 6

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: