28
4
Lower level languages, such as C and C++ actually have no concept of multidimensional arrays. (Other than vectors and dynamic arrays) When you create a multidimensional array with
int foo[5][10];
This is actually just syntactic sugar. What C really does is create a single contiguous array of 5 * 10 elements. This
foo[4][2]
is also syntactic sugar. This really refers to the element at
4 * 10 + 2
or, the 42nd element. In general, the index of element [a][b]
in array foo[x][y]
is at
a * y + b
The same concept applies to 3d arrays. If we have foo[x][y][z]
and we access element [a][b][c]
we are really accessing element:
a * y * z + b * z + c
This concept applies to n-dimensional arrays. If we have an array with dimensions D1, D2, D3 ... Dn
and we access element S1, S2, S3 ... Sn
the formula is
(S1 * D2 * D3 ... * Dn) + (S2 * D3 * D4 ... * Dn) + (S3 * D4 ... * Dn) ... + (Sn-1 * Dn) + Sn
The challenge
You must write a program or function that calculates the index of a multidimensional array according to the formula above. Input will be two arrays. The first array is the dimensions, and the second array is the indices. The length of these two arrays will always be equal and at least 1.
You can safely assume that every number in the arrays will be an non-negative integer. You can also assume that you will not get a 0
in the dimension array, although a 0
might be in the indices. You can also assume that indices will not be larger than the dimensions.
Test IO
Dimensions: [5, 10]
Indices: [4, 2]
Output: 42
Dimensions: [10, 10, 4, 62, 7]
Indices: [1, 2, 3, 4, 5]
Output: 22167
Dimensions: [5, 1, 10]
Indices: [3, 0, 7]
Output: 37
Dimensions: [6, 6, 6, 6, 6, 6, 6, 6, 6, 6]
Indices: [3, 1, 5, 5, 3, 0, 5, 2, 5, 4]
Output: 33570178
4So this is 0-based indexing, correct? Can we use 1-based indexing if that's more natural for our language of choice? – Alex A. – 2016-05-08T22:00:56.090
@AlexA. Yes, that's acceptable. – James – 2016-05-08T22:39:41.980
11Actually, what C 'really does' is create a single contiguous array of five elements of type
int[10]
. – None – 2016-05-09T05:57:34.427Related. – Martin Ender – 2016-05-09T09:27:06.743
1@Hurkyl Yes, but all of the integers in that array are still contiguous. It's just semantics. – James – 2016-05-09T19:27:29.147
Does someone mind to add the reference output for 1-based indexing? :) – bers – 2016-05-11T13:07:56.347