Two Dimensions, One Dimension
Reference > Science > Technology > Beginner Programming TipsLet's say you have a two-dimensional array: MyArray(9,9). That's an array with 100 elements; starting with MyArray(0,0), all the way to MyArray(9,9) and everything in between. Suppose you wanted to treat the elements of this array as a one-dimensional array. In other words, you wanted to think of the array like this:
Element #0: MyArray(0,0) Element #1: MyArray(0,1) Element #2: MyArray(0,2) ... Element #9: MyArray(0,9) Element #10: MyArray(1,0) Element #11: MyArray(1,1) ... Element #97: MyArray(9,7) Element #98: MyArray(9,8) Element #98: MyArray(9,9)
This is a situation you may run into from time to time, and it's good to be able to "walk through" a two-dimensional array, assigning a one-dimensional index to each element. Now, for this example, I've picked something easy, because you'll notice that the ones and tens places of the one-dimensional index correspond to the X and Y dimensions of the two-dimensional indices. What's the one-dimensional index for MyArray(7,8)? It's easy! Put the 7 and the 8 together, and you've got Element #78.
But we need to express that mathematically, so the computer can understand it.
What is the "tens" place of a number? The tens place tells you "how many tens" are in a number. For example, the number 78 is "seven tens and eight more", or 7 x 10 + 8. Great! That tells us how to create our one-dimensional index! Check this out:
Dim X As Integer
Dim Y As Integer
'Get the one-dimensional index
Public Function ArrayIndex(Y As Integer, X As
Integer)
ArrayIndex = (Y * 10) + X
End Function
That's it! Notice that I put the line of code inside a function. This is because I'll probably be using that line of code a lot, and I don't want to have to keep rewriting it over and over again. Plus, if I ever change the array to different dimensions, like maybe a 20x20 array, I would need to change the code, and having it inside a function means I only have to change it in one place.
Speaking of different dimensions, let's suppose MyArray now is a 7x7 array. How does that change our code? Well, that changes it just a little bit:
Dim X As Integer
Dim Y As Integer
'Get the one-dimensional index
Public Function ArrayIndex(Y As Integer, X As
Integer)
ArrayIndex = (Y * 7) + X
End Function
Easy, right? In my next tip, I'll talk about how to reverse the process and convert a one dimensional array index into a two dimensional array index.