Given a grid where I know the number of rows (which is fixed), and I know the current count of columns (which can grow arbitrarily), how do I calculate the row and column of an square from it's index?
+ + + + +
Cols ---> | 0 | 1 | 2 | 3 | ...
+--+---|---|---|---|---
0 | 0 | 3 | 6 | 9 | ...
+--+---|---|---|---|---
Rows 1 | 1 | 4 | 7 | A | ...
+--+---|---|---|---|---
2 | 2 | 5 | 8 | B | ...
+--+---|---|---|---|---
. . . . . ...
. . . . . .
. . . . . .
So, given:
final int mRowCount = /* something */;
int mColCount;
And given some function:
private void func(int index) {
int row = index % mRowCount;
int col = ???
How do I correctly calculate col
? It must be a function of both the number of columns and rows, I'm pretty sure. But my brain is failing me.
Sample: If index == 4
, then row = 1
, col = 1
. If index == 2
then row = 2
, col = 0
.
Thanks.
Didn't really understand your setup but if you got a normal grid with a progressive index like in the Android GridLayout
:
+-------------------+
| 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|
| 5 | 6 | 7 | 8 | 9 |
|---|---|---|---|---|
| 10| 11| 12| 13| 14|
|---|---|---|---|---|
| 15| 16| 17| 18| 19|
+-------------------+
The calculation is:
int col = index % colCount;
int row = index / colCount;
For example:
row of index 6 = 6 / 5 = 1
column of index 12 = 12 % 5 = 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With