Tuesday, December 4, 2007

Version Parser

Hi,

This is the problem which i have extracted from one of the problem statements sent by one of my friend.


main()
{
int nVer1=0,nVer2=0,nVer3=0,nVer4=0;

char szVersion[100]= "1.234.5678.9012";

// only one statement is allowed here. You can use any of the ANSI C library functions.

printf(“Ver1 = %d \nVer2 =%d \nVer3 =%d \nVer4 = %d”,nVer1,nVer2,nVer3,nVer4);
}

The output should be
Ver1 = 1
Ver2 = 234
Ver3 = 5678
Ver4 = 9012

I have sent this problem to my several friend groups and i got the following solutions:

1. for(nVer1=strtol(szVersion, &szVersion,0),nVer2=strtol(((char*)szVersion)+1, &szVersion,0),nVer3=strtol(((char*)szVersion)+1, &szVersion,0),nVer4=strtol(((char*)szVersion)+1, &szVersion,0);nVer1==-1 ;);

2. nVer1 = atoi(strtok(szVersion),"."),nVer2 = atoi(strtok(NULL),"."),nVer3 = atoi(strtok(NULL),"."),nVer4 = atoi(strtok(NULL),".");

3. sscanf ( szVersion, "%d.%d.%d,%d",&nVer1,&nVer2,&nVer3,&nVer4);



The third one is what i got in mind and also has been sent by one of my friends. I feel third one is the correct one since other two solutions just combine two or more statements to make it in a single line and those are not single statements .


If you got any other solution or any comments on this solution please leave your valuable comments.

1 comment:

Unknown said...

Engal Debug Singam aanand Vaazhga!!!

Ennodadhu dhaan 1st Comment!!!

Keep posting problems like this...

-- Manikandan Somasundaram