While working on a recent gaming project, I was originally using
2D arrays to store information relating to the different levels
in the game. But when it came to loop through the contents of
these levels, it wasn't as straightforward to do a simple
foreach loop due to the multiple dimensions.
Instead, I changed the code so that the 2D data was stored in a
single dimension array. By using row-major order you can
calculate any position in 2D space and map it into the 1D array.
This then allows you to continue accessing the data using 2D
co-ordinates, but opens up 1D access too.
Defining your array
Given the size of your 2D array, the 1D creation code is
Converting 2D co-ordinates into 1D index
Once your have your array, converting a 2D co-ordinate such as
3, 4 into the correct index of your 1D array using row-major
order using the following formula:
Converting 1D index into 2D co-ordinates
The calculation to convert a 1D index into a 2D co-ordinate is
Putting it together - the ArrayMap<T> class
To avoid constantly having to repeat the calculations, I created
a generic ArrayMap class that I could use to store any data
type in a 1D array, and access the values using either indexes
or co-ordinates, as well as adding enumerable support. The class
is very straightforward to use:
Below is the full source to the class.
Currently I'm using this class without any problems, but if you
spot any errors or think it could do with anything else, please
let me know!
2012-04-11 - First published
2020-11-21 - Updated formatting
Like what you're reading? Perhaps you like to buy us a coffee?
The founder of Cyotek, Richard enjoys creating new blog content for the site. Much more though, he likes to develop programs, and can often found writing reams of code. A long term gamer, he has aspirations in one day creating an epic video game - but until that time comes, he is mostly content with adding new bugs to WebCopy and the other Cyotek products.