Saturday, November 8, 2014

Is strtok safe !?

We all know that strtok is the most convenient way we all use to tokenize strings.

Syntax:
        #include <string.h>
        char *strtok(char *str, const char *delim);
        where,
        string to be tokenized
        delim - set of delimiters to be used while tokenizing

Example:

#include <iostream>
#include <string.h>
using namespace std;

int main()
{
    char paragraph[] = "Hello$Funny$Man"; // String where words a seperated  by $ 
    // We need to tokenize above string
    char* tok;
    tok = strtok(paragraph,"$"); //  extract the word using $ as a delimiter
    while(tok)
    {
        cout << "Extracted word is " << tok << endl;
        tok = strtok(NULL,"$");
    }
    return 0;
}


Output: 

Extracted word is Hello
Extracted word is Funny
Extracted word is Man


Now is it the safest way to tokenize string/char-array? Do we see any problem with this method ?
What happens when we have to sub-tokenize the extracted token ? Let see with the below example.


#include <iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;

int main()
{
    char paragraph[] = "Hello$Funny$Man How$are$you$doing?"; // String where sentence a seperated by space and words by $ 
    // We need to tokenize above string
    char* tok;
    tok = strtok(paragraph," "); // Firstly extract the sentence using space as a delimiter
    int count = 0;
    while(tok)
    {
        char* subtok;
        char* sentence = strdup(tok);
        subtok = strtok(sentence,"$");
        count++;
        while(subtok)
        {
            cout << "Extracted word in sentence " << count << " is " << subtok << endl;
            subtok = strtok(NULL,"$");
        }
        free(sentence);
        tok = strtok(NULL," ");
    }
    return 0;
}


Output: 

Extracted word in sentence 1 is Hello
Extracted word in sentence 1 is Funny
Extracted word in sentence 1 is Man

We can observe that only one sentence was extracted, this happens because, if we closely observe the usage of strtok, strtok takes source string to be tokenized only in its first call, from the second call on-wards it takes NULL as the first argument, which means strtok uses some global scope space to store the pointer(point to which it has tokenized)

If we use strtok both in outer loops and inner loops, it only runs the outer-loop once as we saw in above example. Since there is only one common global pointer and by the time inner loop is completely executed, this global pointer points to NULL, and hence the actual outer loop pointer(point to which it has tokenized) is lost.Therefore it exits out of outer loop assuming it has tokenized completely.

How do we solve this problem?? well we don't we to do anything, this is a open secret which is in the man page of strtok.
string.h also has an another API called strtok_r which takes in an additional parameter to store the context of the string/char-array i.e point to which it has tokenized.

Syntax:
        #include <string.h>
        char *strtok_r(char *str, const char *delim, char **saveptr);
       where,
        str - string to be tokenized
        delim - set of delimiters to be used while tokenizing
        saveptr - additional pointer to save the context

As per man page its strtok_r() function is a reentrant version strtok(). The saveptr argument is a pointer to a char * variable that is used internally by strtok_r() in order to maintain context between successive calls that parse the same string.

Lets us use strtok_r and see if it solves above problem or not.



#include <iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;

int main()
{
    char paragraph[] = "Hello$Funny$Man How$are$you$doing?"; // String where sentence a seperated by space and words by $ 
    // We need to tokenize above string
    char* tok;
    char *savePtr1, *savePtr2;
    tok = strtok_r(paragraph," ", &savePtr1); // Firstly extract the sentence using space as a delimiter
    int count = 0;
    while(tok)
    {
        char* subtok;
        char* sentence = strdup(tok);
        subtok = strtok_r(sentence,"$",&savePtr2);
        count++;
        while(subtok)
        {
            cout << "Extracted word in sentence " << count << " is " << subtok << endl;
            subtok = strtok_r(NULL,"$",&savePtr2);
        }
        free(sentence);
        tok = strtok_r(NULL," ", &savePtr1);
    }
    return 0;
}


Output:

Extracted word in sentence 1 is Hello
Extracted word in sentence 1 is Funny
Extracted word in sentence 1 is Man
Extracted word in sentence 2 is How
Extracted word in sentence 2 is are
Extracted word in sentence 2 is you
Extracted word in sentence 2 is doing?


