Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 2 1. 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],

Similar presentations


Presentation on theme: "Chapter 2 1. 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],"— Presentation transcript:

1 Chapter 2 1

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 2 01234 list8723829123

3 Abstract data type GeneralArray class GeneralArray { // A set of pairs where for each value of index in IndexSet there 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(int j, RangeList list, float initValue = 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 into the array. float Retrieve(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. void Store(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. }; // 3

4 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) 4

5 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. 5

6 Sequential mapping Most common way to represent an ordered list is by an array where we associate the list element a i with the array index i Performing operations (5) and (6) requires data movement Linked list in Chapter 4 6

7 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 7

8 Abstract data type Polynomial class Polynomial { // p(x) = ; a set of ordered pairs of // where a i is a nonzero float coefficient and e i 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. float Eval(float f ); // Evaluate the polynomial *this at f and return the result. }; 8

9 Polynomial representation 1 private: int degree; // degree ≤ MaxDegree float coef [MaxDegree + 1]; // coefficient array Let a be a Polynomial class object and n≤MaxDegree a.degree=n a.coef[i]=a n-i, 0≤ i ≤n Eg. a(x)=3x 2 +2x-4 9 i012 coef[i]32-4

10 Polynomial representation 2 private: int degree; float *coef; Polynomial::Polynomial(int d) { degree=d; coef = new float[degree+1]; } 10

11 Polynomial representation 3 class Polynomial; class Term{ friend Polynomial; private: float coef; int exp; }; private: Term *termArray; // array of nonzero terms int capacity; // size of termArray int terms; // number of nonzero terms 11

12 Example: c(x)=2x 1000 +1 coef21 exp10000 12 termArray c.capacity=2 c.terms=2

13 Example a(x)=2x 1000 +1, b(x)=x 4 +10x 3 +3x 2 +1 13 a.starta.finishb.startb.finish coef2111031 exp100004320

14 Polynomial addition Polynomial Polynomial::Add(Polynomial b) {// Return the sum of the polynomials *this and b. Polynomial c; int aPos = 0, bPos = 0; while ((aPos < terms) && (bPos < b.terms)) if (termArray [aPos].exp = = b.termArray [bPos].exp) { float t = 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 of b(x) for ( ; bPos < b.terms ; bPos++) c.NewTerm (b.termArray [bPos].coef, b.termArray [bPos].exp); return c; } 14

15 Adding a new term void Polynomial::NewTerm(const float theCoeff, const int theExp) {// Add a new term to the end of termArray if (terms = = capacity) {// double capacity of termArray capacity *= 2; term *temp = new term[capacity]; // new array copy(termArray, termArray + terms, temp); delete [] termArra ; // deallocate old memory termArray = temp; } termArray [terms].coef = theCoeff; termArray [terms++].exp = theExp; } 15

16 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) 16

17 Sparse matrices (b) 17 -27341500220-15 682-20113000 109-6411000-600 1289000000 4827479100000 0028000 (a)(b)

18 Abstract data type SparseMatrix class SparseMatrix {// A set of triples, public: SparseMatrix(int r, int c,int t); // The constructor function creates a SparseMatrix with r rows, c columns, and a capacity // of t nonzero terms SparseMatrix Transpose( ); // Returns the SparseMatrix obtained by interchanging the row and column value of every // triple in *this SparseMatrix Add(SparseMatrix b); // If the dimension of *this and b are the same, add; otherwise, an exception is thrown. SparseMatrix Multiply(SparseMatrix b); }; 18

19 Sparse matrix representation Use triple Must know the numbers of rows and columns and the number of nonzero elements 19 rowcolvaluerowcolvalue smArray[0]0015smArray[0]0015 [1]0322[1]0491 [2]05-15[2]1111 [3]1111[3]213 [4]123 2528 [5]23-6[5]3022 [6]4091[6]32-6 [7]5228[7]50-15 (a)(b)

20 class SparseMatrix; // forward declaration class MatrixTerm { friend class SparseMatrix private: int row, col, value; }; In class SparseMatrix: private: int rows, cols, terms, capacity; MatrixTerm *smArray[MaxTerms]; 20

21 Transposing a matrix For each row i take element and store it in element of the transpose. difficulty: where to put (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 in element 21

22 Iteration 0: scan the array and process the entries with col=0 22 Reference: J.L. Huang@NCTU

23 Iteration 1: scan the array and process the entries with col=1 23 Reference: J.L. Huang@NCTU

24 Transposing a matrix SparseMatrix SparseMatrix::Transpose( ) {// Return the transpose of *this SparseMatrix b(cols, rows, terms); // capacity of b.smArray is terms if (terms > 0) {// nonzero matrix int currentB = 0; for (int c = 0 ; c < cols ; c++) // transpose by columns for (int i = 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) return b; } 24

25 Transposing a matrix faster Store some information to avoid scanning all terms back FastTranspose requires more space than Transpose Calculate RowSize by scanning array b Calculate RowStart by scanning RowSize 25

26 Example 26

27 27 1

28 28 7

29 29 Reference: J.L. Huang@NCTU

30 Transposing a matrix faster SparseMatrix SparseMatrix::FastTranspose( ) {// Return the transpose of *this in O(terms + cols) time. SparseMatrix b(cols, rows, terms); if (terms > 0) {// nonzero matrix int *rowSize = new int[cols]; int *rowStart = new int[cols]; // compute rowSize[i] = number of terms in row i of b fill(rowSize, rowSize + cols, 0); // initialize for (int i = 0 ; i < terms ; i ++) rowSize[smArray[i].col]++; // rowStart[i] = starting position of row i of b rowStart[0] = 0; for (int i = 1 ; i < cols ; i++) rowStart[i] = rowStart[i-1] + rowSize[i-1]; 30

31 for (int i = 0 ; i < terms ; i++) {// copy from *this to b int j = 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; } return b; } 31

32 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] 32

33 Two dimensional array row major order 33

34 Generalizing array representation Declare a[u 1 ][u 2 ]…[u n ] The address for a[i 1 ][i 2 ]…[i n ] is 34 where α is the address of a[0][0], a n =1 and a j =1≤j<n

35 Abstract data type String class String { public: String(char *init, int m); // Constructor that initializes *this to string init of length m. bool operator = = (String t); // If the string represented by *this = t, return true, else return false. bool operator!( ); // If *this is empty, return true, else return false. int Length( ); // Return the number of characters in *this. String Concat(String t); // Return *this + t 。 String Substr(int i, int j); // Return a string containing the j characters of *this at position i, i + 1,..., i + j - 1 if these are valid position of *this; // otherwise, throw an exception. int Find(String pat); // Return an index i such that pat matches the substring of *this that begins at position i. // Retrun -1 if pat is either empty or not a substring of *this. }; 35

36 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. 36 Reference: J.L. Huang@NCTU

37 The Knuth-Morris-Pratt algorithm (KMP algorithm) Suppose that pat=abcabcacab and s=s 0 s 1 …s m-1 37 abcabcacab abcaa 0 1 2 3 4 5 abcabcacab abcaa 0 1 2 3 4 5 6 7 8 9 Restart scanning here

38 Failure function If p=p 0 p 2 …p n-1 is a pattern, then its failure function, f, is defined as f(j) = largest k<j such that p 0 …p k = p j-k …p j if such a k≥0 exists f(j) = -1 otherwise Eg. 38 j0123456789 patabcabcacab f 0123 01

39 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  p 0 =a and p 1 =b  p 0 ≠p 1 f(1)= -1 39 j0123456789 patabcabcacab f 0123 01 f(j) = largest k<j such that p 0 …p k = p j-k …p j if such a k≥0 exists f(j) = -1 otherwise

40 Example j=2 Since k<2 and k ≧ 0, k=0,1 When k=1  p 0 p 1 =ab and p 1 p 2 =bc  p 0 p 1 ≠p 1 p 2 When k=0  p 0 =a and p 2 =c  p 0 ≠p 2 f(2)= -1 j=3 Since k<3 and k ≧ 0, k=0,1,2 When k=2  p 0 p 1 p 2 =abc and p 1 p 2 p 3 =bca When k=1  p 0 p 1 = ab and p 2 p 3 =ca When k=0  p 0 =a and p 3 =a  p 0 =p 3 f(3)= 0 40 j0123456789 patabcabcacab f 0123 01 f(j) = largest k<j such that p 0 …p k = p j-k …p j if such a k≥0 exists f(j) = -1 otherwise

41 Example j=4 k<4 and k ≧ 0, thus k = 0, 1, 2, 3 When k=3  p 0 p 1 p 2 p 3 =abca and p 1 p 2 p 3 p 4 =bcab When k=2  p 0 p 1 p 2 =abc and p 2 p 3 p 4 =cab When k=1  p 0 p 1 =ab and p 3 p 4 =ab f(4)=1 41 j0123456789 patabcabcacab f 0123 01 f(j) = largest k<j such that p 0 …p k = p j-k …p j if such a k≥0 exists f(j) = -1 otherwise

42 Fast matching Suppose that pat=abcabcacab and s=abcaa… 42 abcabcacab abcaa posP 0 1 2 3 4 5 j0123456789 patabcabcacab f 0123 01 Failure function 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 posS 0 1 2 3 4


Download ppt "Chapter 2 1. 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],"

Similar presentations


Ads by Google