Programming with Passion

Make the best out of everything.

Monday, 6 April 2015

easiest program, after "Hello World"

This must be the easiest program, after "Hello World", we have ever written.
Even we don't need a compiler to test the result, right? We can submit it blindly if we get such question in our Competitive Programming world, won't we?
Nevertheless, this might be the most frequently asked, most famous question in interviews, oh I forgot, with a additional condition of Don't use any temporary variable! Did your interviewer not ask this?
Today I have few methods for doing the same.
This is going to be a quite short and quick post, but yet I will give you an important/useful note at the end. This is not which I have planned, but it struck my mind and I thought it's worth sharing.
So, Lets start with our different solutions:-
For all the solutions, Consider a & b are our variables. a = 5 and b = 10.
 1. Using the temporary variable

    void swap(int &a, int &b)
    {
        int temp = a;
        a = b;
        b = temp;
    }

2. Without using temporary variable, with addition-subtraction

    void swap(int &a, int &b)
    {
        a = a + b;
        b = a - b;
        a = a - b;
    }

 3. Without using temporary variable, with multiplication-division

    void swap(int &a, int &b)
    {
        a = a * b;
        b = a / b;
        a = a / b;
    }

 4. Without using temporary variable, with XOR operation

    void swap(int &a, int &b)
    {
        a = a ^ b;
        b = a ^ b;
        a = a ^ b;
    }

 5. One liner with addition-subtraction

    void swap(int &a, int &b)
    {
        a = a + b - (b = a);
    }

 6. One liner with multiplication-division

    void swap(int &a, int &b)
    {
        a = a * b / (b = a);
    }

 7. One liner with XOR

    void swap(int &a, int &b)
    {
        a ^= b ^= a ^= b;
    }





Though These one liners or without-temporary-variable thing looks cool, simple and tricky, fancy; these have their own problems associated with them.
Lets have look at problems associated with each method.
Methods 2, 3, 5, 6:
Will these methods give you answer if values of a and b are huge?
say MAX_INT is the maximum value of integer that can be accommodated in a and b.
The moment we add a & b, or multiply them, They are going to overflow, they don't fit in our 32 bit size.
We will get WA (wrong answer).
Methods 3, 6:
Will these method work if any of a or b is 0?
We are going to get Divide by zero error.
Methods 4, 7:
These methods appear to be clean, because they don't fail for any test-case, but again since (as in method 7) value of variable is modified twice within the same sequence point, it is undefined behavior declared by ANSI C.

No comments:

Post a Comment