受arr2D[i][j]
和启发arr1D[i * k + j]
,我想知道一种可以更改任何数组尺寸的算法。
让我尝试将其形式化:
输入:
一M
维容器A
尺寸D
容器(尺寸)
目标尺寸 N
输出:
如果是,N > 0
则返回B
内容与A
顺序相同的N维容器,否则返回错误代码。
注意:
您可以为N维容器选择任何最佳尺寸。
I would understand a C++ or C code better than an algorithm or a code in some other language. But you may help my curiosity in any language as long as it is comprehensible in English :P
Edit:
I don't need any fully working code. I'm just asking for ways to approach this problem. Thanks in advance for any good ideas.
So you just want to reformat your matrices while no data is changed. As I hinted in my comment the simplest is to use 1D array mid step for converting from M to N dimensions.
The other answers here are on the same track but are lacking the whole math ... they have just examples up to some small dimension without universal equation so here it is:
要在容器的尺寸大小(分辨率)之间A[A0][A1]...[A(M-1)]
以及X[A0*A1*...*A(M-1)]
哪里A0,A1,...A(M-1)
进行转换,只需执行以下操作:
// M-D -> 1D
x = a0
+a1*A0
+a2*A0*A1
...
+a(M-1)*A0*A1*...*A(M-2);
// 1D -> M-D
q=x;
a0 = q%A0; q/=A0;
a1 = q%A1; q/=A1;
a2 = q%A2; q/=A2;
...
a(M-1) = q%A(M-1); q/=A(M-1);
其中a0,a1,...a(M-1)
和x
是数组中的索引。
实际上,您实际上不需要将MD数组转换为1D,然后又回到ND,足以将索引转换为:
for (a0=0;a0<A0;a0++)
for (a1=0;a1<A1;a1++)
...
for (a(M-1)=0;a(M-1)<A(M-1);a(M-1)++)
{
// M-D -> 1D
x = a0
+a1*A0
+a2*A0*A1
...
+a(M-1)*A0*A1*...*A(M-2);
// 1D -> N-D
q=x;
b0 = q%B0; q/=B0;
b1 = q%B1; q/=B1;
b2 = q%B2; q/=B2;
...
b(N-1) = q%B(N-1); q/=B(N-1);
// copy A -> B
B[b0][b1]...[b(N-1)] = A[A0][A1]...[A(M-1)];
}
不要忘记大小必须是:
A0*A1*...*A(M-1) <= B0*B1*...*B(N-1)
否则您将无法访问数组,因为其中的数据A
将不适合B
。
如果您具有动态尺寸,则可以使用:
对于公式及其实现,这是一个很好的答案。我留下了反对意见。
哇,我没有看到动态嵌套的for循环。看起来很有趣!