1  # Python 2.4.3  Hide words in square array
   2  # Author: Bob Cotton, released to the public domain
   3  import sys
   4  import random
   5  
   6  Words = ["QUICK", "BROWN", "FOX", "JUMPED", "OVER",
   7                  "THE", "LAZY", "DOG" ]
   8  
   9  # n is the length and width of the array of letters to be filled
  10  
  11  n = 9
  12  
  13  blankstring = ""
  14  for i in range(n):
  15          blankstring += " "
  16          
  17  square0 = [ ]
  18  for i in range(n):
  19          square0 = [ blankstring ] + square0
  20  
  21  directions = [(0,1),(-1,1),(-1,0),(-1,-1),(0,-1),(1,-1),(1,0),(1,1)]
  22  
  23  random1 = random.Random()
  24  
  25  def rand(k):                # Random function; returns zero or
  26                                  # a negative number > - arg
  27          return -random1.choice(range(k)) 
  28  
  29  def placeWord( k ):
  30          if k == 0:
  31                  return square0
  32          else:
  33                  prior = placeWord( k-1 )        # recursion
  34                  frow = rand(n)
  35                  fcol = rand(n)  
  36                  fdir = rand(8) 
  37                  for row in range( frow, frow + n):
  38                          for col in range( fcol, fcol + n):
  39                                  for dir in range( fdir, fdir + 8):
  40                                          square = isSafe( prior[:], k-1, row, col, dir) 
  41                                          if square != [ ]:
  42                                                  return square
  43          
  44          print "Attempt failed; k = ", k 
  45          for s in prior:
  46                  print s
  47          sys.exit();
  48  
  49  def isSafe( square, wordx, row, col, dir ):
  50          if row < 0:
  51                  row += n
  52          if col < 0:
  53                  col += n
  54                  
  55          word = Words[wordx]
  56          
  57          for i in range( len(word) ):
  58                  if row < 0 or row >= n or col < 0 or col >= n:
  59                          return [ ]  # Ran off edge of square
  60                  if square[row][col] == " ":
  61                          square[row] = ( square[row][0:col] + word[i] +
  62                                  square[row][col+1:n] ) # slicing
  63                  else:
  64                          if word[i] != square[row][col]:
  65                                  return [ ]  # Failed on clash
  66                  row += directions[dir][0]
  67                  col += directions[dir][1]
  68  
  69          return square
  70  
  71  ans = placeWord( len( Words ) )
  72  print "Success!"
  73  for s in ans:
  74          print s