From the above output we can observe that the problem is solved as both the sentences are tokenized. So its always best practice to use strtok_r when you know that your program is going to use strtok in recursions or threads or nested-loops or to put the other way around would be use strtok only if you are damn sure that your program doesn't use strtok in resursions or threads or nested-loops.

Happy Coding !!

Monday, November 3, 2014

Scientific Notation - best way to print floating point numbers

Dealing with floating point numbers is one of the most complex thing which a programmer and computer deal with in a day-to-day programming.

Floating point numbers are real numbers which has a fractional part.
For Eg: 1.234, -2.345 .. etc

As we all know that computers are the integer based machines, [Basically it can understand only 2 voltages high (1) and low (0)], and there are complex ways which includes lots of assumptions and approximations in representing floating point numbers, In this post i will only focus on the best way to print floating point numbers.

There are few standards set by IEEE for using floating point numbers. So coming to printing of floating point numbers on the standard o/p (monitor) or in the file, which is the best practice to be followed ? Which types of notation is more precise and more consistent.... Answer to that would be scientific notation

In scientific notation (which is considered most standard way) any number can be represented in the form :
x*10y

For Eg : 0.2 --> 2*10-1
              200 --> 2*102


The following c++ code and its output could prove to be a simple proof to explain why is scientific method the best way to print floating point numbers.


// Non-scientific way
#include<iostream>  // To print to standard output
#include <iomanip> 
using namespace std;

int main () {

    double shift = 10616.200000000001;
    double num1 = 0;
    double num2 = 0.01;
    
    std::setprecision(15);
    // cout << scientific;

    cout << "(shift + num1) * 1e-3 = " << setw (12) << (shift + num1) * 1e-3 << endl;
    cout << "(shift + num2) * 1e-3 = " << setw (12) << (shift + num2) * 1e-3 << endl;

    return 0;
}

// Output
(shift + num1) * 1e-3 =  10.6162
(shift + num2) * 1e-3 =  10.6162

From above output we can observe that even tough we had set the precision to more than what we need, final result is same irrespective of num1(0) and num2(0.01) begin different.

Now let us try to print the same numbers in scientific way and see the difference. We can just use cout << scientific to print in scientific way. From the above code we need to just remove the comment line.

// Scientific way
#include<iostream>  // To print to standard output
#include <iomanip> 
using namespace std;

int main () {

    double shift = 10616.200000000001;
    double num1 = 0;
    double num2 = 0.01;
    
    std::setprecision(15);
    cout << scientific;

    cout << "(shift + num1) * 1e-3 = " << setw (12) << (shift + num1) * 1e-3 << endl;
    cout << "(shift + num2) * 1e-3 = " << setw (12) << (shift + num2) * 1e-3 << endl;

    return 0;
}

And its output looks like this.

//Output 
(shift + num1) * 1e-3 = 1.061620e+01
(shift + num2) * 1e-3 = 1.061621e+01

We can very clearly observe that the result is different while printing in scientific notation.


Hence scientific notation is the best way as it does not lose more information due to approximations and its safe way to deal with floating point numbers.

A very big thank you to http://hilite.me/ which helped me beautify the code.

Friday, October 24, 2014

Magic Squares

Was just remembering my childhood days this diwali, during childhood which we used to have lots of fun with friends and used to play a lot.

Suddenly remembered that trick which we used to use to fool around with friends, and that's magic-squares.

Magic-Squares is just arrangement of numbers in the square shape where, sum of each of its rows and sum of each of its column and sum of each diagonal is equal to same number.

So now being a computer science enthusiastic, I thought ok.. let me tell my computer (which had g++ compiler) to solve magic-squares.

Here is the result of my computer did. It did all these below ones in less than a fraction of a second ;) :P

NOTE:
After the symbol => is the rowSum
After the symbol \/ is the columnSum
RTLB -- Sum of numbers across Right Top to Left Bottom Diagonal
LTRB -- Sum of numbers across Left Top to Right Bottom Diagonal



Well for those who are interested in having a look at the code, here it is for them.

This is our main function:
 int main()  
 {  
   int num = 0;  
   cout << "Enter any odd number: ";  
   cin >> num;  
   cout << endl << endl;  
   if(num % 2 == 0) {  
     cout << "Even number not supported !! " << endl;  
     return 1;  
   }  
   MagicSquare mSq(num);  
   mSq.computeMagicSquare();  
   return 0;  
 }  

