Initial Commit
[2dmatching.git] / karp.c
blobd8e6a9b0b088c34555a882b67717fa65d08c8d89
1 #include "code.h"
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++ ) {
9 k = 0;
11 for( j = x; j < m + x; j++, k++ )
12 if( pattern[i][k] == text[l][j] )
13 hit++;
15 if ( hit == m*m )
16 return 1;
17 return 0;
20 void karp()
22 int steps = 0;
23 unsigned int i, j, start = m;
25 double Bm = 1;
27 #define B 128
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++ ) {
38 Bm *= B;
40 vertical_pattern = 0;
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++ ) {
54 vertical_text = 0;
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 */
67 if (row != 0)
68 start = 0;
70 for( i = start; i < n; i++ ) {
72 /*Check if the hashes actually match*/
74 steps++;
76 if( pattern_hash == text_hash && calculate_actual_match( i - m, row ))
77 matches++;
79 /* Update text's hash*/
80 vertical_text = 0;
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);