import std.stdio;
int bruteForce(string containing, string str, int start = 0) {
int matchStart = -1;
int matchLen = 0;
foreach(idx, ch; containing[start..$]) {
if(str[matchLen] == ch) {
matchStart = idx - matchLen + start;
matchLen++;
if(matchLen == str.length) {
return matchStart;
}
} else {
matchStart = -1;
matchLen = 0;
}
}
return -1;
}
typedef int function(string, string, int) SearchFunction;
void testSearch(string name, SearchFunction fn) {
writefln("Testing search using %s algorithm", name);
auto pp = "Programming Praxis";
testSearchStr(fn, pp, pp, 0);
testSearchStr(fn, pp, "Praxis", 12);
testSearchStr(fn, pp, "Prax", 12);
testSearchStr(fn, pp, "praxis", -1);
testSearchStr(fn, pp, "P", 0);
testSearchStr(fn, pp, "P", 12, 5);
}
void testSearchStr(SearchFunction fn, string containing, string str, int expected, int start = 0) {
writefln("%s[%s] == %d [%d]", containing, str, expected, fn(containing, str, start));
assert(fn(containing, str, start) == expected);
}
void main() {
testSearch("brute force", &bruteForce);
}