Friday, September 17, 2010

Hexadecimal string to Decimal integer conversion

17, Sep, 2010.
Question:
Given a string that contains hexadecimal number, write a function htoi() that returns the equivalent integer.


// Here is one function
int getValue(char const* hexString, int const radix)
{
    int         loopIndex;      // Loop iterator
    int         signFlag = 1;   // Keeps track of sign
    signed int  retValue = 0;   // Final value
    int         currentDigit;   // Current digit under process
    int         len = strlen(hexString);    // Lenght of string

    // Check for sign
    if(hexString[0] == '-')
    {
        // Advance the base
        hexString++;
        // Remove '-' from count
        len--;
        // Sing is -ve
        signFlag = -1;
    }

    // Iterate from left to right
    // Accumulate the weight of each digit upon occurance of next digit
    for(loopIndex = 0; loopIndex < len; loopIndex++)
    {
        currentDigit = toupper(hexString[loopIndex]) - ASCII_ZERO;

        // Is the digit between A through F?
        if(currentDigit > 9)
        {
            // Adjust numerical value
            currentDigit -= (ASCII_A - '9');
        }

        // Based on Horner's principle
        retValue = retValue * radix + currentDigit;
    }

    // Flip the sign, if required
    retValue *= signFlag;

    // This is the final value
    return retValue;
}
Examples:


getValue("1011", 2);    // Binary string to integer
getValue("12345", 10);  // Decimal string to integer
getValue("ABCDE", 16);  // Hexadecimal string to integer


Error handling is omitted.


1. Overflow and underflow (if string contains more than 10 characters on 32 bit machines, i.e. length = [32*log(2) + 1] digits in general, which is the characteristic).
2. Invalid String (containing unexpected characters).
3. String not terminated with NUL character.
4. String is NULL.
5. What if a kernel space buffer is passed as hex string?
6. Is it reentrant?
7. Who will be the consumers of the function, and possible ways of misusing it?
8. What changes are required if wide character buffer (Unicode) is passed (portability issue).
9. Any optimizations without compromising on the functionality.

Sunday, September 12, 2010

Find the total number of squares and rectangles in an NxN chessboard.

12th, September, 2010


Solution:

For example, consider 8 X 8 chess board.

Note that we need 9 integers to represent one side (say x-axis) of the chess board. Similarly we need 9 integers on other side (say y-axis).

Rectangles:
Every square is a rectangle. A rectangle requires two co-ordinates (horizontal line) on x-axis and two co-ordinates (vertical line) on y-axis. The horizontal line needs two integers out of these 9 integers on x-axis. Similarly the vertical line needs two integers out of 9 on the y-axis. Hence we can draw the horizontal line in 9C2 different ways, and same with vertical line. Overall we can have (9C2)*(9C2) = (36)*(36) = 1296 rectangles on the chess board.

Squares:
There is simple approach to figure out squares.

Draw one simple rectangle with consecutive integers. We can have only one rectangle.

Take any two consecutive integers on x and y axis, there will be 1 (outer) + 4 (individual) squares.

Take any three consecutive integers on x and y axis, there will be 1 (outer) + 4 (dual) + 9 (individual) squares.

Take any four consecutive integers on x and y axis, there will be 1 (outer) + 4 (triple) + 9 (dual) + 16 (individual) squares.

Note that there is a pattern. So, for 8 consecutive integers on x and y axis there will be

1 + 4 + 9 + ... + 49 + 64

= n(n+1)(2n+1)/6 (where n = 8)
= 204 Squares.

I think there is simple approach using binomial co-efficients. Try it.

You can generalize the approach for N X N chess board.

Saturday, September 11, 2010

Find right-most set bit in an integer

September 11, 2010

I recently posted one the following solution. Question is, given an integer (other than 0) find right most set bit in that integer.
You can see the post in the following link
The solution is given below,
// Position of rightmost set bit
An order of log(X) algorithm. We can conclude from 2's complement form that "a number can be converted to 2’s complement form by complementing each bit from right most set bit". For example, -7 can be obtained in the following way (assuming 8 bit size)
7  = 00000111
-7 = 11111001
8  = 00001000
-8 = 11111000

