-1

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.

  • 1
    No, [the correct answer is 3](https://regexr.com/6ket8) – Giovanni Esposito Apr 27 '22 at 07:25
  • See [https://stackoverflow.com/questions/20833295/how-can-i-match-overlapping-strings-with-regex](https://stackoverflow.com/questions/20833295/how-can-i-match-overlapping-strings-with-regex) – woocash19 Apr 27 '22 at 07:31
  • @GiovanniEsposito no, starting from 0,3,5,8 index. – Raayat Ahmed Apr 27 '22 at 08:28
  • @RaayatAhmed no, the match starting from 3, ends at 5 (so you can't consider the match starting from 5). So the answer is 3: from index 0, 3 and 8. This is how regex works. If you want another result you can't use regex. – Giovanni Esposito Apr 27 '22 at 08:34

1 Answers1

0

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.

Giovanni Esposito
  • 9,634
  • 1
  • 10
  • 26