【发布时间】:2018-07-14 10:07:01
【问题描述】:
想象有一个包含 2 列的多维数组,每列具有完全相同的元素数:
int[,] virtualArray = new int[800,2];
如果我要在单个循环中迭代这样的数组 - 我会做类似的事情:
int columnCount = 2;
int eachColumnElementCount = 800;
int totalCombinationCount = Convert.ToInt32(Math.Pow(eachColumnElementCount, columnCount)); // 640_000
for(int i = 0; i < totalCombinationCount ; i++) {
int columnOneIndex= index / totalCombinationCount ;
int columnTwoIndex= index - totalCombinationCount * eachColumnElementCount;
}
结果将是:
0,0 (i = 0)
0,1
..
0,799 (i = 799)
1,0 (i = 800)
1,1
..
1,799
..
799,799 (i = 640_000 - 1)
现在,我想扩展我当前的实现,在一个单维循环中迭代——在一个具有 3 列的多维数组上! IE。假设我们在每列中有相同的 800 个元素计数,预期结果应如下:
int[,] virtualArray = new int[800,3];
int columnCount = 3;
int eachColumnElementCount = 800;
int totalCombinationCount = Convert.ToInt32(Math.Pow(eachColumnElementCount, columnCount)); // 512_000_000
for(int i = 0; i < totalCombinationCount ; i++) {
// int index1 = 0; // ??
// int index2 = 0; // ??
// int index3 = 0; // ??
}
0,0,0 (i = 0)
0,0,1
...
0,0,799
...
10,80,156
...
799,799,799 (i = 512_000_000 - 1)
对于有 3 列的情况,我无法想出一个公式。有没有办法在一个循环中循环这样的数组?
【问题讨论】:
-
我不明白您为什么要多次迭代相同的元素。只有 2*800 = 1,600 个元素,但您正在迭代 640,000 次。因此,您会多次访问每个元素。
-
您需要第二个循环...因为您需要遍历列
-
@MatthewWatson 这是个好问题。我的最终目标是遍历所有可能的值组合。仅仅从数组中获取必要的元素是不够的。就像你说的那样——总共只有 1600 个元素,但是这 1600 个元素可以创建 640000 个独特的组合。
-
啊,所以你想要的是每列中一个元素的每个组合。
标签: c# arrays multidimensional-array