# Get position of tile in tileset

How can I get the position of tile 14 (or any other) when only knowing the following:
Tile ID: 14
Rows: 4
Columns: 7

The end result should be 2x4.

• Do consider waiting a while before accepting an answer, as there might appear a more correct and elaborated one. I'm not bitter, but I'm disappointed. – Lars Viklund Jul 28 '12 at 19:02
• Actually yes, Lars' answer was better :) – Mikael Högström Jul 30 '12 at 12:02

Column = TileID mod Rows
Row = TileID div Rows


so in most programming languages your example would be:

col = 14 % 4;
row = 14 / 4;


Such a bijective mapping is much easier to express if your tile indices and rows/columns are zero-based.

col: 0  1  2  3
[  0  1  2  3  // row 0
4  5  6  7  // row 1
8  9 10 11  // row 2
12 13 14 15  // row 3
...


If you look at the column numbers, as the column number increases by one, so does the tile index. More particularly, there's a pattern that for each row, it starts on a multiple of the row width, and increases by one.

This means that if we could get rid of that term, we would have our column number.

The modulus operator (commonly % in most languages) will take a number in a range [0,n) and map it to the values 0 through n-1, wrapping around.

That is, 7 % 4 == 3, 8 % 4 == 0, and so on.

A suitable expression for the column index is thus col = idx % width.

For the row, we need an expression that results in the same value for all values in the row. An operation related to modulus is division, so it's likely useful.

8/4 = 2, 9/4 = 2.25, 10/4 = 2.50, 11/4 = 2.75, which is almost what we want. We can feed the result of that into the floor() operation, which truncates away the fractional part of a floating point result, or in the case of integer division, it's already done for you.

So in summary:

zero_based_col =       zero_based_idx % row_width
zero_based_row = floor(zero_based_idx / row_width)

• Ahh right you are, didn't see it wasn't zero based :) – Mikael Högström Jul 28 '12 at 18:18