L03 Arrays
L03 Arrays
Arrays
#include <iostream>
#include “Rectangle.h”
main() {
Rectangle r,s; //object of class Rectangle
Rectangle *t = &s; // object pointer
...
if (r.GetHeight()*r.GetWidth() >
t->GetHeight()*t->GetWidth()) cout<<“r”;
else cout<<“s”;
cout<<“ has the greater area” << endl;
};
class GeneralArray {
private:
/* A set of <index, value>, where IndexSet is a
finite ordered set of one or more dimensions */
public:
GeneralArray(int j; RangeList list,
float initValue = defatultValue);
/* Constructor creates a j-D array of floats.
Range of k-D is given by kth element of list.
For each i in IndexSet, insert <i,initValue> */
float Retrieve(index i);
void Store(index i, float x);
}; // end of GeneralArray
x5 4x3 2x2 x0
1 0 4 2 0 1 exponent index
coefficient value
A[0] A[1] A[2] A[3] A[4] A[5]
x5 4x3 2x2 x0
1 0 4 2 0 1
A[0] A[1] A[2] A[3] A[4] A[5]
– Must know MaxDegree, may allocate too much space,
waste memory in a sparse polynomial, e.g., x1000+1
else{
c.NewTerm(termArray[aPos].coef,termArray[aPos].exp);
aPos++;
}
// add in remaining terms of *this
for(; aPos < terms; aPos++)
c.NewTerm(termArray[aPos].coef,
termArray[aPos].exp);
// add in remaining terms of b
for(; bPos < b.terms; bPos++)
c.NewTerm(b.termArray[bPos].coef,
b.termArray[bPos].exp);
return c;
}
b(x) = x6 + 3x5 + 6x + 3
15 0 0 22 0 -15
0 11 3 0 0 0
0 0 0 -6 0 0
A=
0 0 0 0 0 0
91 0 0 0 0 0
0 0 28 0 0 0
15 0 0 0 91 0
0 11 0 0 0 0
0 3 0 0 0 28
AT =
22 0 -6 0 0 0
0 0 0 0 0 0
-15 0 0 0 0 0
SparseMatrix SparseMatrix::FastTranspose( )
{ SparseMatrix b(cols, rows, terms);
if (terms > 0) {
int *rowSize = new int[cols];
int *rowStart = new int[cols];
// compute rowSize[i]=# of terms in row i of b
fill(rowSize, rowSize+cols, 0);
for(int i=0; i<terms; i++)
rowSize[smArray[i].col]++;
// rowStart[i] = starting pos. of row i in b
rowStart[0] = 0;
for(int i=1; i<cols; i++)
rowStart[i]=rowStart[i-1]+rowSize[i-1];
SparseMatrix SparseMatrix::Multiply(SparseMatrix b) {
SparseMatrix bT = b.FastTranspose(); //O(b.terms+b.cols)
for ith row in smArray // O(rows)
for jth row in bT.smArray // O(b.cols)
Perform “Polynomal Addition” // O(Terms[i]+b.Terms[j])
}
Complexity:
– O(rows b.cols (Term[i] + b.Terms[j]))
– rows Term[i] = a.terms
b.cols b.Terms[j] = b.terms
– O(rows b.terms + b.cols a.terms)