DEV Community

Lori-Shu
Lori-Shu

Posted on

Position Calculations in Two-Dimensional Arrays

I keep falling into the same trap: coordinate calculations. I'm here to record some of the lessons with possible solutions which could solve or relieve some of the traps.

Firstly, how do we choose the coordinate axes? When we take math classes, professors often draw the x- and y-axes with the origin located at the bottom-left corner; x goes right and y goes up. This is intuitive but we need to switch our mindset when we are in programming. We still consider a two-dimensional array in such axes only if we can fit the dimensions. For example, an array a[3][4] has three elements in the first dimension and four elements in the second dimension. If we view it as a 3×4 array, the first dimension is mapped to x while the second dimension is mapped to y. If we view it as a 4×3 array, the first dimension is mapped to y while the second dimension is mapped to x. Either layout is valid only if it remains consistent with that mapping. After fixing the axes, we should consistently follow the same mapping whenever we access the array. In order to make the variables more readable, sometimes we use names like "row" or "col". Never mix "x/y" and "row/column" terminology. Just pick one. The code tends to become a disaster when I mix them together.

Secondly, how do we calculate a point from other points? In many cases, we determine the position of a point through linear combination of other points. For example, the midpoint between two points is given by 〖(pos〗_2+〖pos〗_1)/2. However, when pos1 is the origin, I often neglect it in subsequent calculations, leading to incorrect results. To avoid that, we should understand the position formula and the idea of relative position. Every coordinate is ultimately defined relative to the chosen origin. However, when we calculate the middle point between two points, the midpoint is defined relative to the two endpoints rather than the origin.

Insight: Handling dimension mappings and relative positions is a common source of bugs in programming. I hope that "Be consistent with the coordinate system you have chosen." and "Understand what a formula actually represents geometrically." will not bother me again in the future.

Top comments (0)