如何将一维索引转换为多维数组中的对应索引? [英] How to convert a monodimensional index to corresponding indices in a multidimensional array?
本文介绍了如何将一维索引转换为多维数组中的对应索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个3x4x5x6 Java双数组 a
,我可以通过以下方式将其展开为长度为360的ArrayList b
:
Say I have a 3x4x5x6 java double array a
that I unroll into an ArrayList b
of length 360 in the following way:
for (int i = 0; i<a.length; i++){
for (int j = 0; j<a[0].length; j++){
for (int k = 0; k<a[0][0].length; k++){
for (int m = 0; m<a[0][0][0].length; m++){
b.add(a[i][j][k][m]);
}
}
}
}
给定 b
的索引,有没有一种简单的方法可以在 a
中找到相应的四元组索引?
Given the index of b
, is there an easy way to find the corresponding 4-tuple of indices in a
?
推荐答案
假设
-
b
是一维数组上的索引 -
i,j,k,m
是多维数组上的四个结果索引 -
si,sj,sk,sm
是任意尺寸的大小
b
is the index on the monodimensional arrayi,j,k,m
are the four resulting indices on the multidimensional arraysi,sj,sk,sm
are the size of any dimension
您可以使用基本数学,应该是类似的
you can use basic math, it should be something like
-
m = b%sm
-
k =(b/sm)%sk
-
j =(b/(sm * sk))%sj
-
i = b/(sm * sk * sj)
基本上,对于所包含数组的每个大小(通过乘以大小),将每个索引加1,然后将其包装在其维度上.
Basically you increment every index by one for every size of the contained arrays (by multiplying sizes) and you wrap it on its dimension.
这篇关于如何将一维索引转换为多维数组中的对应索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文