420 likes | 534 Views
Arrays. Chapter 2. Arrays. Array: a set of index and value Data structure For each index, there is a value associated with that index. Eg . int list[5]: list[0], …, list[4] each contains an integer. Abstract data type GeneralArray. class GeneralArray {
E N D
Arrays Chapter 2
Arrays • Array: a set of index and value • Data structure • For each index, there is a value associated with that index. • Eg. int list[5]: list[0], …, list[4] each contains an integer
Abstract data type GeneralArray classGeneralArray{ // A set of pairs <index, value> where for each value of index inIndexSetthere is a value of type float. // IndexSet is a finite ordered set of one or more dimensions, for example, {0, …, n-1} for one dimension, // {(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)} for two dimensions, // etc. public: GeneralArray(intj, RangeList list, floatinitValue = defaultValue); // This constructor creates j dimension array of floats; the range of the kth dimension is given by the // kth element of list. For each index i in the index set, insert <i, initValue> into the array. floatRetrieve(index i); // If I is in the index set of the array, return the float associated with i in the array; otherwise throw an // exception. voidStore(index i, float x); // If i is in the index set of the array, replace the old value associated with i by x; otherwise throw an // exception. }; //
Ordered (linear) list • Eg. • Days of the week: (SUN, MON, TUS, WED, THU, FRI, SAT) • Values in a deck of cards: (Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King) • Floors of a building: (basement, lobby, mezzanine, first, second) • Years the United States fought in World War II: (1941, 1942, 1943, 1944, 1945)
Operations on lists • (1) Find the length, n, of the list. • (2) Read the items from left to right (or right to left). • (3) Retrieve the ith element, 0≤i<n. • (4) Store a new value into the ith position, 0≤i<n. • (5) Insert a new element at the position i, 0≤i<n, causing elements numbered i, i+1, …,n-1 to become numbered i+1, i+2, …, n. • (6) Delete the element at position i, causing elements numbered i+1, …, n-1 to become numbered i, i+1, …,n-2.
Sequential mapping • Most common way to represent an ordered list is by an array where we associate the list element ai with the array index i • Performing operations (5) and (6) requires data movement • Linked list in Chapter 4
The polynomial abstract data type • The largest exponent of a polynomial is called is degree • A polynomial is called sparse when it has many zero terms • Implement polynomials by arrays
Abstract data type Polynomial class Polynomial { // p(x) = ; a set of ordered pairs of <ei,ai> // where ai is a nonzero float coefficient and ei is a non-negative integer exponent. public: Polynomial( ); // Construct the polynomial p(x) = 0. Polynomial Add(Polynomial poly); // Return the sum of the polynomials*this and poly. Polynomial Mult(Polynomial poly); // Return the product of the polynomials*this and poly. floatEval(floatf ); // Evaluate the polynomial*this atf and return the result. };
Polynomial representation 1 • private: intdegree; // degree ≤ MaxDegree float coef [MaxDegree + 1]; // coefficient array • Let a be a Polynomial class object and n≤MaxDegree • a.degree=n • a.coef[i]=an-i, 0≤ i≤n • Eg. a(x)=3x2+2x-4
Polynomial representation 2 • private: intdegree; float *coef; • Polynomial::Polynomial(int d) { degree=d; coef = new float[degree+1]; }
Polynomial representation 3 • class Polynomial; class Term{ friend Polynomial; private: floatcoef; intexp; }; • private: Term *termArray; // array of nonzero terms intcapacity; // size of termArray int terms; // number of nonzero terms
Example: c(x)=2x1000+1 c.capacity=2 c.terms=2 termArray
Example • a(x)=2x1000+1, b(x)=x4+10x3+3x2+1
Polynomial addition PolynomialPolynomial::Add(Polynomialb) {// Return the sum of the polynomials*this and b. Polynomialc; intaPos = 0, bPos = 0; while ((aPos < terms) && (bPos < b.terms)) if (termArray[aPos].exp = = b.termArray[bPos].exp) { floatt = termArray[aPos].coef + b.termArray[bPos].coef; If (t) c.NewTerm(t, termArray[aPos].exp); aPos++;bPos++; } else if (termArray[aPos].exp < b.termArray[bPos].exp) { c.NewTerm(b.termArray[bPos].coef, b.termArray[bPos].exp); bPos++; } 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 ofb(x) for ( ; bPos <b.terms;bPos++) c.NewTerm(b.termArray[bPos].coef, b.termArray[bPos].exp); returnc; }
Adding a new term voidPolynomial::NewTerm(const floattheCoeff, const inttheExp) {// Add a new term to the end of termArray if (terms = = capacity) {// double capacity of termArray capacity *= 2; term *temp =newterm[capacity]; // new array copy(termArray, termArray + terms, temp); delete []termArra; // deallocate old memory termArray = temp; } termArray [terms].coef = theCoeff; termArray[terms++].exp =theExp; }
Sparse matrices • A general matrix consists of m rows and n columns of numbers • An m×n matrix • It is natural to store a matrix in a two dimensional array, say A[m][n] • A matrix is called sparse if it consists of many zero entries • Implementing a spare matrix by a two dimensional array waste a lot of memory • Space complexity is O(m×n)
Abstract data type SparseMatrix classSparseMatrix {// A set of triples, <row, column, value> public: SparseMatrix(intr, intc,intt); // The constructor function creates a SparseMatrix with r rows, c columns, and a capacity // of t nonzero terms SparseMatrixTranspose( ); // Returns theSparseMatrixobtained by interchanging the row and column value of every // triple in*this SparseMatrixAdd(SparseMatrix b); // If the dimension of *this and b are the same, add; otherwise, an exception is thrown. SparseMatrixMultiply(SparseMatrixb); };
Sparse matrix representation • Use triple <row, column, value> • Must know the numbers of rows and columns and the number of nonzero elements
classSparseMatrix; // forward declaration classMatrixTerm { friend class SparseMatrix private: int row, col, value; }; • In classSparseMatrix: • private: int rows, cols, terms, capacity; MatrixTerm *smArray[MaxTerms];
Transposing a matrix • For each row i • take element <i, j, value> and store it in element <j, i, value> of the transpose. • difficulty: where to put <j, i, value> (0, 0, 15) ====> (0, 0, 15) (0, 3, 22) ====> (3, 0, 22) (0, 5, -15) ====> (5, 0, -15) (1, 1, 11) ====> (1, 1, 11) Move elements down very often. • For all elements in column j, • place element <i, j, value> in element <j, i, value>
Iteration 0: scan the array and process the entries with col=0 Reference: J.L. Huang@NCTU
Iteration 1: scan the array and process the entries with col=1 Reference: J.L. Huang@NCTU
Transposing a matrix SparseMatrixSparseMatrix::Transpose( ) {// Return the transpose of *this SparseMatrixb(cols , rows , terms);// capacity of b.smArray is terms if (terms > 0) {// nonzero matrix intcurrentB = 0; for (int c = 0 ;c < cols;c++) // transpose by columns for (inti = 0 ;i < terms;i++) // find and move terms in column c if (smArray[i].col = = c) { b.smArray[currentB].row = c; b.smArray[currentB].col = smArray[i].row; b.smArray[currentB++].value = smArray[i].value; } } // end of if (terms > 0) returnb; }
Transposing a matrix faster • Store some information to avoid scanning all terms back • FastTransposerequires more space than Transpose • Calculate RowSize by scanning array b • Calculate RowStart by scanning RowSize
Transposing a matrix faster SparseMatrixSparseMatrix::FastTranspose( ) {// Return the transpose of *this in O(terms + cols) time. SparseMatrixb(cols , rows , terms); if (terms > 0) {// nonzero matrix int *rowSize = newint[cols]; int *rowStart = newint[cols]; // compute rowSize[i] = number of terms in row iof b fill(rowSize, rowSize + cols, 0); // initialize for (inti = 0 ;i < terms;i ++) rowSize[smArray[i].col]++; //rowStart[i] = starting position of row i of b rowStart[0] = 0; for (inti = 1 ;i < cols;i++) rowStart[i] = rowStart[i-1] + rowSize[i-1];
for (inti = 0 ;i < terms ;i++) {// copy from*this to b intj = rowStart[smArray[i].col]; b.smArray[j].row=smArray[i].col; b.smArray[j].col = smArray[i].row; b.smArray[j].value = smArray[i].value; rowStart[smArray[i].col]++; } delete [] rowSize; delete [] rowStart; } returnb; }
Multidimensional arrays • Row major order • Eg. A[2][3][2][2] • 24 elements (2 x 3 x 2 x 2 = 24) • a[0][0][0][0], a[0][0][0][1], a[0][0][1][0], a[0][0][1][1] • a[0][1][0][0], a[0][1][0][1], a[0][1][1][0], a[0][1][1][1] • … • a[1][2][0][0], a[1][2][0][1], a[1][2][1][0], a[1][2][1][1]
Generalizing array representation • Declare a[u1][u2]…[un] • The address for a[i1][i2]…[in] is where α is the address of a[0][0], an=1 and aj= 1≤j<n
Abstract data type String classString { public: String(char *init, intm); // Constructor that initializes *this to string init of length m. booloperator = = (Stringt); // If the string represented by *this =t, return true, else return false. booloperator!( ); // If *this is empty, return true, else return false. intLength( ); // Return the number of characters in*this. StringConcat(Stringt); // Return*this + t。 StringSubstr(inti, intj); // Return a string containing the jcharacters of *this at position i, i+1, ..., i+j-1 if these are valid position of *this; // otherwise, throw an exception. intFind(Stringpat); // Return an indexi such that pat matches the substring of*this that begins at positioni. // Retrun -1 ifpat is either empty or not a substring of *this. };
String matching • Input: P and T, the pattern and text strings; m and n, the length of P and T, respectively. The pattern is assumed to be nonempty. • Output: The return value is the index in T where a copy of P begins, or -1 if no match for P is found. Reference: J.L. Huang@NCTU
The Knuth-Morris-Pratt algorithm (KMP algorithm) • Suppose that pat=abcabcacab and s=s0s1…sm-1 0 1 2 3 4 5 0 1 2 3 4 5 6 7 8 9 Restart scanning here
Failure function • If p=p0p2…pn-1 is a pattern, then its failure function, f, is defined as f(j) = largest k<j such that p0…pk = pj-k…pj if such a k≥0 exists f(j) = -1 otherwise • Eg.
Example • j=0 • Since k<0 and k≧0, no such k exists • f(0)= -1 • j=1 • k<1 and k≧0, thus k=0 • When k=0 p0=a and p1=b p0≠p1 • f(1)= -1 f(j) = largest k<j such that p0…pk = pj-k…pj if such a k≥0 exists f(j) = -1 otherwise
Example f(j) = largest k<j such that p0…pk = pj-k…pj if such a k≥0 exists f(j) = -1 otherwise • j=2 • Since k<2 and k≧0, k=0,1 • When k=1 p0p1=ab and p1p2=bc p0p1≠p1p2 • When k=0 p0=a and p2=c p0≠p2 • f(2)= -1 • j=3 • Since k<3 and k≧0, k=0,1,2 • When k=2 p0p1p2=abc and p1p2p3=bca • When k=1 p0p1 = ab and p2p3=ca • When k=0 p0=a and p3=a p0=p3 • f(3)= 0
Example f(j) = largest k<j such that p0…pk = pj-k…pj if such a k≥0 exists f(j) = -1 otherwise • j=4 • k<4 and k≧0, thus k = 0, 1, 2, 3 • When k=3 p0p1p2p3=abca and p1p2p3p4=bcab • When k=2 p0p1p2=abc and p2p3p4=cab • When k=1 p0p1=ab and p3p4=ab • f(4)=1
Fast matching • Suppose that pat=abcabcacab and s=abcaa… posS 0 1 2 3 4 posP 0 1 2 3 4 5 Step 1: fail at posP=4 (=posS) Step 2: check f(3) Step 3: posP=pat.f[posP-1]+1 = pat.f[3]+1 =0+1=1 Failure function