bruteforce string matching javascript -
function search(pattern, text) { var m = pattern.length; var n = text.length; (var = 0; < n - m; i++) { var j =0; while (j < m) { if (text.charat(i + j) != pattern.charat(j)) {break;} } if (j == m) {return i;} } return -1; } console.log(search("rf", "jdsrfan"));
i want make brute-force string matching algorithm in javascript. can tell me whats wrong above code?
i did fixed myself fixed code follows:
// return offset of first match or -1 if no match function bruteforcepatternsearch(spattern, stext) { var m = spattern.length, n = stext.length; (var = 0; <= n - m; i++) { var j=0; while (j < m) { if (stext.charat(i+j) !=spattern.charat(j)){ break; } j++; } if (j == m) {return i;} // found @ offset } return -1; // not found } bruteforcepatternsearch("abracadabra","abacadabrabracabracadabrabrabracad");
you're never incrementing j
start with. hence infinite loop.
then, claudio commented, i < n - m
wrong. should i <= n - m
.
spoiler: here fixed function. advise not take as-is, try doing instead.
function search(pattern, text) { var m = pattern.length; var n = text.length; (var = 0; <= n - m; ++i) { var matched = true; (var j = 0; j < m; ++j) { if (text.charat(i + j) != pattern.charat(j)) { matched = false; break; } } if (matched) { return i; } } return -1; }
Comments
Post a Comment