0% found this document useful (0 votes)
256 views36 pages

02 ArrayStruct

Uploaded by

Yau Long Cheung
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
256 views36 pages

02 ArrayStruct

Uploaded by

Yau Long Cheung
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Arrays and Structures

2.1 (Arrays)
2.2 (Dynamically Allocated Arrays)
2.3 (Structures and Inoins)
2.4 (Polynomials)
2.5 (Sparse Matrix)
2.6
(Representation of Multidimensional Arrays)
2.7 (Strings)

2.1 (Arrays)


()


<index, value>

2.1 (Arrays)
2.1.1
ADT Array
<indexvalue>
indexitem
index{0,,n1}
{(0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,0), (2,1), (2,2)}

A Array i indexx itemj,size


Array Create(j, list)

::=

return jlistj
iiitems

Item Retrieve(A,i)

::=

if(i index) return Ai


else return

Array Store (A,i,x)

::=

if(iindex) return A
<i,x>
else return

end Array

ADT 2.1 Array


3

2.1 (Arrays)
2.1.2 C

int list[5], *plist[5];
list[5]: five integers
list[0], list[1], list[2], list[3], list[4]
*plist[5]: five pointers to integers
plist[0], plist[1], plist[2], plist[3], plist[4]


list[0]
list[1]
list[2]

List[0]

list

base address =
+ sizeof(int)
+ 2*sizeof(int)

+sizeof(int)

List[1]

+i*sizeof(int)

List[i]

2.1 (Arrays)
2.1.2 C
int *list1 int list2[5]
: list1 list2(pointer)
: list25.

int list2[5]:
list2: list2[0]
(list2 + i): list2[i], , (&list2[i])
*(list2 + i): list2[i]


2.1

2.1 (Arrays)
#define MAX_SIZE 100
float sum(float [], int);
float input[MAX_SIZE], answer;
void main(void)
{
int i;
for ( i = 0; i < MAX_SIZE; i++ )
input[i] = i;
answer = sum(input, MAX_SIZE);
printf(The sum is: %f\n, answer);
}

float sum(float list[], int n)


{
int i;
float tempsum = 0;
for ( i = 0; i < n; i++ )
tempsum += list[i];
return tempsum;
}

2.1

