Is the operation $i = x + y * \text{width}$ reversible?

161 Views Asked by At

In game programming, there is this very common operation we do to index positions in a two-dimensional matrix over a one-dimensional array. We basically associate the value $a_{xy}$ of some matrix $A$ with width $w$ to the index $i = x + y * w$ of the array. This image illustrates the overall concept, but it can be used for a myriad of other things: x + y * w demonstration

However, I was recently wondering whether this operation is reversible; that is, having an index in the array and the width of the matrix, is it possible to obtain the corresponding $(x,y)$?

From my experience with mathematics, I was under the impression that this operation is both injective (since, with a fixed width, every $(x,y)$ position has a single corresponding index), and surjective (since all indexes were generated from at least one position). Nevertheless, I was unable to come up with an inverse of this transformation that didn't result in x being dependent on the y or vice-versa.

1

There are 1 best solutions below

3
On BEST ANSWER

Mathematically we have (assuming that $w > 0$ and $x, y \ge 0$ are integers) $$ i \bmod w = (x + y \cdot w) \bmod w = x \bmod w = x $$ because $x$ is in the range $0, \ldots, w-1$, and $$ w \cdot y \le i \le w \cdot y + w - 1 < w \cdot (y+1)\\ \implies y \le \frac iw < y+1 \implies y = \left\lfloor \frac iw \right\rfloor \, . $$

In many programming languages this can be computed as

x = i % w  # remainder operator
y = i / w  # truncating integer division