I have a 2d array with a different species in each one. I pick a random element on the array and I want to count up how many of each species are in the eight squares immediately adjacent to that element.
But I want the array to wrap at the edges, so if I pick an element on the top row, the bottom row will be counted as “adjacent”. How can I do this while iterating through j in range (x-1,x+1) and the same for j and y?
Also, is there a more elegant way of omitting the element I originally picked while looking through the adjacent squares than the if (j!=x or k!=y line?
numspec = [0] * len(allspec)
for i in range (0,len(allspec)):
#count up how many of species i there is in the immediate area
for j in range(x-1,x+1):
for k in range(y-1,y+1):
if (j!=x or k!=y):
numspec[hab[i][j]] = numspec[hab[i][j]]+1
As for wrapping, I would recomend using relative indexing from -1 to +1 and then computing real index using modulo operator (
%).As for making sure you don’t count the original element (x, y), you are doing just fine (I would probably use reversed contidion and continue, but it doesn’t matter).
I don’t quite understand your usage of
i, j, kindexes, so I’ll just assume thatiis index of the species,j, kare indexes into the 2d map calledhabwhich I changed tox_rel,y_relandx_idxandy_idxto make it more readable. If I’m mistaken, change the code or let me know.I also took the liberty of doing some minor fixes:
Nconstant representing number of speciesrangetoxrange(xrange is faster, uses less memory, etc)X = X + 1for increasing value, I used+=increment operator like this:X += 1Here is resulting code: