代码之家  ›  专栏  ›  技术社区  ›  ebt

垂直枚举分组列

  •  0
  • ebt  · 技术社区  · 14 年前

    如果我有一个水平迭代然后垂直迭代的矩阵,它会像这样枚举:

        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
    

    如果我想垂直枚举,我可以这样做:

      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
    

    有人有算法可以方便地垂直枚举分组列吗?

        ????
    
        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
    
    3 回复  |  直到 14 年前
        1
  •  2
  •   Sanjay Manohar    14 年前
    cols_per_group=2;
    
    (total_rows*cols_per_group)*((int)(coln/cols_per_group))
    +(coln%cols_per_group)+cols_per_group*rown +1
    

    即(组的总大小)*(您所在的组) +(组中的水平位置)+(组的宽度)*(组中的垂直位置)+1

        2
  •  1
  •   Jesse Jashinsky    14 年前

    也许是这样?

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

    想起来很有趣^^

        3
  •  1
  •   Jack    14 年前

    通常使用嵌套循环迭代矩阵

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

    如果交换索引,这将枚举行:

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

    然后你将用列数数。

    在您的例子中,似乎有一个矩阵存储为一个普通数组,这样您就可以从寻址函数的两个循环中获得,正常的行访问是 (x/row_size)*row_size + x%row_size ,所以你迭代 row_size 元素,然后切换到下一行。

    如果稍微改变一下: (x%col_size)*row_size + x/col_size 你得到了一个每次迭代都会添加的函数 行大小 (重新计算第n行),然后每增加一个值 col_size 元素(所以每次完成列时)。这应该有效。

    编辑:哦,等等,错过了分组因素,让我更新我的答案。你可以做一些像

    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]);
    

    或以纯数组样式:

    (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
    

    哪里 n 是每组的列数