c# - 在一个循环中循环多维数组
问题描述
想象有一个包含 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 列的多维数组上!即,给定的预期结果,即我们在每列中具有相同的 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 列时,我无法想出一个公式。有没有办法在一个循环中循环这样的数组?
解决方案
当然可以,试试这个 Java 代码:
int columnCount = 3;
int eachColumnElementCount = 800;
int totalCombinationCount = (int)Math.pow(eachColumnElementCount, columnCount); // 800*800*800
for(int i = 0; i < totalCombinationCount ; i++) {
int column1Index= i % eachColumnElementCount;
int column2Index= i / eachColumnElementCount % eachColumnElementCount ;
int column3Index= i / eachColumnElementCount / eachColumnElementCount ;
System.out.println(column3Index+","+column2Index+","+column1Index);
}
推荐阅读
- python - 带有按钮和框架的 grid() 位置 - Tkinter(需要帮助)
- python - 日期偏移 Pandas 字段基于另一个字段
- php - 从 Laravel 的存储中检索多个文件(图像)
- wcf - 如何为 wcf 服务创建 https 绑定?
- sql - 主键不会自动递增
- python - 需要一些帮助使函数尾递归
- elixir - 是否可以通过“use/2”宏(用于 DRY)扩展 Elixir 协议?
- akka-http - akka http:服务器绑定未按预期运行
- python - 如何在 Django 中启动和停止 celery beat 和 worker?
- amazon-web-services - AWS - Java Lambda - 将数据从 s3 移动到 redshift