Wednesday, May 29, 2013

Bit Counting

I encountered a problem recently where I was asked to write a function to count the number of "on" bits in a character.  This is what I produced:

int CountBits(const char c)
{
    int count = 0;
    int x=0;
    for (; x<8; x++)
    {
        if (c & 1<<x)
            count++;
    }

    return count;
}


This led me into a more detailed problem in which I was asked to use that function to count the number of bits in an array of strings.  I initially produced this on the whiteboard:

int CountStringsBits(char** strArray, int numstrings)
{
    if (!strArray)
        return 0;

    int count = 0;
    for (int x=0; x<numstrings; x++)
    {
        for (int y=0; y <
strlen(strArray[x]); y++)
        {
            count += CountBits(strArray[x][y]);
        }
    }
    return count;
}


While this does work, I realized that it can be done better and faster with a simple hash table to save the counts of previously counted characters.  I also moved the strlen function out of the inner loop.

int CountStringsBits(char** strArray, int numstrings)
{
    if (!strArray)
        return 0;

    int bitArray[128];  //simple hash table

    memset(bitArray, 0, sizeof(bitArray));
    int nstr, count = 0, x=0, y=0;
    char c;
    for (; x<numstrings; x++)
    {
        if (!strArray[x]) // make sure we have a string
            continue;
        nstr = strlen(strArray[x]);
       
        for (y=0; y < nstr; y++)
        {
            c =  strArray[x][y];
            if (bitArray[c] == 0)
                count += bitArray[c] = CountBits(c);
            else
                count += bitArray[c];
        }
    }
    return count;
}


Thanks for reading!

No comments:

Post a Comment