Browse code

Split match and match_postitions

John Hawthorn authored on 28/12/2019 02:35:49
Showing 1 changed files

... ...
@@ -4,6 +4,7 @@
4 4
 #include <stdio.h>
5 5
 #include <float.h>
6 6
 #include <math.h>
7
+#include <stdlib.h>
7 8
 
8 9
 #include "match.h"
9 10
 #include "bonus.h"
... ...
@@ -129,6 +130,53 @@ static inline void match_row(const struct match_struct *match, int row, score_t
129 130
 	}
130 131
 }
131 132
 
133
+score_t match(const char *needle, const char *haystack) {
134
+	if (!*needle)
135
+		return SCORE_MIN;
136
+
137
+	struct match_struct match;
138
+	setup_match_struct(&match, needle, haystack);
139
+
140
+	int n = match.needle_len;
141
+	int m = match.haystack_len;
142
+
143
+	if (m > MATCH_MAX_LEN || n > m) {
144
+		/*
145
+		 * Unreasonably large candidate: return no score
146
+		 * If it is a valid match it will still be returned, it will
147
+		 * just be ranked below any reasonably sized candidates
148
+		 */
149
+		return SCORE_MIN;
150
+	} else if (n == m) {
151
+		/* Since this method can only be called with a haystack which
152
+		 * matches needle. If the lengths of the strings are equal the
153
+		 * strings themselves must also be equal (ignoring case).
154
+		 */
155
+		return SCORE_MAX;
156
+	}
157
+
158
+	/*
159
+	 * D[][] Stores the best score for this position ending with a match.
160
+	 * M[][] Stores the best possible score at this position.
161
+	 */
162
+	score_t D[n][m], M[n][m];
163
+
164
+	score_t *last_D, *last_M;
165
+	score_t *curr_D, *curr_M;
166
+
167
+	for (int i = 0; i < n; i++) {
168
+		curr_D = &D[i][0];
169
+		curr_M = &M[i][0];
170
+
171
+		match_row(&match, i, curr_D, curr_M, last_D, last_M);
172
+
173
+		last_D = curr_D;
174
+		last_M = curr_M;
175
+	}
176
+
177
+	return M[n - 1][m - 1];
178
+}
179
+
132 180
 score_t match_positions(const char *needle, const char *haystack, size_t *positions) {
133 181
 	if (!*needle)
134 182
 		return SCORE_MIN;
... ...
@@ -214,7 +262,3 @@ score_t match_positions(const char *needle, const char *haystack, size_t *positi
214 262
 
215 263
 	return M[n - 1][m - 1];
216 264
 }
217
-
218
-score_t match(const char *needle, const char *haystack) {
219
-	return match_positions(needle, haystack, NULL);
220
-}