CSC 180H1 F
Midterm
October 2008
Question 2.
[15 marks]
Define a function
find
pattern
that returns the position of the first occurrence of a pattern in an array.
If no such pattern were found in the array, it returns 1.
find
pattern
has four parameters:
a
is array,
n
is array size,
pattern
is pattern array, and
m
is size of pattern array. For example, given the following two
arrays,
int a[] = {0, 1, 1, 8, 0, 1, 0, 1, 8, 0};
int b[] = {1, 8, 0};
/* pattern array */
find
pattern(a, 10, b, 3)
returns 2, the position of the first digit of pattern
1 8 0
in array
a
.
a: 0 1 1 8 0 1 0 1 8 0
^

position: 2
/* return index of pattern in a, 1 if none */
int find_pattern(int a[], int n, int pattern[], int m)
{
int i, j, k;
for (i = 0; i < n  m + 1; i++) {
for (j = i, k = 0; k < m && a[j] == pattern[k]; k++, j++)
;
if (k > 0 && k == m)
return i;
}
return 1;
}
Student #:
Page 3 of 11
cont’d
. . .