Friday, 4 March 2011

Removing all white-spaces from a string

Continuing on the same theme as the last post. What if all the spaces need to be stripped out from the input string:



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

using namespace
std;

string removeAllSpaces(const string& s)
{

string newStr(s);
bool
spacesLeft = true;

while
(spacesLeft)
{

int
pos = newStr.find(" ");
if
(pos != string::npos)
{

newStr.erase(pos, 1);
}

else

spacesLeft = false;
}


return
newStr;
}


int
main()
{

string aString("This string has multiple spaces problem!");

cout<<"Original : "<<aString<<endl;
cout<<"Modified : "<<removeAllSpaces(aString)<<endl;

return
0;
}





The output is as follows:

Tuesday, 1 March 2011

Removing Multiple White-spaces from a string

A simple program to remove an arbitrary number of white spaces in between words. Program as follows:




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

using namespace
std;

bool
removeDoubleSpaces(string& s)
{

bool
found = true;

int
i = s.find(" "); //Search for 2 spaces
if(i != string::npos)
{

s.replace(i, 2, " ");
}

else

found = false;

return
found;
}


string removeMultipleSpaces(const string& s)
{

string newStr(s);
bool
found = true;

while
(found)
{

found = removeDoubleSpaces(newStr);
}


return
newStr;
}


int
main()
{

string aString("This string has multiple spaces problem!");

cout<<"Original : "<<aString<<endl;
cout<<"Modified : "<<removeMultipleSpaces(aString)<<endl;

return
0;
}




The output is as follows:

Tuesday, 22 February 2011

A generic sort program with 'functors' and 'templates'

Picked up this question from here and made a program out of it. It may be a good idea to quickly brush functors and templates if required.

The program sorts the input Vector provided regardless of the type.




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

using namespace
std;

class
Int
{

public
:
Int() {x_ = 0;}
Int(const int &x) {x_ = x;}
int
getID (void) {return x_;}
int
x_;
};


class
Str
{

public
:
Str() {x_ = "";}
Str(const string &x) {x_ = x;}
string getID (void) {return x_;}
string x_;
};


template
<typename Object> class Comparator {
public
:
bool
operator()(const Object &o1, const Object &o2) const
{

return
(const_cast<Object&>(o1).getID() < const_cast<Object&>(o2).getID());
}


bool
operator()(const Object *o1, const Object *o2) const {
return
(o1->getID() < o2->getID());
}
};


template
<typename VecObject> void Display(VecObject v)
{

VecObject::iterator it;
for
(it = v.begin(); it != v.end(); ++it)
{

cout<<it->getID()<<", ";
}

cout<<endl;
}


int
main()
{

vector<Int> objects1;
objects1.push_back(Int(3));
objects1.push_back(Int());
objects1.push_back(Int(77));

//print the output
cout<<"objects1 before sort = ";
Display(objects1);
std::sort(objects1.begin(), objects1.end(), Comparator<Int> ());
cout<<"objects1 after sort = ";
Display(objects1);

std::vector<Str> objects2;
objects2.push_back(Str("Hello Hello"));
objects2.push_back(Str("apple?"));
objects2.push_back(Str());
objects2.push_back(Str("1 Jump"));

//print the output
cout<<"objects2 before sort = ";
Display(objects2);
std::sort(objects2.begin(), objects2.end(), Comparator<Str> ());
cout<<"objects2 after sort = ";
Display(objects2);

return
0;
}




The output is as follows:

Tuesday, 15 February 2011

Debugging Mutex and Locks

When there are multiple Mutex's in the program, it may be required to find if a particular thread is locked far longer than necessary. This can cause problems and the output may not be what is expected.

To get round this, I took an old example from here and modified it to help me print some debugging info.

I modified the printSomething() in Singleton.h to add a sleep as follows:



  void printSomething(char *name, int count)
{

Lock guard(mutex_);
Sleep(10);
Lock guard2(mutex_);
std::cout << name << " loop " << count << std::endl;
}




and I modified the Mutex.h as follows:



