views:

47

answers:

3

If I have a matrix that is iterated horizontally and then vertically it would enumerate like this:

    0  1  2  3  4  5  6  7  8  9
   ------------------------------
0 |  1  2  3  4  5  6  7  8  9 10
1 | 11 12 13 14 15 16 17 18 19 20
2 | 21 22 23 24 25 26 27 28 29 30

if I want to enumerate vertically I could do this:

  total_rows * coln+ rown+ 1

   0 1 2  3  4  5  6  7  8  9
  --------------------------
0 |1 4 7 10 13 16 19 22 25 28
1 |2 5 8 11 14 17 20 23 26 29
2 |3 6 9 12 15 18 21 24 27 30

anybody have the algorithm handy to enumerate grouped columns vertically?

    ????

    0  1  2  3  4  5  6  7  8  9
   ------------------------------
 0 |1  2  7  8 13 14 19 20 25 26
 1 |3  4  9 10 15 16 21 22 27 28
 2 |5  6 11 12 17 18 23 24 29 30
+1  A: 

Usually you iterate on a matrix with a nested loop

for (int i = 0; i < rows; ++i)
  for (int j = 0; j < cols; ++j)
    doSomething(matrix[i][j]);

This will enumerate rows, if you swap indices:

for (int i = 0; i < rows; ++i)
  for (int j = 0; j < cols; ++j)
    doSomething(matrix[j][i]);

Then you will enumerate by colums.

In your case you seem to have a matrix that is stored as a plain array so you can get from the two loops which is your addressing function, normal row access is (x/row_size)*row_size + x%row_size, so you iterate row_size elements before switching to the next row.

If you change it slightly: (x%col_size)*row_size + x/col_size you obtain a function that ad every iteration adds row_size (reching nth row) and then a value that is increased every col_size elements (so every time you finish a column). This should work..

EDIT: Oh wait missed that grouping factor, let me update my answer.. you can do something like

assert (cols % n == 0); /* we don't like not precise matrices */
for (int i = 0; i < cols / n; ++i)
  for (int j = 0; j < rows; ++j)
    for (int k = 0; k < n; ++n)
      doSomething(matrix[j][i+k]);

Or in plain array style:

(x%n) + row_size*(x/n) + (x / (col_size*n))*n
  ^          ^                  ^
  |          |                  |
  |          |               reposition after a group of columns
  |         moves vertically in the same group
 moves horizontally on the group

where n is the number of columns per group

Jack
+1  A: 

Something like this perhaps?

for(group = 0; group < maxCol/2; group += 2)
{
    for(row = group; row < maxRows; row++)
    {
        for(col = 0; col < group + 2; col++)
        {
            matrix[col][row];
        }
    }
}

This was fun to think about ^_^

Jesse J
+2  A: 
cols_per_group=2;

(total_rows*cols_per_group)*((int)(coln/cols_per_group))
+(coln%cols_per_group)+cols_per_group*rown +1

i.e. (total size of group)*(which group you're in) + (horizontal position in group) + (width of group) * (vertical position in group) +1

Sanjay Manohar
Since I don't specifically control the order that the columns are fired I believe this is the safest solution. Just what I was hoping for.
ebt