# 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.

[python]
s="xxxxx@xx@xxx@@xx"
[/python]

If you were to look at it as a matrix (width=4), it’d be something like this
[python]
s="xxxx
x@xx
@xxx
@@xx"
[/python]

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:
[python]
width=4
def getNforXY(x,y):
return x + width*y
[/python]

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?

[python]
def getXYforN(n):
y = int(n/width)
x = n – width/y
return (x,y)
[/python]

Cheers

This site uses Akismet to reduce spam. Learn how your comment data is processed.