1
2
3 import sys
4 import random
5
6 Words = ["QUICK", "BROWN", "FOX", "JUMPED", "OVER",
7 "THE", "LAZY", "DOG" ]
8
9
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):
26
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 )
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 [ ]
60 if square[row][col] == " ":
61 square[row] = ( square[row][0:col] + word[i] +
62 square[row][col+1:n] )
63 else:
64 if word[i] != square[row][col]:
65 return [ ]
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