This is the main part where the magic square is begin populated.
   void getRowAndColumn(int& row, int& col, const int counter)  
   {  
     if(counter == 1) { col = num / 2; return;} // Initial condition to insert 0  
     else if(row == 0 && (col == num / 2)) { row = num - 1; col++; return;}  
     else if(col+1 == num && row == 0) { row++; return;}  
     else if(col+1 == num) { col = 0; row--; return;}  
     else if(row == 0) { row = num -1; col++; return;}  
     else if((row!=0) && (col!=num-1) && magicSquare[row-1][col+1] != 0) { row++; return;}  
     else { row--; col++; return;}  
   }  
   void computeMagicSquare(void)  
   {  
   // Printing Dummy Magic Square  
   // Solution for magic square   
   // Step 1 : Placing 1 in the middle of the first row 1st row of the matrix  
     cout << "Printing matrix template:" << endl;  
     printMagicSquare();  
     int counter = 1;  
     int row = 0;  
     int col = 0;  
     while(counter <= num*num)  
     {  
       getRowAndColumn(row, col, counter);  
       // cout << "Row = " << row << "Col = " << col << "Counter = " << counter << endl;  
       if(row < 0 || row >= num || col < 0 || col >= num) cout << "Error in calculating Row/Column Row = " << row  
         << "Column = " << col << endl;  
       magicSquare[row][col] = counter++;  
     }  
     cout << "\n\nPrinting magicSquare: " << num << "*" << num << endl;  
     printMagicSquare();  
   }  
This is the printing portion of the magicSquares.
   void printMagicSquare(void)  
   {  
     int LTRBDiagSum = 0;  
     int LBRTDiagSum = 0;  
     int *columnSum = new int[num];  
     for(int row = 0; row < num; row++)  
     {  
       int rowSum = 0;  
       for(int col = 0; col < num; col++)  
       {  
         rowSum += magicSquare[row][col];  
         if(row == col) LTRBDiagSum += magicSquare[row][col];  
         if(row+col == num-1) LBRTDiagSum += magicSquare[row][col];  
         columnSum[col] += magicSquare[row][col];  
         cout << "\t" << magicSquare[row][col];  
       }  
       cout << " => " << rowSum << endl;  
     }  
     cout << "RTLB(" << LBRTDiagSum << ")";  
     for(int i = 0; i < num; i++)  
     {  
       cout << "\\/";  
       if(i != num-1) cout << "\t";  
     }  
     cout << "LTRB(" << LTRBDiagSum << ")";  
     cout << endl;  
     for(int i = 0; i < num; i++)  
     {  
       cout << "\t" << columnSum[i] ;  
     }  
     cout << endl;  
     delete[] columnSum;  
   }  
And finally our class looked like this
 class MagicSquare {  
   public:  
   MagicSquare(int n)  
   {  
     num = n;  
     magicSquare = new int* [num];  
     for(int i = 0; i < num; i++)  
     {  
       magicSquare[i] = new int[num];  
     }  
   }  
   ~MagicSquare()  
   {  
     for(int i = 0; i < num; i++)  
     {  
       delete[] magicSquare[i];  
     }  
     delete[] magicSquare;  
   }  
   void printMagicSquare(void);  
   void getRowAndColumn(int& row, int& col, const int counter);  
   void computeMagicSquare(void);  
   private:  
   int **magicSquare;  
   int num;  
 };  


Well for those is really interested to execute this source code at your end, you can get the code from here.

I sincerely thank this blog for helping me formatting above code snippets.

Yeah thats it about magic-squares. Lets see if time permits will try to enhance code for even numbers as well.

Sunday, October 19, 2014

Weekend trip from Bengaluru

Bengaluru--Sringeri--Agumbe--Udupi--Dharmastala--Kukke--Bengaluru

Traveling is amazing if you have a good company. This time it was with 2 of my cousins. We just thought bangalore is heating up very much this summer and want to beat the heat by hanging out in some nature's beauty where we can chill out.

So meet the crew :

Nagarjun(L) with Kiran(and thats myself;) )(R)
Nagarjun(L) with Shreyas(R)