5  = 00000101
-5 = 11111011
If we perform ANDing between x and -x we left with right most set bit. All this takes O(1) time. Now use binary search [ O(log(x)) ] to figure out which bit is set. Given below is code.
int getPosition(unsigned x)
{
    // ASSUMPTION: x will not be zero

    // left, right and mid position
    int l = 0, r = 33, mid = 0;
    // temp value
    unsigned temp;

    // Iterate till we find the bit position
    while(l < r)
    {
        // ((r - l) >> 1) + l - Is more effective??
        mid = (l + r) >> 1;

        // Set the most possible significant bit
        temp = (1 << (mid - 1));

        if(temp == x)
        {
            break;
        }
        else if(temp < x)
        {
            // Bit is in the higher half
            l = mid;
        }
        else
        {
            // Bit is in the lower half
            r = mid;
        }
    }

    // Return mid itself if bits
    // are positioned from 1 to 32
    return (mid-1);
}

int getRightMostSetBit(unsigned x)
{
    // Return 0 if x is zero
    int position = 0;

    // Avoid multiple return statements
    if(x != 0)
    {
        // Make the integer passes as least power of 2
        // Call the position locator
        position = getPosition(x & -(signed)x);
    }

    return position;
}
If you find any errors, please let me know.

Counting bits in an integer

September 11th, 2010

I have simple approach as it was mentioned in the bit reversal algorithm. We can add the adjacent bits in each one bit position, two bit positions, four bit positions, etc… until we reach the number of bits in integer. I am providing pseudo code,
1. Add bits in positions (0, 1), (2, 3) so on (30, 31)
2. Add bits in positions (01, 23), (45, 67) so on (28 29, 30 31)
3. Add bits in positions (0123, 4567).....
4. Add bits in positions (01234567, 8 9 10 11 12 13 14 15)
5. Add the bits in first half and second half of the integer.
The algorithm takes log(N) steps to count the bits in integer.
An example will clarify it more clearly
Let us take 0x12345678, the corresponding binary representation can be written easily (it has 13 set bits)
00010010001101000101011001111000
00 01 00 10 00 11 01 00 01 01 01 10 01 11 10 00
After step 1 we get
00 01 00 01 00 10 01 00 01 01 01 01 01 10 01 00
After step 2 we get
00 01 00 01 00 10 01 00 01 01 01 01 01 10 01 00
0001 0001 0010 0001 0010 0010 0011 0001
After step 3 we get
0001 0001 0010 0001 0010 0010 0011 0001
00000010 00000011 00000100 00000100
After step 4 we get
00000010 00000011 00000100 00000100
0000000000000101 0000000000001000
After step 5 we get
0000000000000101 0000000000001000
00000000000000000000000000001101 – (13) Which is required result
The algorithm can be implemented using shifts and addition operation. There are multiple algorithms out there to compute number of set bits in an integer. For few of such algorithms see the following link
Depending on context we can choose right algorithm.

Wednesday, August 25, 2010

Open-Close doors puzzle

August 25, 2010
I come across an interesting puzzle on Gulli’s blog.
Given a number N, how may factor does it have? For example 4 has 1, 2 and 4 as factor, total 3. Can we generalize? Yes, we can.
Any number can be expressed as powers of prime numbers. Assume ‘x’ is prime in the following,
N = xm – then N will have (m+1) factors. It is not necessary that N limits to one prime, an number can be power of more than one prime number.
N = xm * yn – in this case N will have (n+1)*(m+1) factors.
Here is interesting puzzle from the book introduction to algorithms by Anany V. Levitin,
“Locker doors: There are N lockers in a hallway, numbered sequentially from 1 to N. Initially all the locker doors are closed. You make N passes by the locker, each time starting with locker #1. on the kth pass. K = 1, 2, … N, you toggle the door of every kth locker, i.e. if the door is locked, open it and if the door is closed, open it. On the second pass toggle 2nd, 4th, 6th … so on doors. After last pass (Nth) how many doors are closed and how many are opened?”
From the Euler’s analogy, each number except perfect square will even number of factors and perfect squares will have odd number of factors. Using the fact, we can conclude those number which are perfect squares must be toggled odd number of times, and other doors even number of times. Hence only those doors represent perfect square numbers will be toggled from their original position (i.e. they will be in open position if initially closed and vice versa). All other doors will be in their initial position.
Similar sort of puzzle we can found in the book “Heard on the Street”.

Monday, August 23, 2010

http://geeksforgeeks.org/

24th, August 2010
Few months ago I found one interesting website regarding computing related queries. You can visit the same on http://geeksforgeeks.org/ maintained by group of REC friends. Worth reading who interested in learning. I suggest those who comments to be precise. I am also posting as member Venki.

Thursday, August 19, 2010

Script Engines in Browser

20th, August 2010

Most of us not aware of the technology behind a web browser. A script will be used for client side scripting to enhance user interface in dynamic websites. Inside the browser an engine (script engine) will be running to parse this script and renders the image.
Web browser will be next generation computing platform. I have come across two advanced Java Script engines. These technologies are interesting, you can see them in the following links.
What do you say? Browser war started again between two digital revolution giants? Who will be the winner?
In my opinion “common man” is the ultimate winner.

