JS Code-
let N=7
let S="bab"
let arr=["a","b"]
for(i=2;i<N;i++){ //constructing a fibonnaci series
let item=arr[i-1]+arr[i-2]
arr.push(item)
}
// console.log(arr[N-1]) // babbababbabba
let marr=arr[N-1]
let str = new RegExp(S, "g");
let result=marr.match(str)
let answer=(result.length)
console.log(answer) // gives answer as 3 , but correct is 4
task at hand was to first construct a fibonnaci series where f1="a" and f2="b", For 3 onwards f3=f2+f1 and f4=f3+f2 Then we have to match the string S to see how many times it occurs in the fN. My code runs fine for rest of the test cases but for N=7 and S="bab" , correct answer is 4 but my code says 3.
Inspired by this answer, you can't do this with a single regex, but you can do this:
let results = [];
let match;
let N=7
let pat = /(?=(bab))\w/g;
let arr=["a","b"]
for(i=2;i<N;i++){ //constructing a fibonnaci series
let item=arr[i-1]+arr[i-2]
arr.push(item)
}
// console.log(arr[N-1]) // babbababbabba
let marr=arr[N-1]
while ( (match = pat.exec( marr ) ) != null ) {
results.push( match[1] );
}
console.log(results.length);
You capture all three digits inside the lookahead, then go back and match one character in the normal way just to advance the match position.