Data Structures and Algorithms with Object-Oriented Design Patterns in Ruby
next up previous index

MultiDimensionalArray class [] and []= Methods

The elements of a multi-dimensional array are accessed using the [] and []= methods of the MultiDimensionalArray class. For example, you can access the tex2html_wrap_inline59701 element of a three-dimensional array a like this:

value = a[i,j,k]
which invokes the [] method with the array (i,j,k) as the index expression. Similarly, you can modify the tex2html_wrap_inline59701 element like this:
a[i,j,k] = value
which invokes the []= method with the array (i,j,k) as the index expression.

Program gif shows how that [] and []= methods are both implemented using a getOffset method. The getOffset method takes an array of n indices and computes the position of the corresponding element in the one-dimensional array according to Equation gif. This computation takes O(n) time in the worst case, where n is the number of dimensions. Consequently, the running times of the [] and []= methods are also O(n).

   program3125
Program: MultiDimensionalArray class [] and []= methods.


next up previous index

Bruno Copyright © 2004 by Bruno R. Preiss, P.Eng. All rights reserved.