Backtracking

Posted by s on Nov. 24, 2008, 11:15 p.m.

Spent a day with beautiful Python. Breath of fresh air

[8, 0, 0, 0, 0, 0, 0, 0]

[1, 1, 0, 0, 8, 0, 0, 0]

[1, 0, 1, 1, 1, 1, 0, 8]

[1, 0, 1, 1, 1, 8, 1, 1]

[1, 1, 8, 0, 1, 1, 1, 1]

[1, 1, 1, 1, 1, 1, 8, 1]

[1, 8, 1, 1, 1, 1, 1, 1]

[1, 1, 1, 8, 1, 1, 1, 1]

113 iterations got this 8queens solution (It actually finds a solution to a 10queens problem in a shorter time)

def array(x):

. y=0

. X=xrange

. for a in x:y=[y for _ in X(a)]

. return y

def echo(x):return map(echo,x) if type(x[0])==list else x[:]

def plist(x):

. if type(x[0])==list:map(plist,x)

. else:print x

Z=0

def solve(x,y=0):

. global Z

. Z+=1

. if y==len(x):return x

. for a in xrange(len(x[0])):

. . if not x[y][a]:

. . . X=echo(x)

. . . X[y][a]=8

. . . for b in xrange(y+1,len(X)):

. . . . X[b][a]=1

. . . . if a+(b-y)<len(X[0]):X[b][a+(b-y)]=1

. . . . if a-(b-y)>-1:X[b][a-(b-y)]=1

. . . s=solve(X,y+1)

. . . if s:return s

plist(solve(array([8,8])))

print Z

I need to learn to not always do depthfirst

Thinking of trying it with more than 2D

Spent some time working with array() as a substitute for the bugged [[0]*8]*8. A one liner with reduce was half a second slower with 10000 trials of array(range(10)) and X=xrange decreases time to 95%

I'll be adding echo, array and plist to antigravity

[quote=Anyways, I'm still brewing over the message I shot off weeks ago. Something really resonated with me, probably because the source was of a book which resonated with me]I'm sick of being told I'm going to amount to something or nothing. It all seems so mixed like people don't know what to think

Now then, have an NxN queen iteration count list. Kinda neat how it goes up and down. No recursion max is going to be hit, since the stack is always below N

0 0

1 1

2 2

3 5

4 8

5 5

6 31

7 9

8 113

9 41

10 102

11 52

12 261

13 111

14 1899

15 1359

16 10052

17 5374

18 41299

19 2545

20 199635

21 8562

22 1737188

23 25428

24 411608

25 48683

26 397699

27 454213

28 3006298

29 1532239

Comments