0

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?

Community
  • 1
  • 1
M.kazem Akhgary
  • 18,645
  • 8
  • 57
  • 118
  • 1
    The column number increases by 1 after every column, i.e. every 8 entries, so you need `col = index / 8`. – Lynn Sep 01 '15 at 05:27

1 Answers1

2

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
dave
  • 11,641
  • 5
  • 47
  • 65