3 int calculate_actual_match(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
] )
23 unsigned int i
, j
, start
= m
;
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 all characters in the same row*/
44 for( j
= 0; j
< m
; j
++ )
45 vertical_pattern
+= pattern
[j
][i
];
47 pattern_hash
= pattern_hash
* B
+ vertical_pattern
;
50 /*Compute the hash for the first m elements of the first row of the text*/
52 for( i
= 0; i
< m
; i
++ ) {
56 /*Sum all characters in the same row*/
57 for( j
= 0; j
< m
; j
++ )
58 vertical_text
= vertical_text
+ text
[j
][i
];
60 text_hash
= text_hash
* B
+ vertical_text
;
63 /*Compute the hash for the rest of the text*/
64 for( row
= 0; row
< n
- m
+ 1; row
++ ) {
66 /* On the first row start from the mth character */
70 for( i
= start
; i
< n
; i
++ ) {
72 /*Check if the hashes actually match*/
76 if( pattern_hash
== text_hash
&& calculate_actual_match( i
- m
, row
))
79 /* Update text's hash*/
81 vertical_previous_text
= 0;
83 for( j
= 0 + row
; j
< m
+ row
; j
++ ) {
84 vertical_previous_text
= vertical_previous_text
+ text
[j
][i
-m
];
85 vertical_text
= vertical_text
+ text
[j
][i
];
88 text_hash
= ( text_hash
* B
) - ( vertical_previous_text
* Bm
) + vertical_text
;
91 printf("Karp: %i\n",steps
);