linearize n-dimesionality
Hello forum,
I have the following code snippet that represent the 2D array in the linear manner .
1 2 3 4 5 6 7 8 9
|
int i, j;
for (i = 0; i < dy; i++) //height
{
for (j = 0; j < dx; j++) //width
{
p[i*dx+j] = (j+0.5f+(myrand() - 0.5f))/dx;
}
}
|
I am getting hard time to make it functional if add one more dimension in the following way:
1 2 3 4 5 6 7 8 9 10 11 12
|
int i, j, k;
for (i = 0; i < dy; i++) //height
{
for (j = 0; j < dx; j++) //width
{
for(k = 0; k < dz; k++)
{
p[HELP NEEDED HERE] = (j+0.5f+(myrand() - 0.5f))/dx;
}
}
}
|
Any help is greatly appreciated.
Regards
Sajjad
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
|
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const int dx = 2;
const int dy = 3;
const int dz = 5;
const int totalsize = dx * dy * dz;
int p[totalsize];
for (int i=0; i< totalsize; i++)
{
p[i] = i + 1;
}
for (int y = 0; y < dy; y++) // height
{
for (int x = 0; x < dx; x++) // width
{
for (int z = 0; z < dz; z++) // depth
{
int ix = z + x*dz + y*dz*dx;
cout << setw(5) << p[ix];
}
cout << endl;
}
cout << "---------------------------\n";
}
cout << "\n\n ...........................\n\n\n";
for (int z = 0; z < dz; z++) // depth
{
for (int y = 0; y < dy; y++) // height
{
for (int x = 0; x < dx; x++) // width
{
int ix = x + y*dx + z*dx*dy;
//int ix = z + x*dz + y*dz*dx;
cout << setw(5) << p[ix];
}
cout << endl;
}
cout << "------------\n";
}
return 0;
}
|
1 2 3 4 5
6 7 8 9 10
---------------------------
11 12 13 14 15
16 17 18 19 20
---------------------------
21 22 23 24 25
26 27 28 29 30
---------------------------
...........................
1 2
3 4
5 6
------------
7 8
9 10
11 12
------------
13 14
15 16
17 18
------------
19 20
21 22
23 24
------------
25 26
27 28
29 30
------------ |
Be careful about the relative order of x,y and z.
Try replacing line 47 with line 49 and see what happens.
If I was doing this, I'd encapsulate it inside a class, to make sure that the index was always correctly calculated.
Topic archived. No new replies allowed.