我必须编写一个函数,该函数接收整数X(线性化位置的值)和包含多维数组维的数组,并且必须将多维位置X的元素的坐标保存在第二个数组中参考系统。例如:
X = 2和array [] = {A,B},在此示例中,数组包含2D矩阵的维度(A,B)。因此在2D参考系统中的位置是:
知道:X = x * B + y ----> x = X / B和y = X%B ----> position [] = {x,y};
因此将X分解为x和y很简单,因为这是2D矩阵的平常情况,但是我的程序必须处理N维矩阵(因此,它必须将X分解为x,y,..... 。,n)。
我的想法是应用我已经展示的算法,但是即使我找不到能处理通用N维矩阵的C代码(我也尝试编写递归函数但没有成功)。
有人可以找到解决这个问题的方法吗? (先感谢您!!!)
我是初学者!!!
最佳答案
如果您有一个DIM2 [X,Y]数组,其维度为Xn和Yn,则也可以将此表示为一个二元数组。
然后将A [x,y]映射到DIM1 [x + y * Xn]
DIM1必须具有大小(Xn * Yn)
尺寸为Xn,Yn,Zn的3维数组B []可以通过以下方式映射:
B [x,y,z]会映射到DIM1 [x + y * Xn + z * Xn * Yn],DIM1必须能够容纳(Xn * Yn * Zn)个项,
B [x,y,z,a]将映射到DIM1 [x + y * Xn + z * Xn * Yn + a * Xn * Yn *
锌]
等等
对于一般的N维数组,最好是递归,其中100维数组是99维数组。如果所有的尺寸都有相同的大小,那将是相对简单的(编写它,我还提到了递归可以很容易地展开为一个简单的for循环,请在下面找到它)
#include <stdio.h>
#include <math.h>
#include <malloc.h>
#define max_depth 5 /* 5 dimensions */
#define size 10 /* array[10] of array */
// recursive part, do not use this one
int _getValue( int *base, int offset, int current, int *coords) {
if (--current)
return _getValue (base + *coords*offset, offset/size, current, coords+1);
return base[*coords];
}
// recursive part, do not use this one
void _setValue( int *base, int offset, int current, int *coords, int newVal) {
if (--current)
_setValue (base + *coords*offset, offset/size, current, coords+1, newVal);
base[*coords]=newVal;
}
// getValue: read item
int getValue( int *base, int *coords) {
int offset=pow( size, max_depth-1); /* amount of ints to skip for first dimension */
return (_getValue (base, offset, max_depth, coords));
}
// setValue: set an item
void setValue( int *base, int *coords, int newVal) {
int offset=pow( size, max_depth-1);
_setValue (base, offset, max_depth, coords, newVal);
}
int main() {
int items_needed = pow( size, max_depth);
printf ("allocating room for %i items\n", items_needed);
int *dataholder = (int *) malloc(items_needed*sizeof(int));
if (!dataholder) {
fprintf (stderr,"out of memory\n");
return 1;
}
int coords1[5] = { 3,1,2,1,1 }; // access member [3,1,2,1,1]
setValue(dataholder, coords1, 4711);
int coords2[5] = { 3,1,0,4,2 };
int x = getValue(dataholder, coords2);
int coords3[5] = { 9,7,5,3,9 };
/* or: access without recursion: */
int i, posX = 0; // position of the wanted integer
int skip = pow( size, max_depth-1); // amount of integers to be skipped for "pick"ing array
for (i=0;i<max_depth; i++) {
posX += coords3[i] * skip; // use array according to current coordinate
skip /= size; // calculate next dimension's size
}
x = dataholder[posX];
return x;
}