Monday, July 23, 2012

Power of 2 or not ?

How to find a number is power of 2 or not ?


bool IsPowerOfTwo(unsigned long x)
{
    return (x != 0) && (x & (x - 1)) == 0);
}


Explanation:


The above function returns bool (true/false) and accepts one incoming parameter of type unsigned long (x, in this case). Lets take an example, that someone has passed value 4 to the function like:

bool b = IsPowerOfTwo(4);

Now replace each occurance of x with 4:

return (4 != 0) && ((4 & (4-1)) == 0); 


We already know (4 != 0) , so the evaluation of the expression is true.


((4 & (4-1)) == 0)  translates to:


((4 & (3)) == 0) 


But what exactly is  4&3 ? The binary representation of 4 is 100 and of 3 is 011. The & operation says that if both values are equal to 1, then the result is 1. Otherwise it is 0.

100
011

----
000


The result is simply 0. So we go back and look at what our return statement now translates to:

return (4 != 0) && ((4 & 3) == 0);

Which translates now to:

return true && (0 == 0);

return true && true;

We all know that true && true is simply true, and this shows that for our example, 4 is a power of 2.

const


What is the difference between char const * and char * const ?

According to the standard, const modifies the element directly to its left. The use of
 const  at the beginning of a declaration is just a convenient mental shortcut. So the following two statements are equivalent:

char const * pointerToConstantContent;
const char * pointerToConstantContent;

In order to ensure the pointer itself is not modifiable,  const  should be placed after the asterisk:

char * const constantPointerToMutableContent;

To protect both the pointer and the content to which it points, we should use two consts as below:

char const * const constantPointerToConstantContent;

Monday, July 16, 2012

Search in a Circular Sorted Array

Given a circular sorted array say A = { 2,3,4,5,6,7,8,9,0,1 }, find a number in it.

If the array is not circular, we can use binary search to find the key. But if the array is circular we don't know where is the starting point (pivot element). Obviously we can do a linear search to find the element. But if the input array is very large the worst case performance will be very bad. We can take advantage of the fact that the array is sort and use binary search algorithm to find the element in O(N log N).

