If you have a n dimension array - how do you make it efficient? Do you run out of pointers? RRS feed

  • Question

  • I have a program that needs to create an array of arbitrary dimension.  In other words, if you pass 2 to a routine, that routine has to allocate a 2 dimensional array.  

    So I wrote a routine to do this.  Lets assume for simplicity that every dimension has the same number of values.  And lets suppose that if we want to get a value out of this array, we pass the indices as an array too.

    So for example, if we have a 3 dimensional array, and we want to access array(3,2,7) we pass an one dimensional array that has 3,2,and 7 in it.

    I've found a way to do this, but it requires a lot of multiplications to find the index.  So I thought of an alternative, which is this:

    Select Case n
     Case 1
      dim ArrayN(0) as integer
     Case 2
      dim ArrayN(0)(0) as integer
     Case 3
      dim ArrayN(0)(0)(0) as integer
     Case Else
      MsgBox "dimension is too high", vbCritical
    End Select
    It would seem to me that this kind of array operates by addition, rather than multiplication.  
    Internally if you searched for arrayN(4)(2)(5) the compiler would add 4 to the first index, 
    which would give you an array to which you add 2, which would give you an array to which you add 5.
    Now at most, I have 5 dimensional arrays, but I wonder if this kind of array means a lot of
    internal pointers in, and may exceed the capacity of to hold pointers. For instance,
    If the size of each dimension is 10, then an array of 2 dimensions has 10 pointers, an array of 
    3 dimensions has 100 pointers, an array of 5 dimensions has 10,000 pointers. 
    And I might have several such arrays in memory at the same time.
    There seems to be a tradeoff in programming often between speed and space.
    The alternative method (that used the multiplications) was to create a one dimensional array that I 
    would do computations to treat as a multi-dimensional array:
      Function GetIndex(ByVal Arrayofindices() As Integer) As Integer
        Dim theIndex As Integer
        theIndex = Arrayofindices(0)
        For k = 1 To Arrayofindices.GetLength(0) - 1
          theIndex = ArrayofMFindices(k) + theIndex * DimensionSize
        Return (theIndex)
      End Function
    so for N dimensions, you have N-1 multiplications just to get at a weight.
    Perhaps this is true of regular arrays internally too, e.g. MyArr(5,7,2)
    Still, if anyone knows a better method, one that does not overload's
    capacity to hold pointers, and that does not take up too much space, and that
    does not require lots of multiplications just to get a value, let me know!

    Wednesday, November 24, 2010 10:49 AM