Saturday, August 14, 2010

Care about small thinks as well during interview

14th August, 2010
Don’t do it! J
I come across interesting interview story on the web. It goes as following…
A final story
I'd like to leave you with a story of an unfortunate interview. Draw hope that no matter how your interview goes, you will likely be more lucky than this candidate.
At Microsoft, we always offered drinks to our candidates, and one candidate "Jeff" took a pepsi. We got into my office, and he set it down on the desk. We started discussing his experiences and then launched into the whiteboard coding question, and he didn't get around to opening his pepsi.
We stood at the whiteboard, and Jeff started to write a line of code. He stopped to think about the overall algorithm, and absentmindedly took a step back in order to see the entire whiteboard. In doing so, he inadvertently knocked against the desk, and the pepsi fell off the edge.
This pepsi was still unopened. Thus, when it hit the ground, it exploded on impact.
Pepsi sprayed in foamy gusts in all directions from the can. It was a slow-motion moment as beige spots of soda splashed onto my white walls, my bookshelf, my keyboard. We both stood there frozen, our hands halfway out (too slow to catch the pepsi), looking at the dripping liquid coating the entire inside of my office.
We took a 5-minute break to get paper towels and mop up the mess. (Though my books always stuck together after that day, and my walls were never the same again.)
We then returned to the whiteboard question. Jeff was nervous by this time (understandably). He wrote some code, erased it, wrote more. He erased using his fingers against the board instead of using the eraser. Then sweat formed on his forehead, and he wiped it off using the same hand. By the end of the interview, his face was covered in streaks of red, green, and blue whiteboard marker.
I said, "I think you have some marker on your hands. I'll show you the restroom." and let the bathroom mirror show him the problem.
Moral: Caring small things value lot.

Wednesday, August 11, 2010

P ≠ NP - Vinay Deolalikar



12th August, 2010
An interesting paper about class P and class NP problems. I read it on Gulli blgo, the same published on Bangalore Mirror next day. You can find the article here…
Thanks to Gulli for posting it on his blog.

Saturday, August 7, 2010

Complicated declarations in C and C++

8th, August, 2010

Complicated declarations in C and C++
I have seen few questions related to complicated declarations in C and C++. For example see the following,
  1. Declare a function with argument of int* which returns pointer to an array of integer pointers, http://geeksforgeeks.org/forum/topic/tcs-interview-question-about-cpuzzles-1
  2. What does int (*fun2())[4] and int (*fun3)[3][4] mean? Posted on Geeksforgeeks site http://geeksforgeeks.org/forum/topic/pointer-doubt
Answer for case 1, int *(*foo(int *arg))[4];
‘foo’ is function taking integer argument and returning pointer to array of integer pointers.
An example code,
#include

// Symbolic size
#define SIZE_OF_ARRAY (4)
// pointer to array of (SIZE_OF_ARRAY) integers
typedef int *(*p_array_t)[SIZE_OF_ARRAY];

// Declaration : compiler should throw error
// if not matched with definition
int *(*foo(int *arg))[4];

// Definition  : foo returning pointer to an
// array of integer pointers
p_array_t foo(int *arg)
{
    // array of integer pointers
    static int *arr[SIZE_OF_ARRAY] = {NULL};
   
    // return this
    p_array_t pRet = &arr;
   
    return pRet;
}

void main()
{}
Let us see the other two declarations.
CASE 1: int (*fun2())[4];
int (*fun2())[4];
fun2() - A function taking no arguments, returning a pointer to array of 4 integers.
Let us see how I came to this conclusion.
In C and C++, every declaration will contain one declarator and one or more declaration specifiers. In the current declaration 'fun2' is declarator (an identifier in program context) and 'int', '4' are declaration specifiers. Dropping the declarator leaves the type information. So, the following is type
int(*())[4];
The parenthesis binds to the declarator due to their precedence. Further, the type information can be reduced to,
int(*)[4];
It is now clear that the above declaration is pointer to array of 4 integers.
Finally, the identifier 'fun2' is "a function with no arguments and returning pointer to array of 4 integers".
CASE 2: int(*fun3)[3][4];
It is pretty simple from the above description.
int(*fun3)[3][4];
After dropping the declarator we left with,
int(*)[3][4];
which is pointer to array of array of integers (dimensions are obvious).
So, the identifier 'fun3' is "a pointer to array of array of integers".
For more information, read the documentation related to C and C++ programming language references on MSDN.