Approach:



  • Find the middle value of the input array a.
  • If a[0] < a[mid], then all values in the first half of the array are sorted.
  • If a[mid] < a[last], then all values in the second half of the array are sorted.
  • Take the sorted half, and check whether your value lies within it (key lies between the sorted half).

    • If so, binary search that half.
    • If it doesn't, it must be in the unsorted half. Take that half and repeat this process


     
    #include <iostream>
    #include <vector>
    #include <assert.h>
    
    template<typename T, typename type>
    int binary_search(const T& a, int left, 
                      int right, type key) {
    
        while (left <= right) {
            int mid = (right-left)/2 + left;
    
            // base case 1
            if (a[mid] == key)
                return mid;
    
            // mid less than key. Move to right
            if (a[mid] < key) {
                left = mid+1;
            }
            else {
                right = mid-1;
            }
        }
    
        return -1;
    }
    
    template<typename T, typename type>
    int circular_search(const T& a, int left, 
                        int right, type key) {
    
        // base case 1
        int mid = (right-left)/2 + left;
        if (a[mid] == key)
            return mid;
    
        // left array is sorted.
        if (a[0] < a[mid]) {
    
            if (key > a[left] && key < a[mid]) {
                return binary_search(a, left, mid-1, key);
            }
            else {
                return circular_search(a, mid+1, right, key);
            }
        }
        // right array is sorted
        else if (a[mid] < a[right]) {
            if (key > a[mid] && key < a[right])
                return binary_search(a, mid+1, right, key);
            else
                return circular_search(a, left, mid-1, key);
    
        }
    
        return -1;
    
    }
    
    template<typename T>
    void print(const T&a) {
        typedef typename T::const_iterator iterator;
        iterator start = a.begin();
        iterator end = a.end();
        for(; start!=end; ++start)
            std::cout << *start << " ";
        std::cout << std::endl;
    }
    
    int main() {
        typedef std::vector<int> Input;
        Input temp;
        int n =0;
        
        // get n from user
        std::cin >> n;
    
        for(int i=0; i<n; ++i) {
            temp.push_back(i*2);
        }
        Input data;
        data.resize(temp.size());
    
        // Rotate the input sequence
        std::rotate_copy(temp.begin(), temp.begin()+4, 
                         data1.end(), data.begin());
        print(data);
    
        // get key from user
        int key=0;
        std::cin >> key;
    
        int found = circular_search<Input, int>(data, 0, n-1, key);
        if (found)
        {
            assert(key == data[found]);
            std::cout << data[found] 
                      << " found @ pos " 
                      << found << std::endl;
        }
        else
            std::cout << key 
                      << " not found" 
                      << std::endl;
    
        return 0;
    
    }
    
    

    Friday, July 13, 2012

    Hamming sequence

    Hamming's Problem

    Hamming wants an efficient algorithm that generates the list, in ascending order, of all numbers of the form 2i3j5k for i,j,k at least 0. This list is called the Hamming sequence. The list begins like this:
    1 2 3 4 5 6 8 9 10 12 15 16 18 ...

    Brute force technique:

    Take the first number you haven't checked yet, divide it by 2's, 3's and 5's until you can't do that any more, and if you're left with 1, then the number should go on the list; otherwise throw it away and try the next number. So:
    • Is 19 on the list? No, because it's not divisible by 2, 3, or 5.
    • Is 20 on the list? Yes, because after we divide it by 2, 2, and 5, we're left with 1.
    • Is 21 on the list? No, because after we divide it by 3, we're left with 7, which isn't divisible by 2, 3, or 5.
    This obvious technique has one problem: it's unbelievably slow. The problem is that most numbers aren't on the list, and you waste an immense amount of time discovering that. Although the numbers at the beginning of the list are pretty close together, the 2,999th number in the list is 278,628,139,008. Even if you had enough time to wait for the brute-force algorithm to check all the numbers up to 278,628,139,008, think how much longer you'd have to wait for it to finally find the 3,000 number in the sequence, which is 278,942,752,080.

    Linear Solution:

    The idea is that to calculate a[i], we can use a[j]*2 for some j < i. But we also need to make sure that:
    1) a[j]*2 > a[i - 1] and
    2) j is smallest possible.

    Then, a[i] = min(a[j]*2, a[k]*3, a[t]*5)

     
    #include <iostream>
    #include <algorithm>
    #include <vector>
    using namespace std;
    
    int main(void) {
      // get n from user
      unsigned n;
      cout <<"n: ";
      cin >>n;
    
      // list of ugly numbers
      vector <uint64_t> ugly;
      uint64_t x = 1;
      ugly.push_back(x);
    
      // index of next multiple
      unsigned i2 = 0, i3 = 0, i5 = 0;
    
      // value of next multiple
      uint64_t x2 = 2, x3 = 3, x5 = 5;
    
      // loop through ugly numbers
      for(unsigned a = 1; a < n; a++) {
    
        x = std::min(x2, std::min(x3,x5));
    
        ugly.push_back(x);
        if (x == x2) { i2++; x2 = ugly[i2] * 2; }
        if (x == x3) { i3++; x3 = ugly[i3] * 3; }
        if (x == x5) { i5++; x5 = ugly[i5] * 5; }
      }
    
      // return last ugly number found
      cout << x << endl;
      return 0;
    
    }
    

    Friday, September 25, 2009

    HowEasy - Topcoder Arena

    Problem Statement :
      
    ***Note: Please keep programs under 7000 characters in length. Thank you

    Class Name: HowEasy
    Method Name: pointVal
    Parameters: String
    Returns: int

    TopCoder has decided to automate the process of assigning problem difficulty
    levels to problems. TopCoder developers have concluded that problem difficulty
    is related only to the Average Word Length of Words in the problem statement:

    If the Average Word Length is less than or equal to 3, the problem is a 250
    point problem.
    If the Average Word Length is equal to 4 or 5, the problem is a 500 point
    problem.
    If the Average Word Length is greater than or equal to 6, the problem is a 1000
    point problem.

    Definitions:
    Token - a set of characters bound on either side by spaces, the beginning of
    the input String parameter or the end of the input String parameter.
    Word - a Token that contains only letters (a-z or A-Z) and may end with a
    single period. A Word must have at least one letter.
    Word Length - the number of letters in a Word. (NOTE: a period is NOT a letter)

    The following are Words :
    "ab", "ab."

    The following are not Words :
    "ab..", "a.b", ".ab", "a.b.", "a2b.", "."

    Average Word Length - the sum of the Word Lengths of every Word in the problem
    statement divided by the number of Words in the problem statement. The
    division is integer division. If the number of Words is 0, the Average Word
    Length is 0.

    Implement a class HowEasy, which contains a method pointVal. The method takes
    a String as a parameter that is the problem statement and returns an int that
    is the point value of the problem (250, 500, or 1000). The problem statement
    should be processed from left to right.

    Here is the method signature (be sure your method is public):
    int pointVal(String problemStatement);

    problemStatement is a String containing between 1 and 50 letters, numbers,
    spaces, or periods. TopCoder will ensure the input is valid.

    Examples:

    If problemStatement="This is a problem statement", the Average Word Length is
    23/5=4, so the method should return 500.
    If problemStatement="523hi.", there are no Words, so the Average Word Length is
    0, and the method should return 250.
    If problemStatement="Implement a class H5 which contains some method." the
    Average Word Length is 38/7=5 and the method should return 500.
    If problemStatement=" no9 . wor7ds he8re. hj.." the Average Word Length is 0,
    and the method should return 250.
    Definition
      
    Class: HowEasy
    Method: pointVal
    Parameters: string
    Returns: int
    Method signature: int pointVal(string param0)
    (be sure your method is public)
     
     
    #include <iostream>
    #include <sstream>
    #include <string>
    
    const static 
    std::string g_LegalCharacters =  "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    
    class HowEasy
    {
        public:
            int pointVal(std::string problemStmt);
    
        private:
            inline bool isValid(std::string &token);
            inline int problemValue (unsigned int length);
    };
    
    bool HowEasy::isValid(std::string &token)
    {
        if (token.empty()) return 0;
    
        size_t pos = token.find_first_not_of(g_LegalCharacters);
        return (pos == std::string::npos);
    }
    
    int HowEasy::pointVal(std::string problemStmt)
    {
        std::istringstream iss;
        iss.str( problemStmt );
    
        std::string token;
        unsigned int nWords = 0;
        unsigned int lWords = 0;
        unsigned int average = 0;
        int points = 0;
        std::string validString;
        while (!iss.eof())
        {
            iss >> token;
            if (token.length())
            {
                if (token[token.length() - 1] == '.')
                    token.erase(token.end() - 1);
    
                if (isValid(token))
                {
                    ++nWords;
                    lWords += token.length();
                    validString += token;
                }
            }
        }
        
        if (lWords && nWords)
            average = lWords / nWords;
            
        points =  problemValue (average);        
        return points;    
    }
    
    int HowEasy::problemValue (unsigned int length)
    {
        if (length <= 3)
            return 250;
        else if (length <= 5)
            return 500;
        else
            return 1000;
    }
    
    

    Wednesday, September 09, 2009

    Compare Vector V1 and V2 for equality

    Here are the ways to compare two vectors.

    Method 1:
     
    #include < iostream >
    using std::cout;
    using std::endl;
    
    #include < algorithm >
    #include < vector >
    #include < iterator >
    
    int main()
    {
       int a1[ 10 ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
       int a2[ 10 ] = { 1, 2, 3, 4, 9, 6, 7, 8, 9, 10 };
       std::vector<> v1( a1, a1 + 10 );
       std::vector<> v2( a1, a1 + 10 );
       std::vector<> v3( a2, a2 + 10 );
       std::ostream_iterator<> output( cout, " " );
    
       cout << "Vector v1 contains: ";    
       std::copy( v1.begin(), v1.end(), output );    
       cout << "\nVector v2 contains: ";
       std::copy( v2.begin(), v2.end(), output );
       cout << "\nVector v3 contains: ";
       std::copy( v3.begin(), v3.end(), output );
    
       // compare vectors v1 and v2 for equality    
       bool result = std::equal( v1.begin(), v1.end(), v2.begin() );    
       cout << "\n\nVector v1 " 
            << ( result ? "is" : "is not" )
            << " equal to vector v2.\n"
            return 0;
    }
    


    Method 2:

    Overload the == operator for comparision

     
    
    inline bool operator == (const std::vector< std::string >, 
                             const std::vector< std::string >)
    {
        if (lhs.size() != rhs.size())
            return false;
    
        int count = lhs.size();
        std::vector< std::string >::const_iterator lhsi = lhs.begin();
        std::vector< std::string >::const_iterator rhsi = rhs.begin();
        while (count--)
        {
            if ( *lhsi != *rhsi)
                return false;
            lhsi++; rhsi++;
        }
        return true;
    }
    


    Monday, July 27, 2009

    Convert "man page" into text file

    Save a man page into text file

    Option #1



    man -P cat ls > man_ls.txt


    Option #2:



    man ls | col -b > ls.txt

    Wednesday, July 15, 2009

    First try in C#

    Here is my first try in C#


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace dotNet
    {
    class Greeting
    {
    public static int displayGanesh()
    {
    Console.WriteLine("Ganesh Here !!");
    return 0;
    }
    public static int displayVishnu()
    {
    Console.WriteLine("Vishnu Here !!");
    return 1;
    }
    }

    delegate int delGreetings();

    class Program
    {
    static void Main(string[] args)
    {
    int choice = 1;
    delGreetings[] Greetings =
    {
    new delGreetings(Greeting.displayGanesh),
    new delGreetings(Greeting.displayVishnu)
    };
    int return_ = Greetings[choice - 1]();
    Console.Write("Return Value ");
    Console.WriteLine(return_);
    return;
    }
    }
    }



    delegate is basically defines the function pointer.
    In the below snippet, it defines a function pointer which
    takes no arguments and returns an int value.


    delegate int delGreetings();




    Happy Hacking !!

    Tuesday, July 14, 2009

    Visual Studio .Net 2008 Cheat sheet

    For all the C# fans out there, today I came across this excellent keyboard cheat sheet and Jeff's Summary Macro to generate the full list of VS 2008 cheat sheet in HTML format.

    Here is the steps to generate the cheatsheet for yourself. Skip to down under if you wish to get the generated cheatsheet.

    Download the Keyboard shortcut Summary macro

    How to install and run the macro ??
    1. go to Tools - Macros - IDE
    2. Create a new Module named "KeyboardShortcuts" under "MyMacros"
    3. Paste the above code into the module
    4. Add a reference to the System.Data.dll and System.XML.dll ; make sure it builds with no errors
    5. Close the macro IDE window
    6. go to Tools - Macros - Macro Explorer
    7. A new macro named "List" will be under "KeyboardShortcuts." Double-click it to run the macro
    8. The macro will take a moment to write the keyboard shortcuts to a HTML file, then open the HTML file in the IDE.
    This is tested against VS 2008 and the macro generates the HTML file :

    C:\Users\mganesh\Documents\Visual Studio .NET 20xx Keyboard Shortcuts.htm

    This is the file location in my Win 7 OS.

    The cheat sheet result for the Visual Studio 2008 default C# keyboard shortcuts is posted to save people the trouble of getting the macro running. It's here.

    Monday, June 29, 2009

    Building Boost Lib 1.35 with VC++ 2008

    Version 1.35 of the Boost libraries was released on March 29th, 2008.

    Below are the steps I followed to have everything working on Win 7.

    If not already done, install the following development tools (in the prescribed order, please):

    Visual C++ 2008 Express Edition
    Microsoft Windows SDK
    Microsoft Compute Cluster Pack SDK

    The last one will only be needed if you plan to compile the Boost.MPI library.

    Download and install Python. Download Boost 1.35 and the latest Boost Jam binary (3.1.17 at the time of this writing). Copy the bjam executable to the Boost root directory. Next, disable the automatic linking features of the Microsoft Visual C++ compiler by enabling the BOOST_ALL_NO_LIB macro on the file user.hpp (boost/config/user.hpp). We’re ready to go (type all the commands inside the Visual Studio 2008 Command Prompt):

    “bjam stage”

    Boost Jam auto detects the Visual C++ 2008 compiler!

    If you want to compile the Boost.MPI library a couple of additional steps must be followed. Boost Jam is your friend as it prints it nicely for you:

    warning: skipping optional Message Passing Interface (MPI) library.
    note: to enable MPI support, add “using mpi ;” to user-config.jam.
    note: to suppress this message, pass “–without-mpi” to bjam.
    note: otherwise, you can safely ignore this message.

    Follow the instructions. The user-config.jam is to be created in your “current” directory ($BOOST_ROOT_DIR\tools\build\v2).

    Now build the Boost.MPI library by issuing:

    “bjam –with-mpi stage”

    The Microsoft MPI library is auto detected!

    That is it! Happy Hacking :)

    Sunday, June 28, 2009

    Anbe Vaa - Vijay TV's New serial

    Here you go. Me and Mani has become a big fan of this title song .. Thats a soft melody song .. Here is the lyrics for the song.

    Guys, if u get a chance, hear this song in Vijay TV :)

    Ah.. ah... (Female Voice)
     
    (Male voice)
    Oru paarvai paarkirai..
    pudhidhai nan pookiren..
    Idhayam idam maarudhe..
    Idhu kaadhala...

    Nilavodu theigiren..
    Ninaivale karaigiren..
    sugamana vedhanai..
    Idhu kaadala...

    Engeyo.. engeyo.. 
    ennule engeyo..
    vinmeengal sidharudhe
    yaenadi..

    Anbe vaa..
    Anbe vaa..
    Anbe vaa
    Anbe vaa.. a...

    Ah...

    (Female)
    Kannukule kannukule.. kaadhal vandhu nenjai thotu povathen.. 
    (Male)
    Enna idhu enna idhu.. vaanavillil vanam rendu koodudhe..
    (Female)
    Theendinal.. vaanile..
    megamai alaigiren
    (male)
    neenginal dhoorathil..
    pulliyai tholaigiren..

    Nillarendral nillaamal
    yenendru kelaamal
    edhedho seigirai..
    yaenadi..

    Anbe vaa..
    Anbe vaa..
    Anbe vaa
    Anbe vaa.. a...

    (F)Enna solli enna solli kaadhal adhai unnidathil kaatuven..
    (m)Sathamindri sathamindri mounamai nenjukulle pootuven..
    (F)kavithaigal ezhudhida vaarthaigal thedinen..
    (M)un peyar  ezhudhinaal kavidhayai paadinen..

    Enn ulle en ulle..
    un kannin minsaram..
    edhedho seiyudhe.. 
    Yaenadi..


    Anbe vaa..
    Anbe vaa..
    Anbe vaa
    Anbe vaa.. a...

    Thursday, June 25, 2009

    Secrets of std::map

    I should admit that I'm very poor in C++ Programming. Today, me and one of colleague was trying to understand a code writter by one of a pioneer in our team. We initially thought he wrote a crabby code but indeed we were wrong and he proved his expertness :)

    Below is the snippet of similar case.



    #include "stdafx.h"
    #include < iostream >
    #include < map >

    int main()
    {
    // 1. define the map
    typedef std::map Map;

    // 2. Create the object for it
    Map myMap;

    for (int i=0; i<10; ++i)
    {
    /****************************
    3. Whats going on here ???.
    We just created the object.
    Could this be a buggy code ??

    Nope. When we reference an item in map
    and if the item is not available,
    it creates the object. Great :)

    I personally seen/used the creation
    of map on the left side,
    something like myMap[2] = 20
    But the below is of something which
    I am seeing new today :)
    **********************************************/

    int &ref = myMap[i];
    ref = i;

    }
    for (int i=0; i<10; ++i)
    {
    std::cout << myMap[i] << " ";
    }
    std::cout << std::endl;

    return 0;
    }



    Happy Hacking :)

    Monday, June 22, 2009

    C++ forward declaration error

    Problem:

    I am trying to declare and use a class B inside of a class A and define B outside A.I know for a fact that this is possible because Bjarne Stroustrup uses this in his book "The C++ programming language" (page 293,for example the String and Srep classes). So this is my minimal piece of code that causes problems.

    class A
    {
    struct B; // forward declaration
    B* c; A()
    {
    c->i;
    }
    };

    struct A::B
    {
    /** we define struct B like this
    ** becuase it was first declared
    ** in the namespace A */

    int i;
    };
    int main()
    {

    }


    Error:

    This code gives the following compilation errors in g++ : tst.cpp: In constructor ‘A::A()’: tst.cpp:5: error: invalid use of undefined type ‘struct A::B’ tst.cpp:3: error: forward declaration of ‘struct A::B’

    Solution:

    Define the constructor for A AFTER the definition of struct B.

    Sunday, June 14, 2009

    Sambhar Receipe

    Step 1:
    Put Onions, Tomato, Chilly, Coriander leaf, 1 Spn of Turmeric Cumin powder (from Amma) in a pressure cooker and keep 3 Whistle.

    Step 2:

    Put all the needed vegetables in the same pressure cooker and add 1/5 Spn of chilly power, salt to taste. Keep for one more whistle.

    Sambhar is ready ;)

    Thursday, February 26, 2009

    How to get the elapsed time in millisecs

    Finding an elapsed time of a function/API/method will help you to understand its performance and the most of our manager/management will hails u if you give them a nice performance graph/chart of an application :)

    My Approach:
    You can use gettimeofday at the start and end of your method and then the difference the two will give the elapsed time .. You'll get a structure like the one below:


    struct timeval {
    time_t tv_sec; /* in secs */
    suseconds_t tv_usec; /* in Microseconds */
    };


    Code snippet:


    #include
    #include
    #include
    int main()
    {
    struct timeval start, end;
    long mtime, seconds, useconds;

    // Get the start time
    gettimeofday(&start, NULL);

    // Here you go with your method call
    usleep(2000);

    // note the end time
    gettimeofday(&end, NULL);

    seconds = end.tv_sec - start.tv_sec;
    useconds = end.tv_usec - start.tv_usec;

    mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5;

    printf("Elapsed time: %ld milliseconds\n", mtime);

    return 0;
    }


    Wednesday, February 25, 2009

    Python: Human readable time span given total secs

    Problem:

    Function takes an amount of time in seconds and returns a human readable time span.

    Input: 14723 (in secs)
    Output : 4h 5m 23s

    Suffixes used:

    y - year
    w - week
    d - days
    h - hours
    m - min
    s - sec

    Code:


    #!/usr/bin/env python
    def elapsed_time (seconds, suffixes=['y','w','d','h','m','s'], add_s=False, separator=' '):
    """
    Takes an amount of seconds and turns it into a human-readable amount of time.
    """
    # the formatted time string to be returned
    time = []

    # the pieces of time to iterate over (days, hours, minutes, etc)
    # - the first piece in each tuple is the suffix (d, h, w)
    # - the second piece is the length in seconds (a day is 60s * 60m * 24h)
    parts = [(suffixes[0], 60 * 60 * 24 * 7 * 52),
    (suffixes[1], 60 * 60 * 24 * 7),
    (suffixes[2], 60 * 60 * 24),
    (suffixes[3], 60 * 60),
    (suffixes[4], 60),
    (suffixes[5], 1)]

    # for each time piece, grab the value and remaining seconds, and add it to
    # the time string
    for suffix, length in parts:
    value = seconds / length
    if value > 0:
    seconds = seconds % length
    time.append('%s%s' % (str(value),
    (suffix, (suffix, suffix + 's')[value > 1])[add_s]))
    if seconds < 1:
    break

    return separator.join(time)

    if __name__ == '__main__':
    # 2 years, 1 week, 6 days, 2 hours, 59 minutes, 23 seconds
    # 2y 1w 6d 2h 59m 23s
    seconds = (60 * 60 * 24 * 7 * 52 * 2) + (60 * 60 * 24 * 7 * 1) + (60 * 60 * 24 * 6) + (60 * 60 * 2) + (60 * 59) + (1 * 23)
    print elapsed_time(seconds)
    print elapsed_time(seconds, [' year',' week',' day',' hour',' minute',' second'])
    print elapsed_time(seconds, [' year',' week',' day',' hour',' minute',' second'], add_s=True)
    print elapsed_time(seconds, [' year',' week',' day',' hour',' minute',' second'], add_s=True, separator=', ')



    Output:

    [10:13:34 gmuniyan@lnl43a-3102] /home/gmuniyan/python>./elapsedTime.py
    2y 1w 6d 2h 59m 23s
    2 year 1 week 6 day 2 hour 59 minute 23 second
    2 years 1 week 6 days 2 hours 59 minutes 23 seconds
    2 years, 1 week, 6 days, 2 hours, 59 minutes, 23 seconds

    Honor: Original Post

    Tuesday, February 24, 2009

    Running a cmd from bash script

    Problem:

    There are many situations in which you may want to run different command in your shell script depending on requirements and circumstances.

    There are two approaches we can take from here on.

    Approach #1:

    Use either case statement or if..elif..else For example:



    #!/bin/bash
    if [ this -eq that ];then
    command1
    else
    command2
    fi



    Approach #2:

    BASH allows you to assign/store a command in a built-in variable called CMD. Build your command in this variable and execute $CMD.



    #!/bin/bash
    [ this -eq that ] && CMD=”/bin/ls” || CMD="/bin/date";
    eval $CMD;



    This is a very simple example and this approach is very much generic if you want to have a generic function to execute all the commands. For example:



    #!/bin/bash

    execute() {
    # $1 holds the arg to this function
    CMD="$1";
    eval $CMD;
    }

    ## Here is your main function

    if [ this -eq that]
    then
    execute "/bin/ls | wc -l";
    else
    execute "/bin/ls";
    fi



    NOTE: eval is required when you use "|" or redirection of cmd output.

    Happy hacking :) !!

    Monday, February 23, 2009

    Python: Processing cmd line args

    Next thing that you might be interested to learn after the historic "Hello World" program is to know how to process the cmd line arguments.

    Method #1: Using sys:


    #! /usr/bin/python

    import sys;

    if __name__ == "__main__":
    for args in sys.argv:
    print args;




    Output:

    # cmdLine.py 1 2 3 4
    cmdLine.py
    1
    2
    3
    4

    Python: Hello World

    This is my first post against Python, watchout for more to come soon ...

    Python way of saying "Hello world" :)


    #!/usr/bin/env python

    ## In Python each module will have a name associated with it
    ## And here is the main module

    if __name__ == "__main__":
    print "Hello World";

    Sunday, February 01, 2009

    Show that 2^n is O(n!)

    This is an interview question from MS.

    Answer:

    n! = 2*3*...*n >= 2*2*...*2 = 2^(n-1)

    Since 2^n <= 2*n! for all n, we have that 2^n = O(n!).