Bugfix: Really fix the crash in bm.c, do memory checking after each allocation, corre...
[2dmatching.git] / baeza2.c
blobf7db4632ae528f4494b2ef4e2d7f5330a9b8c22e
1 #include "code.h"
3 int naive2( char **text, char **pattern, int m, int n, int textrow, int textcolumn, int patternrow )
5 unsigned int i, j, k;
7 /* Slide the text's window */
8 for ( i = textcolumn; i < n - m + 1; i++ ) {
10 k = i;
12 /* Start searching against the first pattern character */
13 for( j = 0; j < m; j++ ) {
15 if( pattern[patternrow][j] == text[textrow][k] )
16 k++;
18 else
19 break;
21 /* If j finished without breaking return success */
22 if ( j == m )
23 return k-m;
24 else
25 j = 0;
27 /* No match found on this row */
28 return -1;
31 int naive2b( char **text, char **pattern, int m, int n, int textrow, int textcolumn, int patternrow )
33 unsigned int j;
35 /* Search only m characters after the current text's column without sliding the window */
36 for ( j = 0; j < m; j++ ) {
38 if( pattern[patternrow][j] == text[textrow][textcolumn] )
39 textcolumn++;
41 else
42 return -1;
44 /* If reached through here, report success */
45 return 0;
48 unsigned int baeza2( char **text, char **pattern, int m, int n )
50 int x, i, j, row, matches = 0;
52 /* Iterate every m rows of the text (first check lines 0 to m - 1) */
53 for ( row = m - 1; row < n; row += m ) {
55 /* Search each row against all m lines of the pattern */
56 for ( i = 0; i < m; i++ ) {
58 /* In each row start searching from the begining */
59 x = 0;
61 while ( x != -1) {
63 /* Check text's row against pattern's row */
64 x = naive2( text, pattern, m, n, row, x, i);
66 /* If a row is not found procceed to the next pattern's row */
67 if ( x != -1 ) {
69 /* If there is a match at i = 3, check vertically the text above for i = 0-2 and below for 4-m*/
71 /* Check lines above the current */
72 for ( j = 0; j < i; j++ )
73 if( naive2b( text, pattern, m, n, row - i + j, x, j ) == -1)
74 goto newline;
76 /* Check lines below the current */
77 for ( j = 1; j < m - i; j++ ) {
79 /* Avoid crashing when x = n or n-1 */
80 if ( row + j >= n )
81 goto newline;
83 if ( naive2b( text, pattern, m, n, row + j, x, i + j ) == -1)
84 goto newline;
87 /* If we reached here we should have a match */
88 matches++;
90 /* If a mismatch is found, don't bother searching for the other y lines */
91 newline:
93 /* Now increase counter to continue searching on the same row */
94 x++;
96 else break;
100 return matches;