Wednesday 27 April 2011

Example of Algorithm Copy

Sometimes its useful to know the 'copy' method in algorithm class. The following is an example:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy

//OutputIterator copy ( InputIterator first, InputIterator last, OutputIterator result );

#include<iostream>
#include <algorithm>
#include <vector>

using namespace
std;

int
main()
{

int
someInts[] = {10, 20, 20, 40, 50};
int
someMoreInts[] = {100, 200, 300, 400, 500, 600, 700};

vector<int> someVector;
vector<int>::iterator someIterator;

//Get the total size of all elements
int totalSize = (sizeof(someInts) + sizeof(someMoreInts)) / sizeof(int);

//Resize someVector to right size
someVector.resize(someVector.size() + totalSize);

//Get the number of elements of someInts
int tempSize = sizeof(someInts) / sizeof(int);

vector<int>::iterator finalElementIt = copy(someInts, someInts + tempSize, someVector.begin());

cout<<"\n1. someVector contains :";
for
(someIterator = someVector.begin(); someIterator != someVector.end(); ++someIterator)
cout<<" "<<*someIterator;
cout<<endl;

//Get size of someMoreInts
tempSize = sizeof(someMoreInts) / sizeof(int);

copy(someMoreInts, someMoreInts + tempSize, finalElementIt);

cout<<"\n2. someVector contains :";
for
(someIterator = someVector.begin(); someIterator != someVector.end(); ++someIterator)
cout<<" "<<*someIterator;
cout<<endl;

return
0;
}


The output is as follows:

Wednesday 20 April 2011

An Challenging Interview question with a difference

The following program is provided:


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>

using namespace
std;

//This class can be designed as you wish
class SR
{

public
:
SR(int i) {}
};


int
main()
{

int
sum = 0;
for
(int i = 1; i < 100; i++)
{

SR ii(i);
while
(i--)
sum += i;
}

cout<<"Expected value of sum = 161700" << endl;
cout<<"Returned value of sum = " << sum << endl;

return
0;
}


As already mentioned above, the expected output of 161700 is provided. The class 'SR' could be written as one wishes. How to do write the class 'SR' to get the desired output?
.
.
.
.
Give it a try before looking at the solution.
.
.
.
.
.
The modified program with the correct 'SR' class as follows:


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>

using namespace
std;

//This class can be designed as you wish
class SR
{

public
:
SR(int& i):ref(i)
{

var = i;
}
~
SR()
{

ref = var;
}

private
:
int
var;
int
&ref;
};


int
main()
{

int
sum = 0;
for
(int i = 1; i < 100; i++)
{

SR ii(i);
while
(i--)
sum += i;
}

cout<<"Expected value of sum = 161700" << endl;
cout<<"Returned value of sum = " << sum << endl;

return
0;
}



Source: Modified from here. Another similar question is available here.

Tuesday 12 April 2011

isNumeric()

For some reason many C++ programmers believe there is an isNumeric() function available as part of the language. In fact I was searching for the header file to include to get a piece of code to work.

Its not difficult to create a function that will be able to check if the string is numeric or not. Here is the code.



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include <iostream>
#include <string>
#include <sstream>

using namespace
std;

bool
isNumeric1(string stringToCheck)
{

bool
numeric = false;

if
(stringToCheck.find_first_not_of("0123456789.") == string::npos)
numeric = true;

return
numeric;
}


bool
isNumeric2(string stringToCheck)
{

bool
numeric = true;
unsigned
i = 0;

while
(numeric && i < stringToCheck.length())
{

switch
(stringToCheck[i])
{

case
'0': case '1': case '2': case '3': case '4': case '5':
case
'6': case '7': case '8': case '9': case '.':
//do nothing
break;
default
:
numeric = false;
}

i++;
}


return
numeric;
}


bool
isNumeric3(string stringToCheck)
{

stringstream streamVal(stringToCheck);
double
tempVal;

streamVal >> tempVal; //If numeric then everything transferred to tempVal

if
(streamVal.get() != EOF)
return
false;
else
return
true;
}


int
main()
{

string str1("123"), str2("134.567"), str3("12AB");
cout << "Approach 1" << endl;
cout << str1 << (isNumeric1(str1) ? " is Numeric" : " is Not Numeric") << endl;
cout << str2 << (isNumeric1(str2) ? " is Numeric" : " is Not Numeric") << endl;
cout << str3 << (isNumeric1(str3) ? " is Numeric" : " is Not Numeric") << endl;

cout << "\nApproach 2" << endl;
cout << str1 << (isNumeric2(str1) ? " is Numeric" : " is Not Numeric") << endl;
cout << str2 << (isNumeric2(str2) ? " is Numeric" : " is Not Numeric") << endl;
cout << str3 << (isNumeric2(str3) ? " is Numeric" : " is Not Numeric") << endl;

cout << "\nApproach 3" << endl;
cout << str1 << (isNumeric3(str1) ? " is Numeric" : " is Not Numeric") << endl;
cout << str2 << (isNumeric3(str2) ? " is Numeric" : " is Not Numeric") << endl;
cout << str3 << (isNumeric3(str3) ? " is Numeric" : " is Not Numeric") << endl;

return
0;
}




Output is as follows:


There are few problems in the program above:

1. It does not cater for negative numbers
2. It will return wrong result when you have incorrect string like 12.34.56.78

I have intentionally left it as an exercise.

Other approaches are possible as well. Why not try and think of an approach yourself.

Tuesday 5 April 2011

string::find_next()

I met this new starter who has come from Java background. He was upset because he couldn't find string::find_next() as C++ function. He said Java is much more flexible this way. In reality, its not that bad if you look at the definition of find carefully.

size_t find ( const string& str, size_t pos = 0 ) const;
size_t find ( const char* s, size_t pos, size_t n ) const;
size_t find ( const char* s, size_t pos = 0 ) const;
size_t find ( char c, size_t pos = 0 ) const;

The first one works as find_next as I show in the example below:

//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy

#include <iostream>
#include <string>

using namespace
std;

int
main()
{

string someString("Tom is not in. Infact Tom is not going to be in Tomorrow or day after Tomorrow");
string findTheString("Tom");

unsigned
position = 0;

position = someString.find(findTheString);
cout<<"First position of " << findTheString << " is " << position << endl;

//We want to find all the next positions which is after position + findTheString.length()
while(position != string::npos)
{

position = someString.find(findTheString, (position + findTheString.length()));
cout<<"Next position of " << findTheString << " is " << position << endl;
}


return
0;
}



The output is as follows:

Exercise for new programmers:
  1. The last two Tom's are part of 'Tomorrow', how can you make sure they are not printed
  2. The last Tom which is 4294... is equal to -1 or string::npos. How can you stop that being printed without making another check for string::npos
Please dont post answers as they should be trivial exercise and you should be able to figure out without much problems.