M.kazem Akhgary
M.kazem Akhgary

Reputation: 19149

How do I convert a 1-D index into a 2-D index

I have a 2-D array and I want to access its elements with a 1-D index.

the array length varies. row varies but col is always 8(Array[varies, 8])

Looking at this question and its answers , it seems I can't access elements correctly.

This is how I want to access elements with one index:

0 = (0, 0)        8 = (1, 0)        16 = (2, 0)
1 = (0, 1)        9 = (1, 1)        17 = (2, 1)
2 = (0, 2)        10 = (1, 2)       18 = (2, 2)
3 = (0, 3)        11 = (1, 3)       19 = (2, 3)
4 = (0, 4)        12 = (1, 4)       20 = (2, 4)
5 = (0, 5)        13 = (1, 5)       21 = (2, 5)
6 = (0, 6)        14 = (1, 6)       22 = (2, 6)
7 = (0, 7)        15 = (1, 7)       23 = (2, 7)

In this example my array is 3x8. According to the formula:

row = index % 8;
col = index / 3;

Say for index 13 it will be:

row = 13 % 8 = 5 >> correct
col = 13 / 3 = 4 >> incorrect

So what am i missing here?

Upvotes: 0

Views: 175

Answers (1)

dave
dave

Reputation: 11975

Try the following:

col = index / 8

You should use the same divisor (in this case, 8) for both the mod and the div. That way, they are in synch.

In your example,

col = 13 / 8 = 1

Upvotes: 2

Related Questions