Arrays - 弘光科技大學

Download Report

Transcript Arrays - 弘光科技大學

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], …, list[4] each contains an integer
list
0
1
2
3
4
87
23
82
91
23
2
Abstract data type GeneralArray
class GeneralArray {
// A set of pairs <index, value> 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 <i, initValue> 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
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
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
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
6
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
Abstract data type Polynomial
class Polynomial {
e
e
// p(x) = a0 x 0  an x n ; 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.
float Eval(float f );
// Evaluate the polynomial *this at f and return the result.
};
8
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]=an-i, 0≤ i ≤n
Eg. a(x)=3x2+2x-4
i
0
1
2
coef[i]
3
2
-4
9
Polynomial representation 2
 private:
int degree;
float *coef;
 Polynomial::Polynomial(int d)
{
degree=d;
coef = new float[degree+1];
}
10
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
Example:
1000
c(x)=2x +1
c.capacity=2
c.terms=2
termArray
coef
2
1
exp
1000
0
12
Example
 a(x)=2x1000+1, b(x)=x4+10x3+3x2+1
a.start a.finish b.start
b.finish
coef
2
1
1
10
3
1
exp
1000
0
4
3
2
0
13
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
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
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
Sparse matrices (b)
-27
6
109
12
48
3 4
82 -2
-64 11
8 9
27 47
(a)
15
0
0
0
91
0
0
11
0
0
0
0
0
3
0
0
0
28
(b)
22
0
-6
0
0
0
0 -15
0
0
0
0
0
0
0
0
0
0
17
Abstract data type SparseMatrix
class SparseMatrix
{// A set of triples, <row, column, value>
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
Sparse matrix representation
 Use triple <row, column, value>
 Must know the numbers of rows and columns and the
number of nonzero elements
smArray[0]
[1]
[2]
[3]
[4]
[5]
[6]
[7]
row
0
0
0
1
1
2
4
5
col
0
3
5
1
2
3
0
2
(a)
value
15
22
-15
11
3
-6
91
28
smArray[0]
[1]
[2]
[3]
[4]
[5]
[6]
[7]
row
0
0
1
2
2
3
3
5
col
0
4
1
1
5
0
2
0
value
15
91
11
3
28
22
-6
-15
(b)
19
 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
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>
21
Iteration 0: scan the array and
process the entries with col=0
Reference: J.L. Huang@NCTU
22
Iteration 1: scan the array and
process the entries with col=1
Reference: J.L. Huang@NCTU
23
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
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
Example
26
1
27
7
28
Reference: J.L. Huang@NCTU
29
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
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
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
Two dimensional array row major order
行0
行1
X
X
X
X
X
X
…
…
…
X
X
X
列 u1-1 X
X
…
X
列0
列1
列2
… 行 u2-1
(a)
u2 個元素
u2 個元素
…
列0
…
列1
列i
列 ui-1
i * u2 個元素
(b)
33
Generalizing array representation
 Declare a[u1][u2]…[un]
 The address for a[i1][i2]…[in] is
  i1u 2u3  u n
 i2u3u 4  u n
 i3u 4u5  u n

 in 1u n
 in
n
    ija j
j 1
n
where α is the address of a[0][0], an=1 and aj=
u
k  j 1
k
1≤j<n
34
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
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
36
The Knuth-Morris-Pratt algorithm
(KMP algorithm)
 Suppose that pat=abcabcacab and s=s0s1…sm-1
a
b
c
a
a
a
b
c
a
b
3
4
a
a
0
a
1
b
2
c
a
0
1
2
3
4
c
a
c
a
b
c
a
b
c
6
7
8
9
5
b
5
a
c
Restart scanning here
a
b
37
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.
j
0
1
2
3
4
5
6
7
8
9
pat
a
b
c
a
b
c
a
c
a
b
f
-1
-1
-1
0
1
2
3
-1
0
1
38
Example
j
0
1
2
3
4
5
6
7
8
9
pat
a
b
c
a
b
c
a
c
a
b
f
-1
-1
-1
0
1
2
3
-1
0
1
 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
39
Example
j
0
1
2
3
4
5
6
7
8
9
pat
a
b
c
a
b
c
a
c
a
b
f
-1
-1
-1
0
1
2
3
-1
0
1
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
40
Example
j
0
1
2
3
4
5
6
7
8
9
pat
a
b
c
a
b
c
a
c
a
b
f
-1
-1
-1
0
1
2
3
-1
0
1
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
41
Fast matching
 Suppose that pat=abcabcacab and s=abcaa…
posS 0
a
1
b
2
c
3
a
4
a
a
b
c
a
b
c
1
2
3
4
5
posP 0
a
c
a
b
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
j
0
1
2
3
4
5
6
7
8
9
pat
a
b
c
a
b
c
a
c
a
b
f
-1
-1
-1
0
1
2
3
-1
0
1
42