Mapping of multidimensional array to a one-dimensional array
Question:
A
multidimensional array can be mapped to a one-dimensional array in two ways: In
one method, called row-major mapping, we store the multidimensional array row
by row. In the second method, called column-major mapping, we store it column
by column . For example, consider the following multidimensional array:
11 12 13
21 22 23
Its row-major
mapping is:
11 12 13 21 22 23
And
column-major is:
11 21 12 22 13 23
Now, given the
following array declaration in a pascal like language:
int
arr[l1..h1][l2..h2][l3..h3];
where l1,l2,
& l3 are lower indices and h1,h2, & h3 are upper indices, inclusive.
The memory is allocated in column-major fashion. Write the mapping formula
for arr[i][j][k] where l1 <= i <= h1, l2 <= j <= h2,
& l3 <= k <= h3. Assume all indices are non-negative.
Further help:
The first element can be referred by arr[l1][l2][l3] and the last by arr[h1][h2][h3]
SOLUTION:
An element at index position (i,j,k) is mapped to the
following index of the 1-D array:
(k-l3)*(h2-l2+1)*(h1-l1+1)
+
(j-l2)*(h1-l1+1)
+
(i-l1)
Comments
Post a Comment