Search code examples
javascriptalgorithmnaivebayes

naive string matching algorithm gone wrong


I am trying to implement naive search and I do not get the expected result. Can anyone point out here, what could be the possible error.

function naive(string, str) {
    for (let i = 0; i <= string.length - str.length; i++) {
        if (string[i] == str[0]) {
            let counter = 1

            for (let j = 1; j <= str.length; j++) {
                if (string[i + j] == str[j]) {
                    counter++;
                    console.log(counter)
                } else
                    counter = 0;
            }

            if (counter == str.length) {
                console.log(`${counter} pattern matched at ${i}`)
            }
        } else
            console.log('nothing matched')
    }
}

Solution

  • var match_found = false;
    function naive(string, str){
      for(let i =0; i <= string.length - str.length; i++){
          if(string[i] == str[0]){
            let counter= 1
                for(let j = 1; j < str.length; j++){
                    if(string[i + j] == str[j]){    
                      counter++;
                    }else{
                      break;
                    }
                }
            if(counter == str.length){ 
              console.log('Pattern matched at ' + i);
              match_found = true;// can break; here if you wish to, else it will give you all matches present
            }
          }
      }
      if(match_found === false){
        console.log(str + ' not found in ' + string);
      }
    }
    
    naive('abcdgggabcdggg','ggg');

    • You increment the counter when there is a match, but you need to break the loop where there is a mismatch.

    • Your inner for loop condition needs to have j < str.length instead of j <= str.length, because index starts from 0.

    • else console.log('nothing matched'). You can't just instantly decide that. If a string index doesn't match, you need to still keep looking for the rest of the indexes. Best way to go about it is to maintain a boolean flag for it as shown in the above code.