Reputation: 1177
I was tasked with calculating all the potential positions a knight can take, when starting at (0,0). I am a beginner so my code is clunky, but it seems to work for a smaller set of iterations. As soon as I get 8-9 steps deep, I run out of memory.
def moves(pos):
re=[[]]
for i in range(0,len(pos)):
x,y=pos[i]
a=[x+2,y+1]
b=[x+2,y-1]
c=[x-2,y+1]
d=[x-2,y-1]
e=[x+1,y+2]
f=[x+1,y-2]
g=[x-1,y+2]
h=[x-1,y-2]
re.append(a)
re.append(b)
re.append(c)
re.append(d)
re.append(e)
re.append(f)
re.append(g)
re.append(h)
del re[0]
return re
def clean(a):
cmoves=[]
for i in range(0,len(a)):
if a[i][0]>-1 and a[i][1]>-1 and a[i][0]<9 and a[i][1]<9 :
cmoves.append(a[i])
return cmoves
def comb(a):
return clean(moves(a))
pos= [[0,0]]
a=comb(res)
steps_count=10
for step in range(steps_count):
res=comb(res)
Any help or tip is highly appreciated, thank you.
Upvotes: 1
Views: 60
Reputation: 117771
In clean
, also remove duplicate positions. You can use a set
to keep track of which positions you've seen before, if you convert the coordinates to use tuple
s instead of list
s.
Upvotes: 5