//Example from http://www.relisoft.com/Win32/active.html
#if !defined _MUTEX_H_
#define _MUTEX_H_

class
Mutex
{

friend class
Lock;
public
:
Mutex () { InitializeCriticalSection (& _critSection); }
~
Mutex () { DeleteCriticalSection (& _critSection); }
private
:
void
Acquire ()
{

DWORD start = GetTickCount();
EnterCriticalSection (& _critSection);
DWORD elapsed = GetTickCount() - start;
if
(elapsed > 15)
{

//Debugging Info
std::cout<<"Debugging Info: Waited at mutex for "<<elapsed<<std::endl;
}
}

void
Release ()
{

LeaveCriticalSection (& _critSection);
}


CRITICAL_SECTION _critSection;
};


#endif



The output is as follows:
The small problem with the above approach is that if a Thread is deadlocked, we may not get the debug output as we would have to kill the process.

Wednesday, 9 February 2011

Add two unsigned integers without using '+'

I found this very interesting discussion (and the program) to add two numbers without the use of the arithmetic operator '+'. The obvious guess would be to use the Bitwise operators.

The logic behind the addition operation using the bitwise operators is as follows:


integer1 =  3  = 0011b
integer2 = 5 = 0101b

first operation second operation third operation
0011 0011
shift by one
0101 0101

______ ______
XOR 0110 AND 0001 ------> <<1 0010

Again...
first operation second operation third operation
previous XOR 0110 0110 shift by one
previous <<1 0010 0010
______ ______
XOR 0100 AND 0010 ------> <<1 0100

Again...
first operation second operation third operation
previous XOR 0100 0100 shift by one
previous <<1 0100 0100
______ ______
XOR 0000 AND 0100 ------> <<1 1000

Again...
first operation second operation
previous XOR 0000 0000
previous <<1 1000 1000
______ ______
XOR 1000 AND 0000
When AND iguals 0 the result of XOR is iqual to the sum of the two integers

The program is as follows:



//Program to add two numbers by using boolean operators
//Ref: http://www.daniweb.com/forums/thread84950.html
//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>

using namespace
std;

unsigned long
add(unsigned integer1, unsigned integer2)
{

unsigned long
xor, and, temp;

and
= integer1 & integer2; /* Obtain the carry bits */
xor
= integer1 ^ integer2; /* resulting bits */

while
(and != 0 ) /* stop when carry bits are gone */
{

and
<<= 1; /* shifting the carry bits one space */
temp = xor ^ and; /* hold the new xor result bits*/
and
&= xor; /* clear the previous carry bits and assign the new carry bits */
xor
= temp; /* resulting bits */
}

return
xor; /* final result */
}


int
main()
{

int
num1 = 13, num2 = 27;

cout << num1 << " + " << num2 << " = " <<add(num1, num2) << endl;

return
0;
}



The output is:
13 + 27 = 40

See the original discussion here.

Wednesday, 2 February 2011

Consequences of Ignoring Compiler Warnings

Though this is a fictional program that I have picked up from here, I have seen similar problems in real life.

Lets say my program (below) was expected to return this


but instead returned:

Program as follows:


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

using namespace
std;

class
Bclass
{

public
:
Bclass() {}
virtual
void func()
{

cout<<"In Bclass::func()"<<endl;
}
};


class
Dclass : public Bclass
{

public
:
Dclass() {}
virtual
void func()
{

cout<<"In Dclass::func()"<<endl;
Bclass:func();
}
};


int
main()
{

Dclass d;
d.func();
//...
return 0;
}



The clue of the problem was given by the compiler that generated the following warning:

main.cpp(23) : warning C4102: 'Bclass' : unreferenced label

pointing to the line

Bclass:func();

The problem lies in the fact that due to a single : rather than :: the line above is being treated as label and since its an unreferenced label it goes back to the start of the same function.

You can read the complete discussion here. Make sure to check the warnings the next time your program behaves unexpectedly.

Wednesday, 26 January 2011

Swap two variables without using third and in one line

