【问题标题】:enumerate grouped columns vertically垂直枚举分组列
【发布时间】:2010-07-15 00:05:10
【问题描述】:

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

    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

【问题讨论】:

    标签: java algorithm math matrix


    【解决方案1】:
    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】:

    大概是这样的吧?

    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】:

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

      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你会得到一个函数,每次迭代都会增加一个函数row_size(reching nth row),然后每个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 是每组的列数

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-23
        • 1970-01-01
        • 2016-04-03
        • 1970-01-01
        • 2010-12-10
        相关资源
        最近更新 更多