|
Data Structures and Algorithms
with Object-Oriented Design Patterns in Ruby |
The simplest way to implement a matrix is to use a multi-dimensional
array with two dimensions as shown in Program
.
The DenseMatrix class extends the Matrix class
discussed in the preceding section.
The DenseMatrix class adds a instance attribute called @array
which is a multi-dimensional array.
The initialize method of the DenseMatrix class
takes two arguments,
and
,
and constructs the corresponding
multi-dimensional array.
Clearly, the running time of the initialize method is O(mn).

Program: DenseMatrix class initialize, [] and []= methods.
Program
also defines the [] and []=
methods for the DenseMatrix class.
These methods each take an ordered pair, (i,j),
as the index expression and use the pair
as the index into the multi-dimensional array.
Because the number of dimensions is fixed at two,
the running time for each of these methods is O(1).