I am trying to count how many times a pattern occurs as a subsequence of a string and also keep the indices where the match happens.
The counting is easy using recursive calls.
function count(str, pattern, strInd, patternInd) {
if (patternInd === 0) {
return 1;
}
if (strInd === 0) {
return 0;
}
if (str.charAt(strInd - 1) === pattern.charAt(patternInd - 1)) {
const count1 = count(str, pattern, strInd - 1, patternInd - 1);
const count2 = count(str, pattern, strInd - 1, patternInd);
return count1 + count2;
} else {
return count(str, pattern, strInd - 1, patternInd);
}
}
For keeping the indices, the logic I have is to push current index of str to a "local indices array" within a recursive call when the pattern character matches the string character, and once the pattern is finished, push the "local indices" to the "global indices" and reset the "local indices" for the next recursion path.
Resetting the local indices is where i am facing problems:
function count(str, pattern, strInd, patternInd) {
if (patternInd === 0) {
// when this path ends, add to list the indices found on this path
globalIndices.push(localIndices);
// reset the local indices
localIndices = [];
console.log("found");
return 1;
}
if (strInd === 0) {
return 0;
}
if (str.charAt(strInd - 1) === pattern.charAt(patternInd - 1)) {
localIndices.push(strInd);
const count1 = count(str, pattern, strInd - 1, patternInd - 1);
const count2 = count(str, pattern, strInd - 1, patternInd);
return count1 + count2;
} else {
return count(str, pattern, strInd - 1, patternInd);
}
}
This way it loses the previous path information after every bifurcation, because once a matched subpath is consumed, it is removed from localIndices, and localIndices starts keeping track of the matches after the bifurcation happened.
so for example, str is "abab" and pattern is "ab" then i would like to globalIndices = [[4,3], [4,1], [2,1]] but instead i would get [[4,3],[1],[2,1]]
I would like to reset "local indices" to the previous bifurcation.
Am i going in the right direction, or do these kind of problems need a different implementation altogether?