Plan :

Initial plan was to leave bangalore on friday evening and then visit Sringeri early in the morning, witness the temples and holy places there, later go to Agumbe and enjoy nature's beauty, which happpend accordingly and the rest of the tour was dynamically planned.

We hired a auto-guy in agumbe who helped us roam around that place.(That place was real nature's beauty)

Meet this auto-guy. (Took his permission to take his photo)
And his auto with his phone number (Took his permission to take this photo as-well)
Here are some of the photos which we captured, Nagarjun did take a lot of photos which i am missing now while writing this post.

The view from the top of the hill was breath-taking.

This is the very ancient temple on the hill.

Looks small but very very deep well.

Amazing is'nt it!! Looks like one of those children slides


Nagarjun and Shreyas busy boating !! (This photo was taken while boating so the photo quality got messed-up;))


After witnessing the world famous sunset point in Agumbe, we headed towards Udupi which is 55 Kms form Agumbe, there are of plenty local mini buses which ply from nearby places to Udupi via Agumbe.

Udupi . We visited Sri Krishna Temple and Madhwa Charya Matha there.
We got chance to see elephant moving the chariot of Lord Sri Krishna and then after evening Aarthi at 8.30 pm we went inside the temple for darshnam, we had a very good darshan and it was very blissful experience to see Lord Sri Krishna of Udupi, At that time of darshan, i was remembering the Madhurastakam which has the line in that as "...Udupiya Sri Krishna ..." It was a very good experience. On the day we visited it was Ekadashi, so we missed the chance to have dinner in temple.

Then next day we woke up early in the morning by 4.00 am and again went to temple to see Subrabatha seva to Sri Lord Krishna and we have again had a very good darshnam and also got a chance to see Abhishekam being perform to Lord Krishna.

Later we headed towards Dharmastala. Saw very famous Sri Dharmasthala Manjunateshwara Temple there. We had to stand in queue for quite some time there as we went during Maha neiveidya timings 11 - 12 noon.

There are many buses with lots of frequency from Dharmastala to Kukke. Went to Sir Kukke Subramanya Swamy temple and it was very pleasant evening, really had a very peaceful time.

We had a return booking from Kukke to Bangalore in KSRTC Airawat we just got in to the bus and by the time we opened our eyes we were in Majestic, Bangalore
Back home :)

Dasara - Navratri Alankaram's (Temples in Yelahanka)

Dasara Times - Temple decorations in Yelahanka-Oldtown

Ardha-Nareshwar Alankaram (Incarnation of Shiva-Parvathi) [Vasavi Devi Temple]



PanchRangi Alankaram (Alankaram with colors) [Yelamma Devi Temple]



Saraswathi Alankaram [Vasavi Devi Temple]



Shiva-Parvathi in Pancharangi Alankaram (Alankaram with Colors) [Vasavi Devi Temple]



Shiv Ji (Har Har Mahadev) [Vasavi Devi Temple]



Lakshmi Narayana in Sindhur-Carpoor Alankaram [Vasavi Devi Temple]



Ganesh ji in Pancharangi Alankaram [Vasavi Devi Temple]



Swaamiye Sharam Aiyappa [Muneeshwara Swamy Temple]



Saraswathi Alankaram [Chowdeshwari Devi Temple]



Subramanya Swamy in Chandan Alankaram [Chowdeshwari Devi Temple]



Ganesh ji in Benne (Butter) Alankaram [Chowdeshwari Devi Temple]



Sri MahaVishnu [ Muneeshwara Swamy Temple]



Durga Devi Alankaram [Chowdeshwari Devi Temple]



Sri Parvathi Parameshwara in Chandan Alankaram [Vasavi Devi Temple]



Durga Devi Alankaram [Vasavi Devi Temple]



Hatti (Cotton) Alankaram [Vasavi Devi Temple]



Drakshi Godambhi (Resins and Cashew) Alankaram [Chowdeshwari Devi Temple]



Gayatri Devi Alankaram [Vasavi Devi Temple]



Lord Venkateshwara Alankaram [Chowdeshwari Devi Temple]



Vajranghi Alankaram [Sri Ganesh Temple]



Droupadi Devi Alankaram [Maheshwari Devi Temple]