3 int calculate_actual_match(char **text
, char **pattern
, int m
, int n
, int x
, int y
)
5 unsigned int i
= 0, k
, j
, l
, hit
= 0;
7 for( l
= y
; l
< m
+ y
; l
++, i
++ ) {
11 for( j
= x
; j
< m
+ x
; j
++, k
++ )
12 if( pattern
[i
][k
] == text
[l
][j
] )
21 unsigned int karp(char **text
, char **pattern
, int m
, int n
)
29 unsigned int row
, matches
= 0;
31 double pattern_hash
= 0, text_hash
= 0;
33 double vertical_pattern
, vertical_text
, vertical_previous_text
;
35 /*Compute the hash for the pattern*/
36 for( i
= 0; i
< m
; i
++ ) {
42 /*Sum m characters in the same row*/
43 for( j
= 0; j
< m
; j
++ )
44 vertical_pattern
+= pattern
[j
][i
];
46 pattern_hash
= pattern_hash
* B
+ vertical_pattern
;
49 /*Compute the hash for the text*/
50 for( row
= 0; row
< n
- m
+ 1; row
++ ) {
54 /*Compute the hash for the first m elements of each row of the text*/
55 for( i
= 0; i
< m
; i
++ ) {
59 /*Sum m characters in the same row*/
60 for( j
= 0 + row
; j
< m
+ row
; j
++ )
61 vertical_text
= vertical_text
+ text
[j
][i
];
63 text_hash
= text_hash
* B
+ vertical_text
;
66 /*Compute the hash for the rest n-m elements of each row of the text*/
67 for( i
= m
; i
< n
; i
++ ) {
69 /*Check if the hashes actually match*/
70 if( pattern_hash
== text_hash
&& calculate_actual_match( text
, pattern
, m
, n
, i
- m
, row
))
73 /* Update text's hash*/
75 vertical_previous_text
= 0;
77 /*Sum m characters from i-m (vpt) and from i (vt) */
78 for( j
= 0 + row
; j
< m
+ row
; j
++ ) {
79 vertical_previous_text
= vertical_previous_text
+ text
[j
][i
-m
];
80 vertical_text
= vertical_text
+ text
[j
][i
];
83 text_hash
= ( text_hash
* B
) - ( vertical_previous_text
* Bm
) + vertical_text
;