Given a multidimensional array of integers, how can I find the sum of all the base elements? Each array may have a different number of arrays in it, so my algorithm must be flexible to accommodate all possible inputs. A recursive method would seem to be the most elegant solution. Example:
Given:
array = {
{{1,2,3},
{4,5},
{6,7,8}},
{{9},{10}}
}
Return:
55
Note that the length of each sub-array is inconsistent and varies, as well as the depth of the array. This means that traditional loops would not be able to check the length of the array, and recursive methods would not be able to define the number of dimensions the loop has as an initial parameter. Perhaps a recursive loop would need to cast an Object as an array?
Edit:
The method should also be able to sum an array of ANY number of dimensions. For example, the input array could have three dimensions, or even 7.