2.1 (Arrays)
2.1.2 C
2.1[]
void print1( int *ptr, int rows)
{ /* */
int i;
printf(Address Contents\n);
for ( i = 0; i < rows; i++ )
printf(%8u%5d\n, ptri, *(ptri);
printf(\n);
}

2.2

int one[] = {0,1,2,3,4};


print1(ones,5); //

address

contents

12244868

12244872

12244876

12244880

12244884

2.1

4
4
7

2.2
2.2.1

#define MAX_SIZE 101


#define SWAP(x, y, t) ((t) = (x), (x) = (y), (y) = (t))
void sort(int [], int ); /**/
void main(void)
{
int i, n;
int list[MAX_SIZE];

?
?
?
?

1.4

2.2
2.2.1



MAX_SIZE
MAX_SIZE
n

2.2
2.2.1

int i, n, *list;
printf("Enter the number of numbers to generate:");
scanf("%d", &n);
if (n < 1 ) {
fprintf(stderr, "Improper value of n \n");
exit(EXIT_FAILURE);
}
MALLOC(list, n*sizeof(int));

10

2.2
2.2.2
C

int x[3][5]
[0]

[1]

[2] [3]

[4]

x[0]
x[1]
x[2]

2.2
Row Major

column Major?

11

2.2
2.2.2

int **myArray;
myArray = make2dArray(5,10);
myArray[2][4]=6;
int** make2dArray(int rows, int cols)
{
/* rows cols */
int **x, i;
/* */
MALLOC( x, rows * sizeof(*x));
/* */
for ( i = 0; i < rows; i++)
MALLOC(x[i], cols * sizeof(**x));
return x;
}

2.3

12

2.2
2.2.2
C
calloc

0

NULL
realloc

13

2.2
2.2.2
calloc
n
int *x;
x=calloc(n, sizeof(int))

#define CALLOC(p, n, s) \
if (!((p) = calloc(n,s))) {\
fprintf(stderr, "Insufficient memory");\
exit(EXIT_FAILURE);\
}

14

2.2
2.2.2
realloc
malloccalloc
ps

p=realloc(p,s);

#define REALLOC(p, s) \
if (!((p) = realloc(p,s))) {\
fprintf(stderr, "Insufficient memory");\
exit(EXIT_FAILURE);\
}
15

2.2


array3D[s1][s2][s3]
int ***array3D;
MALLOC(array3D, s1*sizeof(*array3D));
for ( i=0; i<s1; i++) {
MALLOC(array3D[i], s2*sizeof(**array3D));
for ( j=0; j<s2; j++) {
MALLOC(array[i][j], s3*sizeof(***array3D));
}
}

16

2.3
(Structure and Union)
2.3.1



struct {
char name[10]; //
int age;
//
float salary;
//
} person;


strcpy(person.name, "james");
person.age = 10;
person.salary = 3500;

17

2.3
(Structure and Union)
2.3.1

typedef struct humanBeing {
char name[10];
int age;
float salary;
};

typedef struct {
char name[10];
int age;
float salary;
} humanBeing;

humanBeing person1, person2;


18

2.3
(Structure and Union)
2.3.1

int humansEqual (humanBeing person1, humanBeing person2)
{ /* person1person2TRUEFALSE */
if (strcmp(person1.name, person2.name))
return FALSE;
if (person1.age != person2.age)
return FALSE;
if (person1.salary != person2.salary)
return FALSE;
return TRUE;
}

2.4
19

2.3
(Structure and Union)
2.3.1

strcpy(person1.name person2.name);
person1.age=person2.age;
person1.salary=person2.salary;

C
if (person1==person2)
person1=person2;

20

10

2.3
(Structure and Union)
2.3.1

typedef struct {
char name[10];
int age;
float salary;
date dob;
} humanBeing;

typedef struct {
int month;
int day;
int year;
} date;


humanBeing person1;
person1.dob.month = 2;
person1.dob.day = 11;
person1.dob.year = 1944;

21

2.3
(Structure and Union)
2.3.2 (Union)



22

11

2.3
(Structure and Union)
2.3.2 (Union)

typedef struct {
char name[10];
int age;
float salary;
date dob;
sexType sexInfo;
} humanBeing;

typedef struct sexType {


enum tagField {female, male} sex;
union {
int children; //
int beard;
//
} u;
};

humanBeing person1, person2;


person1.sexInfo.sex = male;
person1.sexInfo.u.beard = FALSE;
person2.sexInfo.sex=female;
person2.sexInfo.u.children=4;

23

2.3
(Structure and Union)
2.3.3

4, 8, 16 byte


struct {
char c;
int i;
float a;
};

Memory
c

24

12

2.3
(Structure and Union)
2.3.4 (Self-Referential Structures)

typedef struct list {
char data;
list *link;
}
list item1, item2, item3;
item1.data = 'a';
item2.data = 'b';
item3.data = 'c';
item1.link = item2.link = item3.link = NULL;

item1.link = &item2;
item2.link = &item3; a

NULL
25

2.4 (Polynomials)
2.4.1

(ordered list)(linear list)


Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday


Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King


basement, lobby, mezzanine, first, second


26

13

2.4 (Polynomials)
2.4.1

Finding the length, n , of the list.


Reading the items from left to right (or right to left).
Retrieving the ith element from a list, 0 i < n.
Replacing the ith item of a list, 0 i < n.
Inserting a new item in the ith position of a list, 0 i < n.
Deleting an item from the ith position of a list, 0 i < n.

27

2.4 (Polynomials)
2.4.2

A(x)=2x1000+1
B(x)=x4+10x3+3x2+1


C(x) = A(x) + B(x)?
D(x) = A(x) B(x)?

28

14

ADT Polynomial
p(x) a1xe1 ... anxen; <ei, ai> ai
Coefficientsei Exponentsei

poly, poly1, poly2 Polynomialcoef Coefficients


exponExponents

Boolean IsZero(poly)

::=
::=

Coefficient Coef(poly,expon)

::=

else return TRUE


if(expon poly) return
else return 0

Exponent LeadExp(poly)

::=
::=

return poly
if(expon poly) return

Polynomial Zero()

Polynomial
Attach(poly,coef,expon)
Polynomial

return p(x) = 0
if(poly) return FALSE

else return <coef,expon>


poly
::=

Remove(poly,expon)

if(expon poly) return


expon

Polynomial
SingleMult(poly,coef,expon)

::=

poly else return


return polycoefxexpon

Polynomial Add(poly1,poly2)
Polynomial Mult(poly1,poly2)

::=

return poly1poly2

::=

return poly1poly2

end Polynomial

29

ADT 2.2Polynomial

2.4 (Polynomials)
2.4.2

#define MAX_DEGREE 1001
typedef struct {
int degree;
float coef[MAX_DEGREE];
} polynomial;

A(x)=2x1000+1

998

999

1000

B(x)=x4+10x3+3x2+1


polynomial a;
a.degree = n
a. coef[i] = an-i , 0 i n.

10

1000


(sparse)
30

15

/* d = ababd */
d = Zero()
while ( !IsZero(a) && !IsZero(b) ) do {
switch COMPARE (LeadExp(a), LeadExp(b)) {
case -1:
d = Attach (d, Coef(b,LeadExp(b)), LeadExp(b));
b = Remove(b, LeadExp(b));
break;
case 0:
sum = Coef(a,LeadExp(a)) + Coef(b,LeadExp(b));
if (sum) {
Attach(d,sum,LeadExp(a));
a = Remove(a,LeadExp(a));
b = Remove(b,LeadExp(b));
}
break;
case 1:
d = Attach(d,Coef(a,LeadExp(a)),LeadExp(a));
a = Remove(a,LeadExp(a));
}
}
insert any remaining terms of a or b into d

2.5

31

2.4 (Polynomials)
2.4.2

typedef struct {
float coef;
int expon;
} polynomial;


polynomial terms[MAX_TERMS];
int avail = 0; /* */

A(x)=2x1000+1

B(x)=x4+10x3+3x2+1

startA

finishA

startB

10

1000

finishB

avail

2.3
: 2
:

32

16

2.4 (Polynomials)
2.4.3
2.6
2.7

33

void padd(int startA, int finishA, int startB, int finishB, int *startD, int *finishD)
{ /* D(x)=A(x)+B(x) */
float coefficient;
*startD = avail;
while (startA <= finishA && startB <= finishB)
switch(COMPARE(terms[startA].expon, terms[startB].expon)) {
case -1: /* a b */
attach(terms[startB].coef, terms[startB].expon);
startB++;
break;
case 0: /* */
coefficient = terms[startA].coef +
terms[startB].coef;
if (coefficient) attach(coefficient, terms[startA].expon);
startA++;
startB++;
break;
case 1: /* ab */
attach(terms[startA].coef, terms[startA].expon);
startA++;
break;
}

2.6(1/2)

34

17

/* A(x)D */
for( ; startA <= finishA; startA++)
attach(terms[startA].coef,terms[startA].expon);
/* B(x)D */
for( ; startB <= finishB; startB++)
attach(terms[startB].coef,terms[startB].expon);
*finishD = avail 1;
}

2.6(2/2)

35

void attach(float coefficient, int exponent)


{ /* */
if (avail >= MAX_TERMS) {
fprintf(stderr, Too many terms in the polynomial \n);
exit(EXIT_FAILURE);
}
terms[avail].coef = coefficient;
terms[avail++].expon = exponent;
}

2.7

36

18

2.5 (Sparse Matrix)


2.5.1
mn
mnmn

col 0 col 1 col 2
3
4
row 0 - 27

82
2
row 1 6
row 2 109 64 11

8
9
row 3 12
27
47
row 4 48

col 0 col 1 col 2 col 3 col 4


0
0
22
0
row 0 15

11
3
0
0
row 1 0

0
0
0
6
0
row 2

0
0
0
0
row 3 0
0
0
0
0
row 4 91

0
28
0
0
row 5 0

col 5
15
0
0

0
0

(b) 0

(a)

2.4
37

2.5 (Sparse Matrix)


2.5.1

100010002000
1000000

38

19

ADT SparseMatrix
<row, column, value> row column
value item
ab SparseMatrixx item
ijmaxColmaxRow index
SparseMatrix
Create(maxRow,maxCol)

::=

SparseMatrix

::=

Transpose(a)
SparseMatrix Add(a,b)

::=

SparseMatrix
Multiply(a,b)

::=

return maxItems =
maxRow maxCol maxRow
maxCol SparseMatrix
return

if a b
return
else return
if a b
return a b
dd[i][j]=(a[i][k]b[k][j])
d(i,j) (i,j)
else return

ADT 2.3SparseMatrix
39

2.5 (Sparse Matrix)


2.5.2
<row, col, value>
Sparse_matrix Create(max_row, max_col) ::=
#define MAX_TERMS 101
/* maximum number of terms +1,
e.g., # of rows (columns) or # of nonzero terms */
typedef struct {
int row;
int col;
int value;
} term;
term a[MAX_TERMS]
40

20

2.5 (Sparse Matrix)


2.5.3 (transpose)
a
A = 00
a10

a01
a11

a02
a12

a00
AT = a01
a02

a10
a11
a12

for each row i


take element < i, j, value> and store it
as element <j, i, value> of the transpose

41

2.5 (Sparse Matrix)


2.5.3

row

col

value

a[0]
a[1]
a[2]

6
0
0

6
0
3

8
15
22

a[3]
a[4]
a[5]

0
1
1

5
1
2

15
11
3

a[6]
a[7]
a[8]

2
4
5

3
0
2

6
91
28

AT
b[0]

row
6

col
6

value
8

b[1]
b[2]
b[3]

0
3
5

0
0
0

15
22
15

b[4]
b[5]
b[6]

1
2
3

1
1
2

11
3
6

b[7]
b[8]

0
2

4
5

91
28

42

21

2.5 (Sparse Matrix)


2.5.3 (transpose)

for all element in column j


place elemnet <i, j, value> in element <j, i, value>
a[0]

row
6

col
6

value
8

b[0]

row
6

col
6

value
8

a[1]
a[2]
a[3]

0
0
0

0
3
5

15
22
15

b[1]
b[2]
b[3]

0
0
1

0
4
1

15
91
11

a[4]
a[5]

1
1

1
2

11
3

b[4]
b[5]

2
2

1
5

3
28

a[6]
a[7]

2
4

3
0

6
91

b[6]
b[7]

3
3

0
2

22
6

a[8]

28

b[8]

15

(a)

(b)

2.5

43

void transpose (term a[], termb[])


{
/* ab */
int n,i,j,currentb;
n = a[0].value;
/* */
b[0].row = a[0].col; /* ba */
b[0].col = a[0].row; /* ba */
b[0].value = n;
if (n > 0) { /* */
currentb = 1;
for (i = 0; i < a[0].col; i++) /* a */
for (j = 1; j<= n; j++) /* */
if (a[j].col == i) {
/* b */
b[currentb].row = a[j].col;
b[currentb].col = a[j].row;
b[currentb].value = a[j].value;
currentb++;
?
?
} /* end of if */
O(?)
} /* end of if */
}

2.8

44

22

2.5 (Sparse Matrix)


2.5.3

for (i = 0; i < a[0].col; i++) /* a */
for (j = 1; j<= n; j++) /* */

O(columns elements)

2
for ( j=0; j< columns; j++)
for ( i=0;i<rows;i++)
b[j][i]=a[i][j];

O(rows columns)


O(columns+elements)

45

void fastTranspose(term a[], term b[])


{
/* ab */
int rowTerms[MAX_COL], startingPos[MAX_COL];
int i,j, numCols = a[0].col, numTerms = a[0].value;
b[0].row = numCols;
b[0].col = a[0].row;
b[0].value = numTerms;
if (numTerms > 0) { /* */
for (i = 0; i < numCols; i++) rowTerms[i] = 0;
O(columns)
for (i = 1; i <= numTerms; i++) rowTerms[a[i].col]++; O(Terms)
startingPos[0] = 1;
for (i = 1; i < numCols; i++)
O(columns-1)
startingPos[i] = startingPos[i-1] + rowTerms[i-1];
for (i = 1; i <= numTerms; i++) {
O(Terms)
j = startingPos[a[i].col]++;
b[j].row = a[i].col;
b[j].col = a[i].row;
b[j].value = a[i].value;
O(Columns+Terms)
}
}/* end of if */
}

2.9

46

23

2.5 (Sparse Matrix)


2.5.4
: [D]mp=[A]mn* [B]np
n 1

d ij = aik bkj 0 i < m0 j < p


k =0

:
A
B jB

:
B
A
Bj
47

2.5 (Sparse Matrix)


2.5.4

1 0 01 1 1 1 1 1
1 0 00 0 0 = 1 1 1

1 0 00 0 0 1 1 1
2.6

48

24

void mmult(term a[], term b[], term d[])


{
/* */
int i, j, column, totalB = b[0].value, totalD = 0;
int rowsA = a[0].row, colsA = a[0].col, totalA = a[0].value, colsB = b[0].col;
int rowBegin = 1, row = a[1].row, sum = 0;
int newB[MAX_TERMS][3];
if (colsA != b[0].row) {
fprintf(stderr,Incompatible matrices\n);
exit(EXIT_FAILURE);
}
fastTranspose(b,newB);
/* */
a[totalA+1].row = rowsA;
newB[totalB+1].row = colsB;
newB[totalB+1].col = 0;

2.10(1/3)

49

for (i = 1; i <= totalA; ) {


column = newB[1].row;
for (j = 1; j <= totalB+1; ) {
/* AB */
if (a[i].row != row) {
storeSum(d,&totalD,row,column,&sum);
i = rowBegin;
for (;newB[j].row == column; j++);
column = newB[j].row;
}else if (newB[j].row != column) {
storeSum(d,&totalD,row,column,&sum);
i = rowBegin;
column = newB[j].row;

2.10(2/3)

50

25

} else switch (COMPARE(a[i].col, newB[j].col)) {


case -1: /* a */
i++; break;
case 0: /* ab */
sum += ( a[i++].value * newB[j++].value);
break;
case 1: /* b */
j++;
}
} /* for j <= totalB+1 */
for (; a[i].row ==row; i++) ;
rowBegin = i, row = a[i].row;
} /* for i <= totalA */
d[0].row = rowsA;
d[0].col = colsB;
d[0].value = totalD;
}

2.10(3/3)

51

D
void storeSum(term d[], int *totalD, int row, int column, int *sum)
{
/* if *sum != 0, then it along with its row and column position is stored
as the *totalD+1 entry in d */
if (*sum)
if (*totalD < MAX_TERMS) {
d[++*totalD].row = row;
d[*totalD].col = column;
d[*totalD].value = *sum;
*sum = 0;
} else {
fprintf(stderr,Numbers of terms in product exceeds %d\n,MAX_TERMS);
exit(EXIT_FAILURE);
}
}

2.11storeSum
52

26

2.5 (Sparse Matrix)


2.5.4

fastTranspose
O(ColsB+totalB)
for( i=1; i<=totalA; )
for (j=1; j<=totalB+1; )

O (colsB termsRow + totalB )

row
= O(colsB totalA + rowsA totalB )

53

2.5 (Sparse Matrix)


2.5.4

for (i =0; i < rows_a; i++)
for (j=0; j < cols_b; j++) {
sum =0;
for (k=0; k < cols_a; k++)
sum += (a[i][k] *b[k][j]);
d[i][j] =sum;
}

O(rows_a * cols_a * cols_b)


cols_b)

54

27

2.6

a[upper0][upper1]...[uppern-1]
upper0 upper1... uppern-1=

n 1

upper

i =0

row major order

2D

3D

a[upper0][upper1]

a[upper0][upper1][upper2]

a[0][0]=

a[0][0][0]=

a[i][j]=+iupper1+j

a[i][j]=+iupper1upper2+jupper2+k

55

2.6

a[upper0][upper1]...[uppern-1]
upper0 upper1... uppern-1=

n 1

upper

i =0

column major order

2D

3D

a[upper0][upper1]

a[upper0][upper1][upper2]

a[0][0]=

a[0][0][0]=

a[i][j]=+jupper0+i

a[i][j]=+kupper0upper1+jupper0+i

56

28

2.7 (String)
2.7.1 (ADT)
:
S=s0,s1,...,sn-1,
n=0, S(empty string)(null string)
:"Welcome to data structure 2008/10/23!"

...
57

ADT String

s, t String i, j,m
String Null(m)

::=

return m
NULL

Integer Compare(s,t)

::=

if s t return 0

NULL
else if s t return
else return

Boolean IsNull(s)

::=

if (Compare(s,NULL)) return FALSE

Integer Length(s)

::=

if (Compare(s,NULL))
return s

String Concat(s,t)

::=

String Substr(s,i,j)

::=

else return TRUE

else return 0
if (Comare(t,NULL))
return s t
else return s
if ((j0) && (ij1)<Length(s))
return s i, i1,,
ij1
else return NULL

ADT 2.4String

58

29

destsrcdest

char *strcat(char *dest, char *src)


char *strncat(char *dest, char *src, int n)

destsrcndest

char *strcmp(char *str1, char *str2)

str1str20str1str2
0str1str20

char *strncmp(char *str1, char *str2, int n)

nstr1str20str1str2
0str1str20

char *strcpy(char *dest, char *src)

srcdestdest

char *strncpy(char *dest, char *src, int n)

srcndest dest

size_t strlen(char *s)

char *strchr(char *s, int c)

scNULL

char *strrchr(char *s, int c)

scNULL

char *strtok(char *s, char *delimiters)

s delimiters

char *strstr(char *s, char *pat)

spat

size_t strspn(char *s, char *spanset)

sspanset

size_t strcspn(char*s, char *spanset)

sspanset

char *strpbrk(char *s, char *spanset)

sspansetspanset

2.8C
59

2.7 (String)
2.7.2 C
'\0' (null character)
:
:
#define MAX_SIZE 100
char s[MAX_SIZE] = {"dog"};
char t[MAX_SIZE] = {"house"};

s[0] s[1] s[2] s[3]


d

\0

t[0] t[1] t[2] t[3] t[4] t[5]


h

\0

2.9C
:
char s[] = {"dog"}; /* 4byte */
char t[] = {"house"}; /* 6byte */

60

30

2.7 (String)
2.7.2 C
Example 2.2[(string insertion)]
:string1string2, string2string1i
:
#include <string.h>
#define MAX_SIZE 100
char string1[MAX_SIZE], *s=string1;
char string2[MAX_SIZE], *t=string2;
"amobile", "uto"
211"automobile"
C, 2.10, 2.12

61

2.7 (String)
s

\0

temp

\0

\0

temp

\0

(a) strncpy (temp,s,i)


temp

\0

(b) strcat (temp,t)


temp

\0

(c) strcat (temp,(si))

62

31

void strnins(char *s, char *t, int i)


{
/* tsi */
char string[MAX_SIZE], *temp = string;
if (i < 0 && i > strlen(s)) {
fprintf(stderr,Position is out of bounds \n);
exit(EXIT_FAILURE);
}
if (!strlen(s))
strcpy(s,t);
else if (strlen(t)) {
strncpy(temp,s,i);
strcat(temp,t);
strcat(temp,(s+i));
strcpy(s,temp);
}
}

2.12
63

2.7 (String)
2.7.3
stringpat, stringpat
Cstrstr,
patpatstring,
NULL;
strstr:
char pat[MAX_SIZE], string[MAX_SIZE], *t;
if (t=strstr(string, pat))
printf("The string from strstr is: %s\n",t);
else
printf("The pattern was not found with strstr\n");
64

32

2.7 (String)
2.7.3
(2.13)
int nfind(char *string, char *pat)
{ /* */
int i,j,start = 0;
int lasts = strlen(string)-1;
int lastp = strlen(pat)-1;
int endmatch = lastp;
for (i = 0; endmatch <= lasts; endmatch++, start++) {
if (string[endmatch] == pat[lastp])
for (j = 0, i = start; j < lastp && string[i] == pat[j]; i++,j++) ;
if (j == lastp)
return start; /* */
}
return -1;
}

2.13

65

2.13 [Simulation of nfind]


pat="aab", string="ababbaabaa"
a

lastp
(a) pattern

star
t

endmatch

lasts
(b) no match

start

endmatch

lasts

(c) no match

2.11nfnid(1/2)

66

33

start

endmatch

lasts

(d) no match
a

start

endmatch

lasts

(e) no match
a

start

endmatch

lasts

(f) no match
a

start

endmatch

lasts

(g) match

2.11nfnid(2/2)

67

2.7 (String)
2.7.3
O(n*m)
Knuth, Morris, PrattO(strlen(string))

#include <stdio.h>
#include <string.h>
#define max_string_size 100
#define max_pattern_size 100
int pmatch();
void fail();
int failure[max_pattern_size];
char string[max_string_size];
char pat[max_pattern_size];
68

34

int pmatch(char *string, char *pat)


{ /* Knuth, Morris, Pratt */
int i = 0, j = 0;
int lens = strlen(string);
int lenp = strlen(pat);
while ( i < lens && j < lenp ) {
if (string[i] == pat[j]) {
i++;
j++;
} else if (j == 0)
i++;
else j = failure[j-1]+1;
}
return ( (j == lenp) ? (i-lenp) : -1);
}

2.14Knuth, Morris, Pratt


69

void fail(char *pat)


{
/* */
int n = strlen(pat);
failure[0] = -1;
for (j = 1; j < n; j++) {
i = failure[j-1];
while ((pat[j] != pat[i+1] && (i >= 0))
i = failure[i];
if (pat[j] == pat[i+1])
failure[j] = i+1;
else failure[j] = -1;
}
}

2.15
70

35


Arrays and Structures

2.1 (Arrays)
2.2 (Dynamically Allocated Arrays)
2.3 (Structures and Inoins)
2.4 (Polynomials)
2.5 (Sparse Matrix)
2.6
(Representation of Multidimensional Arrays)
2.7 (Strings)

71

36

You might also like