CSC 180H1 F
Midterm
October 2008
Question 2.
[15 marks]
Defne a ±unction
find
pattern
that returns the position o± the frst occurrence o± a pattern in an array.
I± no such pattern were ±ound in the array, it returns 1.
find
pattern
has ±our parameters:
a
is array,
n
is array size,
pattern
is pattern array, and
m
is size o± pattern array. For example, given the ±ollowing 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 o± the frst digit o± pattern
180
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 o± 11
cont’d
. . .