Couple of weeks back I was interviewing a fresh graduate. Even though they are taught programming, I am not sure if they take it seriously and learn or practice it well. One of the questions I asked was to swap 2 numbers without using a temp variable.

Looking back now, I think it may be a bigger challenge to ask to swap numbers without using a temp variable and in one line. Below are my three different approaches but I would advise you to try it yourself before looking at the answer.


//Program to swap 2 numbers without using 3rd variable and in one line
//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>

using namespace
std;

void
approach1(int& a, int& b)
{

cout<<"\nApproach 1"<<endl;
a^=b^=a^=b;
}


void
approach2(int& a, int& b)
{

cout<<"\nApproach 2"<<endl;
//b=(a+b)-(a=b); - This should work but doesnt, why?
a =((a = a + b) - (b = a - b));
}


void
approach3(int& a, int& b)
{

cout<<"\nApproach 3"<<endl;
a = ((a = a * b) / (b = a / b));
}




int
main()
{

int
a = 13, b = 29;
cout<<"\nOriginal"<<endl;
cout<<"a = "<<a<<", b = "<<b<<endl;

approach1(a, b);
cout<<"a = "<<a<<", b = "<<b<<endl;

a = 13, b = 29;
approach2(a, b);
cout<<"a = "<<a<<", b = "<<b<<endl;

a = 13, b = 29;
approach3(a, b);
cout<<"a = "<<a<<", b = "<<b<<endl;

return
0;
}


The output is as follows:
Agreed that the above would be applicable only for integers.

Wednesday, 19 January 2011

'sizeof' a class

Continuation from last week. What is the sizeof of a class? Wrote a simple program as follows:


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

using namespace
std;

class
A
{

int
a;
};


class
B
{

int
b;
int
someFunc(void) {return b;}
};


class
C
{

void
someFunc1(void) {};
void
someFunc2(void) {};
};


class
D : public A
{

void
someFunc(void) {};
};



int
main()
{

cout<<"Size of class A = "<<sizeof(A)<<endl;
cout<<"Size of class B = "<<sizeof(B)<<endl;
cout<<"Size of class C = "<<sizeof(C)<<endl;
cout<<"Size of class D = "<<sizeof(D)<<endl;
}



The output is as follows:

After finishing this, I found this interesting article here.

Wednesday, 12 January 2011

Checking the 'sizeof' doubts

I noticed sometime back that one of my programs behaved unexpectedly in certain scenarios which was traced to an incorrect use of sizeof. As a result, I made a small program to make sure that my understanding of sizeof is correct. Here is the program:



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

using namespace
std;

int
main()
{

char
a[]="";
cout<<"Size of a[] = "<<sizeof(a)<<endl;

char
b[]=" ";
cout<<"Size of b[ ] = "<<sizeof(b)<<endl;

char
c[10];
cout<<"Size of c[10] = "<<sizeof(c)<<endl;

char
* d;
cout<<"Size of d = "<<sizeof(d)<<endl;

char
* e = c;
cout<<"Size of e = "<<sizeof(e)<<endl;

char
f[] = "123456";
cout<<"Size of f = "<<sizeof(f)<<endl;

char
g[] = {'1','2','3','4','5','6'};
cout<<"Size of g = "<<sizeof(g)<<endl;

return
0;
}



The output is as follows:
A lot of interviewers love the sizeof questions.

Have you come across any interesting sizeof problems? Please feel free to add them in comments.

Wednesday, 5 January 2011

C++ example of Linked List implementation

It is debatable if Linked lists are needed in C++, especially because STL can do a very good job for the same functionality for which Linked Lists are required. Nevertheless sometimes it maybe convenient to know linked lists.



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

using namespace
std;

class
Node
{

public
:
Node() : next(NULL) {}; //default constructor
Node(const string& s1) : info(s1), next(NULL) {};
string info;
Node* next;
};


