我需要遍历一个n维数组。该数组是从另一个函数构建和传递的,并且维数事先未知。这需要使用类似于 VBA 的原始语言来完成。所以,不存在 Python 的优点。
有谁知道如何实现这一点吗?
示例数组可能类似于 5 x 6 x 1 x 8 数组。因此,它是一个 4 维数组,维度 1=5、维度 2=6、维度 3=1 和维度 4=8。
我需要遍历 5*6*1*8= 240 个元素中的每一个,并以某种方式记录我的结果,以便我可以将我的结果与元素联系起来。
编辑:为了更清楚地说明,在遍历结束时,我希望能够说位置 (2,3,1,5) 处的元素是 x。因此,我需要记录元素在数组中的位置以及元素本身。
所讨论的数组更像是这样的
`全局多数组作为变体
'\现在,许多其他函数,当找到符合条件的候选者时,将数组添加到此数组'\如下所示。
Redim 多数组(len(multiArray)+1) multiArray(len(multiarray))= newElementArray()
` 所以,我最终得到如下所示的结果。只是尺寸会在运行时改变,所以,我需要一个通用逻辑来遍历它。
最佳答案
让一个坐标
表示n维数组中元素的位置。例如 (2,1,3,4)
对应于以下位置的元素:array[2][1][3][4]
。
var array = // n-dimensional
function traverse(array, coordinate, dimension);
for(var i = 0 ; i < array.length ; i++){
// assuming coordinate is immutable. Append the current iteration's index.
currentCoordinate = coordinate.add(i);
if(dimension == 1){
doSomething(currentCoordinate, array[i]);
}else{
traverse(array[i], currentCoordinate, dimension(array[i]));
}
}
}
coordinate = []; // at first, the top level coordinate is empty.
traverse(array, coordinate, 4); // 4-dimensional
关于algorithm - 当维度可变时遍历 n 维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11768120/