Using a linear array as a bidimensional matrix
Often times I find the need to use a list or linear array as if it was a table.
Everytime I need to do so, I always end up coding functions to convert a (x,y) coordinate to the real index n in the array.
Let me illustrate, with an example. You have a string that defines the elements of a game board, and you want to work using (x,y) coordinates.
s="xxxxx@xx@xxx@@xx"
If you were to look at it as a matrix (width=4), it’d be something like this
s="xxxx x@xx @xxx @@xx"
However, I can’t do
s[x,y], since it’s a linear array, it’s a string.
You need to convert from (x,y) to a number that represents an index in the array.
This is very simple:
width=4 def getNforXY(x,y): return x + width*y
What if you want to do it backwards. What if you need to know what’s the X and Y for a given index N in the string?
def getXYforN(n): y = int(n/width) x = n - width/y return (x,y)
Cheers