Node* getNewNode()
{

//Lets flush the input buffer first
istream& in(cin);
in.ignore( numeric_limits<std::streamsize>::max(), '\n' );

//Read the String from console
cout<<"\tEnter a string: ";
istreambuf_iterator<char> eos; // end-of-range iterator
istreambuf_iterator<char> iit (cin.rdbuf()); // stdin iterator
string s2;
while
(iit!=eos && *iit!='\n') s2+=*iit++;

//Call the constructor with the input string
Node* newNode = new Node(s2);

return
newNode;
}


int
main()
{

Node* head = NULL;
bool
contFlag = true;
char
c;

while
(contFlag)
{

cout<<"\n\n";
cout<<"0. Quit"<<endl;
cout<<"1. Traverse and Print"<<endl;
cout<<"2. Insert node at the start"<<endl;
cout<<"3. Insert node at the end"<<endl;
cout<<"4. Insert after specified number of nodes"<<endl;
cout<<"5. Remove node from the start"<<endl;
cout<<"6. Remove node from the end"<<endl;
cout<<"7. Remove node from a specified number"<<endl;

cout<<"\nEnter your choice: ";
cin>>c;

switch
(c)
{

case
'0':
contFlag = false;
break
;
case
'1':
{

Node* tempNode = head;
int
count = 0;
while
(tempNode)
{

cout<<"\tItem "<<count<<" = "<<tempNode->info<<endl;
tempNode = tempNode->next;
count++;
}
}

break
;
case
'2':
{

Node* newNode = getNewNode();
newNode->next = head;
head = newNode;
}

break
;
case
'3':
{

Node* newNode = getNewNode();

Node* endNode = head;
if
(endNode)
{

while
(endNode->next)
endNode = endNode->next;
endNode->next = newNode;
}

else
//In case its the first element
{
head = newNode;
}
}

break
;
case
'4':
{

Node* tempNode = head;
if
(tempNode)
{

unsigned
num;
cout<<"\tInsert after how many nodes? : ";
cin>>num;
Node* newNode = getNewNode();

unsigned
count = 1;
//If less elements are present then insert at the end
while(tempNode->next && (count < num))
{

tempNode = tempNode->next;
count++;
}

newNode->next = tempNode->next;
tempNode->next = newNode;
}

else

{

cout<<"\tNo nodes present yet"<<endl;
}
}

break
;
case
'5':
{

Node* firstNode = head;
if
(firstNode)
{

head = firstNode->next;
delete
firstNode;
}
}

break
;
case
'6':
{

Node* endNode = head;
if
(endNode) //Atleast one element
{
Node* endEndNode = endNode->next;
if
(endEndNode) //Atleast 2 elements
{
while
(endEndNode->next)
{

endNode = endEndNode;
endEndNode = endEndNode->next;
}

endNode->next = NULL;
delete
endEndNode;
}

else
//Only one element
{
head = NULL;
delete
endNode;
}
}
}

break
;
case
'7':
{

Node* tempNode = head;
if
(tempNode)
{

unsigned
num;
cout<<"\tRemove after how many nodes? : ";
cin>>num;

unsigned
count = 1;
//If less elements are present then return
while(tempNode->next && (count < num))
{

tempNode = tempNode->next;
count++;
}

if
(count == num && tempNode->next && tempNode->next->next)
{

Node* nodeToRemove = tempNode->next;
tempNode->next = nodeToRemove->next;
delete
nodeToRemove;
}
}

else

{

cout<<"\tNo nodes present yet"<<endl;
}
}

break
;
default
:
cout<<"Incorrect selection."<<endl;
}
}


return
0;
}



The output is as follows:
You can try more combinations and if you have ideas for improvements please add in the comments section.

Few things to note:
1. This program is for reference and I have not accounted for memory leaks after pressing '0'.
2. For simplicity, getNewNode() is shown as a seperate function. In a real program, it may be better as a method of class Node
3. General Linked Lists use Struct's but in C++, Structs and Classes are nearly the same so its better to use Class.
4. In C++ there is rarely a need to use Linked Lists. Its better to use the STL which already have vectors, stacks, lists, etc.
5. There should be check for memory allocation and try catch blocks that have been ignored for simplicity