in Code, Python

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.


If you were to look at it as a matrix (width=4), it’d be something like this

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:
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)


Write a Comment


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