Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through an array of arbitrary dimension

Using c#, how to iterate through an multidimensional array of unknown dimensions?

For example consider setting each element of the array to a specified value, all entries of the array needs to be iterated. The method should handle all the following cases and fill all entries with the value 4, regardless of the dimension of the array passed.

ClearArray(new int[3], 4);
ClearArray(new int[3,3], 4);
ClearArray(new int[3, 3, 3, 3], 4);

The methods signature obviously looks something like

static void ClearArray(Array a, int val) { ... }

I know how to iterate through one dimension:

for (int i=0; i<a.GetLength(dimension); i++) 
{
    ...
}

Note: This question is not about 2D arrays, 3D arrays, nor 4D arrays. It should handle whatever dimension the Rank property on the Array object says.

like image 378
vidstige Avatar asked Mar 28 '12 19:03

vidstige


1 Answers

Use Lexicographical order:
Index is sequence of "digits". On each iteration last "digit" incremented while it in bounds, then next "digit" incremented, etc

Func<Array, int[]> firstIndex = 
  array => Enumerable.Range(0, array.Rank)
         .Select(_i => array.GetLowerBound(_i))
         .ToArray();

Func<Array, int[], int[]> nextIndex = (array, index) => 
  {
    for (int i = index.Length-1; i >= 0; --i)
    {
       index[i]++;
       if (index[i] <= array.GetUpperBound(i))
         return index;
       index[i] = array.GetLowerBound(i);
    }
    return null;
  };

for (var index = firstIndex(array); index != null; index = nextIndex(array, index))
{
   var v = array.GetValue(index);
   ...
   array.SetValue(newValue, index);
}
like image 124
Serj-Tm Avatar answered Sep 19 '22 15:09

Serj-Tm