Enigmatic Code

Programming Enigma Puzzles

Enigma 113: What is the code word?

From New Scientist #1257, 11th June 1981 [link]

A code word consists of five letters, each letter being either X, Y or Z. Determine the code word with the following clues:

(1) The word X X Y Y Y contains three letters of the code word, but has only one letter in the correct location.
(2) The word Z Z X X X contains four letters of the code word and has only one letter in the correct location.
(3) The interchange of the letters Z and X in the second and third locations in the word of clue 2 does not change the number of letters in the correct locations.

[enigma113]

One response to “Enigma 113: What is the code word?

  1. Jim Randell 5 August 2013 at 9:22 am

    It’s easy to check all possible code words against the conditions. This Python program runs in 46ms.

    from itertools import product
    from collections import Counter
    from enigma import printf
    
    (X, Y, Z) = letters = 'XYZ'
    
    # count how many letters in common
    def count(c, w):
      return sum((c & Counter(w)).values())
    
    # count how many letters are in the same location
    def correct(w1, w2):
      return sum(1 for (a, b) in zip(w1, w2) if a == b)
    
    # generate code words
    for w in product(letters, repeat=5):
      # count the letters
      c = Counter(w)
    
      # 1. XXYYY contains 3 letters of the code word...
      w1 = 'XXYYY'
      if count(c, w1) != 3: continue
      # ... but has only 1 letter in the correct location
      if correct(w, w1) != 1: continue
    
      # 2. ZZXXX contains 4 letters of the code word...
      w2 = 'ZZXXX'
      if count(c, w2) != 4: continue
      # ... but has only 1 letter in the correct location
      if correct(w, w2) != 1: continue
    
      # 3. ZXZXX still only has 1 letter in the correct location
      w3 = 'ZXZXX'
      if correct(w, w3) != 1: continue
    
      printf("code word = {w}", w=' '.join(w))
    

    Solution: The code word is Y X X Z Z.

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: