arrays - How to convert an index into N coordinates? -
in 1 dimensional space:
x =
in 2 dimensional space (of size sx, sy):
x = / sx y = % sx
in 3 dimensional space (of size sx, sy, sz):
x = / (sy*sz) y = (i/sz) % sy z = % sz
how deal n dimensional space? how can these formulas generalized?
what inverse conversion?
(x1, x2, ..., xn) -->
note: variables integer.
i guess common formulas looks like:
to check formulas used programs , looks works.
#include <iostream> #include <string> #include <string.h> #define sz1 2 #define sz2 3 #define sz3 4 #define sz4 5 using namespace std; int main() { int a[sz4][sz3][sz2][sz1]; int i,j,k,l,n,x1,x2,x3,x4,s1,s2,s3,s4; s1=sz1;s2=sz2;s3=sz3,s4=sz4; memset(a,0,sizeof(a)); (i=0;i<s1*s2*s3*s4;i++){ x4= i/(s1*s2*s3); x3 = / (s1*s2) % s3; x2 = (i/s1) % s2; x1 = % s1; a[x4][x3][x2][x1]=i; } (l=0;l<sz4;l++) { (i=0;i<sz3;i++) { for(j=0;j<sz2;j++) { for(k=0;k<sz1;k++) { n=s1*s2*s3*l+s1*s2*i+s1*j+k;//inverse convertion cout<<a[l][i][j][k]<<"{"<<n<<"} "; } cout<<"|"; } cout<<endl; } cout<<endl<<endl; } return 0; }
Comments
Post a Comment