Search This Blog

Saturday, 24 December 2016

KMP string search

KMP (Knuth Morris Pratt) Pattern Searching
The naive pattern search doesn’t work well in cases where we see many matching characters followed by a mismatching character.

The KMP matching algorithm uses degenerating property (pattern having same sub-patterns appearing more than once in the pattern) of the pattern and improves the worst case complexity to O(n). The basic idea behind KMP’s algorithm is: whenever we detect a mismatch (after some matches), we already know some of the characters in the text of next window. We take advantage of this information to avoid matching the characters that we know will anyway match.
Link to code.

Sunday, 11 December 2016

Count number of ones in binary of a number


#include <iostream>
using namespace std;
//count no of ones in binary representation
int count1(int n)
{
    int c=0;
    while(n)
    {
        n=n&(n-1);
        cout<<n;
        c++;
    }
    return c;
}
int main(){
 cout<<count1(6);
 return 0;
}