Saturday, July 24, 2010

Selection Sort Implementation in C

Selection Sort algorithm works in three steps:

1. Find the minimum value in the list.
2. Swap it with the value in the first position.
3. Repeat the steps above for the remainder of the list (starting at the second position and
advancing each time)

Here's a simple implementation of Selection Sort in C

#include<stdio.h>

void display(int *arr , int start, int end);

void swap(int *a , int *b) 
{
    *a = *a - *b; 
    *b = *b + *a; 
    *a = *b - *a; 
}

int findmin(int arr[], int start, int end)
{
    int min = arr[start];
    int ret = start;
    for(; start < end ; start++)
    {   
        if(arr[start] < min)
        {   
            min = arr[start];
            ret = start;
        }   
    }   

    return ret;         // Returns the index of the minimum value in the range
}

void selection_sort(int *arr, int nmem)
{
    int start = 0;
    int end = nmem;
    int minIndex;

    for(; start < end; start++)
    {
        minIndex = findmin(arr,start,end);     //Find minimum value in the array

        if(arr[start] != arr[minIndex])        //If the minimum value lies at start
            swap(&arr[start],&arr[minIndex]);

    }

}

void display(int arr[] , int start , int end)
{
    int i;
    for(i = start; i < end ; i++)
        printf("%d ",arr[i]);
    printf("\n");
}

int main()
{
    int arr[] = {12,2,54,23,57,21,78,34};

    int nmem = sizeof(arr)/sizeof(int);

    display(arr,0,nmem);
    selection_sort(arr,nmem);
    display(arr,0,nmem);
}

Friday, July 23, 2010

QuickSort implementation in C

A simple implementation for QuickSort using arrays.
This version of QuickSort involves the partitioning mechanism. In each pass we partition the array into two parts and the center point is the 'Pivot'. One part contains elements greater than 'Pivot' and other contains less than 'Pivot'.

We continue this process until the array becomes sorted.


#include <stdio.h>
#include <stdlib.h>

void display(int*,int);

void swap(int *a, int *b)
{
  *a = *a - *b;
  *b = *b + *a;
  *a = *b - *a;
}

int partition(int *arr, int start, int end)  //Partition the array
{
  int pivot = start;
  int left = start , right = end;
  int i , pivotVal = arr[pivot];
  
  while(left < right)
  {
    while(arr[left] <= pivotVal && left <=end )
      left++;
    while(arr[right] > pivotVal && right >= 0)
      right--;
    if(left < right)
      swap(&arr[left], &arr[right]);
  }

  arr[start] = arr[right];
  arr[right] = pivotVal;

  return right;
}

void quick(int *arr, int start, int end)
{
  int m;
    if(start < end)
    {
      m = partition(arr,start,end); //Pivot
      quick(arr,start,m-1);
      quick(arr,m+1,end);
    }
}



void display(int *arr,int nmem)
{
  int i;
  for(i = 0; i < nmem;i++)
    printf("%d ",arr[i]);
  printf("\n");
}

int main()
{
  int arr[]={12,32,2,56,34,23,67,122};
  int nmem = sizeof(arr)/sizeof(int);
  
  quick(arr, 0, nmem - 1);
  display(arr,nmem);  //Sorted array
}


Thursday, July 22, 2010

Stack Implementation in C++

A Stack is a data structure which works on the principle LIFO(Last In, First Out).The basic operations in a Stack are :

1. Push : In which we push the data into the stack.
2. Pop : In which we remove an element from the Stack.

All insertions and removals are done only from one side of the Stack , which is called the 'top' of the Stack.

A stack is generally used in function calls where the local variables are pushed onto the Stack and when the function returns , it pops the variables from the Stack.

This is a simple implementation of Stack in C++.

#include <iostream>

using namespace std;

class Stack
{
private:
    int *p;
    int top,length;

public:
    Stack(int = 0);
    ~Stack();

    void push(int);
    int pop();
    void display();
};

Stack::Stack(int size)
{
    top=-1;
    length=size;
    if(size == 0)
        p = 0;
    else
        p=new int[length];
}

Stack::~Stack()
{
    if(p!=0)
        delete [] p;
}

void Stack::push(int elem)
{
    if(p == 0)                //If the stack size is zero, allow user to mention it at runtime
    {
        cout<<"Stack of zero size"<<endl;
        cout<<"Enter a size for stack : ";
        cin >> length;
        p=new int[length];
    }
    if(top==(length-1))     //If the top reaches to the maximum stack size
    {
        cout<<"\nCannot push "<<elem<<", Stack full"<<endl;
        return;
    }
    else
    {
        top++;
        p[top]=elem;
    }
}
int Stack::pop()
{
    if(p==0 || top==-1)
    {
        cout<<"Stack empty!";
        return -1;
    }
    int ret=p[top];
    top--;
    return ret;
}

void Stack::display()
{
    for(int i = 0; i <= top; i++)
        cout<<p[i]<<" ";
    cout<<endl;
}

int main()
{
    Stack s1;             //We are creating a stack of size 'zero'
    s1.push(1);
    s1.display();
    s1.push(2);
    s1.push(3);
    s1.push(4);
    s1.push(5);
    s1.display();
    s1.pop();
    s1.display();
    s1.pop();
    s1.display();
    s1.pop();
    s1.display();
    s1.pop();
    s1.display();
}

Wednesday, July 21, 2010

TCP Server Client

This TCP server client provides the time requested by Client from Server.
It can be modified to send and receive messages too.

Here's a picture how the connections are set up.



TCP Server Client Connection SetUp

//simpleserver.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#include <time.h>

/* the port users will be connecting to */
#define MYPORT 3490
/* how many pending connections queue will hold */
#define BACKLOG 10

void sigchld_handler(int s)
{
    while(wait(NULL) > 0);
}

int main(int argc, char *argv[ ])
{
    /* listen on sock_fd, new connection on new_fd */
    int sockfd, new_fd;
    time_t ticks;
    char buf[300];
    /* my address information */
    struct sockaddr_in my_addr;
    /* connector.s address information */
    struct sockaddr_in their_addr;
    int sin_size;
    struct sigaction sa;
    int yes = 1;

    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
    {
        perror("Server-socket() error lol!");
        exit(1);
    }
    else
        printf("Server-socket() sockfd is OK...\n");

    if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1)
    {
        perror("Server-setsockopt() error lol!");
        exit(1);
    }
    else
        printf("Server-setsockopt is OK...\n");

    /* host byte order */
    my_addr.sin_family = AF_INET;
    /* short, network byte order */
    my_addr.sin_port = htons(MYPORT);
    /* automatically fill with my IP */
    my_addr.sin_addr.s_addr = INADDR_ANY;

    printf("Server-Using %s and port %d...\n", inet_ntoa(my_addr.sin_addr), MYPORT);

    /* zero the rest of the struct */
    memset(&(my_addr.sin_zero), '\0', 8);

    if(bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1)
    {
        perror("Server-bind() error");
        exit(1);
    }
    else
        printf("Server-bind() is OK...\n");

    if(listen(sockfd, BACKLOG) == -1)
    {
        perror("Server-listen() error");
        exit(1);
    }
    printf("Server-listen() is OK...Listening...\n");

    /* clean all the dead processes */
    sa.sa_handler = sigchld_handler;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART;

    if(sigaction(SIGCHLD, &sa, NULL) == -1)
    {
        perror("Server-sigaction() error");
        exit(1);
    }
    else
        printf("Server-sigaction() is OK...\n");

    /* accept() loop */
    while(1)
    {
        sin_size = sizeof(struct sockaddr_in);
        if((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size)) == -1)
        {
            perror("Server-accept() error");
            continue;
        }
        else
            printf("Server-accept() is OK...\n");
        printf("Server-new socket, new_fd is OK...\n");
        printf("Server: Got connection from %s\n", inet_ntoa(their_addr.sin_addr));

        /* this is the child process */
        if(!fork())
        {
            /* child doesn.t need the listener */
            close(sockfd);
            ticks = time(NULL);
            snprintf(buf, sizeof(buf), "%.24s\r\n", ctime(&ticks));
             
            if(send(new_fd,buf, sizeof(buf), 0) == -1)
                perror("Server-send() error lol!");
            close(new_fd);
            exit(0);
        }
        else
            printf("Server-send is OK...!\n");

        /* parent doesn.t need this*/
        close(new_fd);
        printf("Server-new socket, new_fd closed successfully...\n");
    }
    return 0;
}



// simpleclient.c

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>

// the port client will be connecting to
#define PORT 3490
// max number of bytes we can get at once
#define MAXDATASIZE 300

int main(int argc, char *argv[])
{
    int sockfd, numbytes;
    char buf[MAXDATASIZE];
    struct hostent *he;
// connector.s address information
    struct sockaddr_in their_addr;

// if no command line argument supplied
    if(argc != 2)
    {
        fprintf(stderr, "Client-Usage: %s the_client_hostname\n", argv[0]);
// just exit
        exit(1);
    }

// get the host info
    if((he=gethostbyname(argv[1])) == NULL)
    {
        perror("gethostbyname()");
        exit(1);
    }
    else
        printf("Client-The remote host is: %s\n", argv[1]);

    if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
    {
        perror("socket()");
        exit(1);
    }
    else
        printf("Client-The socket() sockfd is OK...\n");

// host byte order
    their_addr.sin_family = AF_INET;
// short, network byte order
    printf("Server-Using %s and port %d...\n", argv[1], PORT);
    their_addr.sin_port = htons(PORT);
    their_addr.sin_addr = *((struct in_addr *)he->h_addr);
// zero the rest of the struct
    memset(&(their_addr.sin_zero), '\0', 8);

    if(connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1)
    {
        perror("connect()");
        exit(1);
    }
    else
        printf("Client-The connect() is OK...\n");

    if((numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1)
    {
        perror("recv()");
        exit(1);
    }
    else
        printf("Client-The recv() is OK...\n");

    buf[numbytes] = '\0';
    printf("Client-Received: %s", buf);

    printf("Client-Closing sockfd\n");
    close(sockfd);
    return 0;
}

Portscanner for Linux/Unix in C

A simple portscanner in C.
Works for Linux only .
It detects the open ports for a host.

After compiling using : gcc portscanner.c
Usage : ./a.out <host-IP>

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>

int main(int argc, char *argv[])
{
    int sockfd, port;
    struct hostent *he;


    if (argc != 2)
    {
        fprintf(stderr,"usage: client hostname\n");
        exit(1);
    }

    if ((he=gethostbyname(argv[1])) == NULL)    // get the host info
    {
        perror("gethostbyname");
        exit(1);
    }
    for(port=0; port<=65000; port++)
    {
        struct sockaddr_in their_addr; // connector's address information
        if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
        {
            perror("socket");
            exit(1);
        }

        their_addr.sin_family = AF_INET;    // host byte order
        their_addr.sin_port = htons(port);  // short, network byte order
        their_addr.sin_addr = *((struct in_addr *)he->h_addr);
        memset(&(their_addr.sin_zero), '\0', 8);  // zero the rest of the struct

        if (connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1)
        {
            close(sockfd);
        }
        else
        {
            printf("%i open\n", port);
            close(sockfd);
        }
    }
}

Remove duplicate characters from a string

Here's a simple program to remove duplicate characters from an input string.

Function search(char* , char) finds the duplicates and return 1 if finds a duplicate and 0 otherwise.

Function removeDup(char*) actually removes the duplicates.

#include <stdio.h>
#include <malloc.h>
#include <string.h>

int search( char * arr, char item );

char* removeDup(char * input)
{
    char *res = (char*)malloc(strlen(input)+1);
    int i = 0,j=0  ;
   
    while(input[i] != '\0')
    {
        if (search(res,input[i]) == 0)
            res[j++] = input[i];
        i++;
    }
    
    return res;
}

int search( char * arr, char item )
{
    int i;
    for(i = 0 ; i < strlen(arr) ; i++)
        if(item == arr[i])
            return 1;
    return 0;
}

int main()
{
  char input[200];

  printf("\nEnter a string : ");
  scanf("%s",input);

  printf("\nOutput : %s\n" , removeDup(input));
}

Tuesday, July 20, 2010

Observer Class

Here's a simple example on Observer Design Pattern in C++

Here Target class's derived classes AddObserver and SubObserver are the classes which performs updates to the variable 'value' in the Target class. These updates get notified to the Observer class by means of the 'notify' function in the Target class.


//observer.hpp
#include <iostream>
#include <vector>
using namespace std;

class Target
{
    vector<class Observer*> views;
    int value;
public:
    void attach( Observer* obs );
    void setVal( int val );
    int  getVal();
    void notify();
};

class Observer
{
    Target* model;
    int modifier;
public:
    Observer( Target* targ, int val );
    virtual void update() = 0;
protected:
    Target* getTarget();
    int getModifier();
};

class AddObserver : public Observer
{
public:
    AddObserver( Target* targ, int val ) : Observer(targ,val) { }
    void update();
};

class SubObserver : public Observer
{
public:
    SubObserver( Target* targ, int val ) : Observer(targ,val) { }
    void update();
};


//observer.cpp

#include <iostream>
#include <vector>
#include "observer.hpp"
using namespace std;

void Target ::attach( Observer* obs )
{
    views.push_back( obs );
}

void Target ::setVal( int val )
{
    value = val;
    notify();
}

int  Target ::getVal()
{
    return value;
}

void Target::notify()
{
    for (int i=0; i < views.size(); i++) 
      views[i]->update();
}

Observer :: Observer( Target* targ, int modf )
{
    model = targ;
    modifier = modf;
    model->attach( this );
}

Target* Observer :: getTarget()
{
    return model;
}

int Observer :: getModifier()
{
    return modifier;
}

void AddObserver :: update()
{
    int v = getTarget()->getVal(), m = getModifier();
    cout << v << " add " << m << " is " << v + m << '\n';
}

void SubObserver :: update()
{
    int v = getTarget()->getVal(), m = getModifier();
    cout << v << " sub " << m << " is " << v - m << '\n';
}

int main()
{
    Target targ;
    AddObserver  add1( &targ,4 );
    AddObserver  add2( &targ,3 );
    SubObserver  modObs3( &targ,3 );
    targ.setVal( 14 );
    targ.setVal( 90 );

    return 0;
}


Sunday, July 18, 2010

Reverse a byte's two equal halves

This program reverses a byte's two halves separately

e.g. if the input is 1100 1010

Then the output will be 0011 0101

The last line in the function reverse_half() is explained like this :

*ch = (rev(temp1) << 4) | ((rev(temp2) >> 4) & mask2);

1. *ch returns the resultant reversed bits

2. (rev(temp1) << 4)

Here we first take the reverse of temp1 i.e first four bits of the byte

So suppose if the input byte is 1100 0010 then temp1 would be 1100 0000 and rev(temp1) would be 0000 0011 now since these are first four bits we need to put them back as first four bits .
So we left shift by 4 bits rev(temp1) << 4 , which gives us 0011 0000

Similarly for the latter half of the byte (rev(temp2) >> 4) & mask2 gives 0000 0100

Now we bitwise OR these results i.e. 0011 0000 | 0000 0100 = 0011 0100



#include <stdio.h>
#include <limits.h>

void showbits(unsigned char byte)       // To display bits in a character
{
    unsigned char bit;
    for ( bit = 1 << (CHAR_BIT - 1); bit; bit >>= 1 )
    {
        putchar(byte & bit ? '1' : '0');
    }
    putchar('\n');
}

char rev(char ch)               //This function reverses a character's bit pattern
{
  char rev_char = ch;
  int siz = sizeof(char)*CHAR_BIT -1;
  
  ch = ch >> 1;

  while(ch)
  {
    rev_char = rev_char << 1;
    rev_char = rev_char | (ch & 1);
    ch = ch >> 1 ;
    siz--; 
  }

  rev_char = rev_char << siz;
  
  return rev_char;
}

char reverse_half(char *ch)
{
    char temp1,temp2;
    unsigned char mask1 = 0xf0;  // 11110000
    unsigned char mask2 = 0x0f;  // 00001111

    temp1 = *ch & mask1;        //To get the first four bits
    temp2 = *ch & mask2;        //To get the last four bits

    *ch = (rev(temp1) << 4) | ((rev(temp2) >> 4) & mask2);

}
int main()
{
    char ch;

    printf("\nEnter a byte to reverse it to reverse its two halves: ");
    ch = getchar();   
    getchar();        //To ignore '\n'
    printf("\nYou entered : ");
    showbits(ch);
    reverse_half(&ch);
    printf("\nOutput : ");
    showbits(ch);
}

Friday, July 16, 2010

Doubly Linked List in C++

Here's a simple implementation of doubly linked list using C++

//dll.hpp
class dnode
{
public:
    dnode();
    dnode *prev;
    int data;
    dnode *next;
    ~dnode();
};

class DLL
{
private:
    dnode *front;
    dnode *rear;
    dnode *newnode;
public:
    DLL();
    dnode* create_node(int data);
    void insertAtFront(int data);
    void insertAtRear(int data);
    void insertBefore(int data, dnode *node);
    void insertAfter(int data, dnode *node);
    void deleteFront();
    void deleteLast();
    void del(int data);
    dnode* search(int data);
    void display();
    ~DLL();
};



//dll.cpp
#include <iostream>
#include "dll.hpp"

using namespace std;

dnode::dnode()
{
    cout<<"dnode()"<<endl;
}

dnode::~dnode()
{
    cout<<"~dnode()"<<endl;
}

DLL::DLL()
{
    front = NULL;
    rear = NULL;
    cout<<"DLL()"<<endl;
}

dnode* DLL :: create_node(int data)
{
    newnode = new dnode;
    newnode->data = data;
    newnode->prev = NULL;
    newnode->next = NULL;
    return newnode;
}

void DLL::insertAtFront(int data)
{
    dnode* newnode = create_node(data);

    if(front == NULL)
    {
        front = newnode;
        rear = newnode;
    }
    else
    {
        newnode -> next = front;
        front -> prev = newnode;
        front = newnode;
    }
}

void DLL::insertAtRear(int data)
{
    dnode *prev,*ptr;
    dnode* newnode = create_node(data);

    if(front == NULL)
    {
        front = newnode;
        rear = newnode;
    }
    else
    {
        for(prev = front, ptr = front -> next ; ptr ; prev = ptr, ptr = ptr -> next);

        if(ptr == NULL)
        {
            prev -> next = newnode;
            newnode -> prev = prev;
            rear = newnode;
        }
    }
}

void DLL::insertBefore(int data, dnode *node)
{
    dnode *prev,*ptr;
    dnode* newnode = create_node(data);

    if(front == NULL)
    {
        front = newnode;
        rear = newnode;
    }
    else
    {
        node->prev->next = newnode;
        newnode -> prev = node -> prev;
        newnode -> next = node;
    }
}

void DLL::insertAfter(int data, dnode* node)
{
    dnode *prev,*ptr;
    dnode* newnode = create_node(data);

    if(front == NULL)
    {
        front = newnode;
        rear = newnode;
    }
    else
    {
        newnode -> next = node -> next;
        node->next = newnode;
        newnode -> prev = node;
    }

}

void DLL::deleteFront()
{
    dnode *temp;
    
    temp = front;
    front = front -> next;
    front -> prev = NULL;

    delete temp;
}

void DLL::deleteLast()
{
    dnode *temp;
    
    temp = rear;
    rear -> prev -> next = NULL;
    rear = rear -> prev;
    delete temp;
}

void DLL::del(int data)
{
  if(front == NULL)
  {
    cout<<"List is empty"<<endl;
    return;
  }

  dnode *searchNode;

  if((searchNode = search(data)) != NULL)
  {
    cout<<"SNData :"<<rear->data<<endl; 
    if(front == searchNode)
    {
      cout<<"front"<<endl;
      deleteFront();
    }
    else if(rear == searchNode)
    {
      cout<<"last"<<endl;
      deleteLast();
    }
    else
    {
      dnode *temp;
      temp = searchNode;

      searchNode -> prev -> next = searchNode -> next;
      searchNode -> next -> prev = searchNode -> prev;

      delete temp;
    }
  }
}

dnode* DLL::search(int data)
{
  dnode *prev,*ptr;
  for(ptr = front ; ptr ; ptr = ptr -> next)
  {
    if(ptr -> data == data)
      return ptr;
  }
    
  return NULL;
}


void DLL::display()
{
    dnode *ptr;

    if(front == NULL)
    {
        cout<<"List is empty"<<endl;
        return;
    }

    for(ptr = front ; ptr ; ptr = ptr ->next)
        cout<<"->"<<ptr->data;

    cout<<endl;
}

DLL::~DLL()
{
    while(front)
    {
        dnode* temp = front;
        front  = front ->next;
        delete temp;
    }
    cout<<"~DLL()"<<endl;
}

int main()
{
    DLL d1;

    d1.insertAtFront(4);
    d1.insertAtFront(2);
    d1.insertAtFront(23);
    d1.insertAtRear(12);
    d1.insertAtRear(27);
    d1.insertAtRear(42);
    d1.display();
    d1.deleteFront();
    d1.display();
    d1.deleteLast();
    d1.display();
    d1.del(27);
    d1.display();
}

Monday, July 12, 2010

BitWise Operators

This is a multi purpose bit operations program.
I have covered the most basic operations that can be performed using bitwise operators.

#include <stdio.h>
#include <stdlib.h>
#define CHAR_BIT 8         //No. of bits in a byte
#define BAD_INPUT_CUTOFF 3

int str[32];
enum {S=0,U};             //S-Set U-Unset

void showbits(unsigned int);

void toggle(int *inp)
{
    int mask = 0XFFFFFFFF;
    *inp = mask ^ *inp;
    showbits(*inp);
}

void detectset(unsigned int inp)
{
    int i , flag = 0;
    unsigned int mask = 0x80000000;
    int s = sizeof(inp) * CHAR_BIT - 1;

    for(i=0; i < s; i++)
    {
        if((mask & inp)!= 0 )
        {
            printf("%dth ,",i+1);
            flag = 1;
        }
        mask = mask >> 1;
    }

    if(flag == 1)
    {
      printf(" bits are set\n");
    }
    else
    {
       printf("\nNone of the bits are set\n");
    }
}

void set_unset(int *inp,int op)
{
    int n,temp;
    unsigned int mask;

    if(op == S)
    {
        printf("\nEnter the bit(1-32) which you want to set: ");
        scanf("%d",&n);

        mask = 0x80000000;

        mask = mask>>(n-1);

        temp = *inp;
        if((*inp = *inp | mask ) == temp)
        {
            printf("\nThe bit was set already\n");
            return;
        }
    }
    else if(op == U)
    {
        printf("\nEnter the bit(1-32) which you want to unset: ");
        scanf("%d",&n);

        mask = 0x80000000;

        mask = mask>>(n-1);

        temp = *inp;
        if((*inp = *inp ^ mask ) == temp)
        {
            printf("\nThe bit was unset already\n");
            return;
        }

    }
    else
    {
        printf("\nSecond Argument must be S or U !!!");
        return;
    }
}

void check_set(int inp)
{
    int n;
    printf("\nEnter which bit you want to check : \n");
    scanf("%d",&n);

    unsigned int mask = 0x80000000 >> n-1; //Mask is 32bit 1000 0000 0000 0000 0000 0000 0000 0000
    if ( mask & inp )
    {
        // AND (&) of the two will be 0000 0000 0000 0000 (false)
        printf("Input has %dth bit set. \n",n);
    }
    else
    {
        printf("Input has %dth bit unset. \n",n);
    }

}

void showbits(unsigned int value)
{
    unsigned int bit;
    for ( bit = (-1U >> 1) + 1; bit > 0; bit >>= 1 )
    {
        putchar(value & bit ? '1' : '0');
    }
    putchar('\n');
}

void reverse_bits(unsigned int *inp)
{
    unsigned int rev = *inp;
    int s = sizeof(*inp) * CHAR_BIT - 1; // extra shift needed at end

    for (*inp >>= 1; *inp; *inp >>= 1)
    {
        rev = rev << 1;
        rev = rev | (*inp & 1);
        s--;
    }
    rev = rev << s;
    *inp = rev;
    showbits(*inp);
}

int main()
{
    int input ,ch ;

    printf("\nEnter an integer of size %d bytes to be displayed in binary : ",sizeof(int));
    scanf("%d", &input);

    while(1)
    {
        printf("\n1.Toggle all bits\n2.Detect all set bits\n3.Set a bit\n4.Unset a bit\n5.Check bit status\n6.Reverse bit pattern\n7.Show the bit pattern\n8.Exit\nEnter your choice : ");
        scanf("%d",&ch);

        switch(ch)
        {
        case 1 :
            toggle(&input);
            break;
        case 2 :
            detectset(input);
            break;
        case 3 :
            set_unset(&input,S);
            break;
        case 4 :
            set_unset(&input,U);
            break;
        case 5 :
            check_set(input);
            break;
        case 6 :
            reverse_bits(&input);
            break;
        case 7 :
            showbits(input);
            break;
        case 8 :
            exit(0);
        }
    }
}

Friday, July 9, 2010

Operator Overloading

A simple example of operator overloading

#include<iostream>

using namespace std;

class Dollar
{
private:
    int dlr;
public :
    Dollar(int dollar = 0)
    {
        dlr = dollar;
    }
    friend Dollar operator +(const Dollar &oper1, const Dollar &oper2);

    int getDollars()
    {
        return dlr ;
    }
};

Dollar operator +(const Dollar &oper1, const Dollar &oper2)
{
    return ( oper1.dlr + oper2.dlr );
}

int main()
{
    Dollar d1(4);
    Dollar d2(6);


    cout<< (d1 + d2).getDollars();
    return 0;
}

Simple Stack using Arrays

A Simple stack using arrays.

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

class Base{
  
  public:
  virtual void push(int) = 0;
  virtual int pop() = 0;
};

class Stack : public Base{
 
  int *arr;
  int stack_len; 
  public:
    
   int top;
   Stack(int size);
  ~Stack();

 void push(int);
 int pop();
 void print_stack();
};

Stack::Stack(int size)
{
   arr = new int[size];
   top = -1;
   stack_len = size;
}

Stack::~Stack()
{
  delete[] arr;
}

void Stack::push(int item)
{
  if((top + 1) < stack_len)
  { 
    cout<<"Pushed "<<item<<endl;
    arr[++top] = item;
    print_stack();
  }
  else
    {
   cout<<"Stack Full!!!";
   exit(0);
 }
}

int Stack::pop()
{
  if(top!= -1)
  {
    cout<<"Popped "<<arr[top]<<endl;
    --top;
    print_stack();
  }
  else
    {
   cout<<"Stack Empty!!!";
   exit(0);
 }
}

void Stack::print_stack()
{
  int i;
  for(i = top ; i > -1 ; i--)
  {
    cout<<" "<<arr[i];
  }
  cout<<endl;
}

int main()
{
  Stack s1(5);

  s1.push(1);
  s1.push(2);
  s1.push(3);
  s1.push(4);
  
  s1.pop();
  s1.pop();

}

Singleton Design Pattern

Here we present the implementation for a Singleton class.


//singleton.hpp
class Singleton
{
  private:
    int value;
    static Singleton *_instance;
    Singleton();
    Singleton(const Singleton&);
    Singleton & operator=(const Singleton &);
    ~Singleton();
    
  public:
    int getVal();
    void setVal(int);
    static Singleton* getInstance();
};

Singleton* Singleton::_instance;


//singleton.cpp
#include "singleton.hpp"
#include <iostream>

using namespace std;

Singleton::Singleton()
{
 cout<<"Singleton constructor"<<endl;
}

Singleton* Singleton::getInstance()
{
 if(!_instance)
   _instance = new Singleton;
  return _instance;
}

Singleton::~Singleton()
{
  cout<<"Singleton destructor"<<endl; 
}

int Singleton :: getVal()
{
  return value;  
}

void Singleton :: setVal(int val)
{
  value = val;
}

int main()
{
  Singleton::getInstance()->setVal(20);
  cout << Singleton::getInstance()->getVal();   
}


To run the program :
1. g++ -o singleton singleton.cpp (make sure that the header file singleton.hpp is in the same directory as singleton.cpp)
2. ./singleton

Monday, July 5, 2010

Virtual Functions Explained

Virtual function is the probably most sought after feature of Object Oriented Programming practice.
Let me explain how it works.

Consider a case where a function called speak() is used in the base class Animals.
Now we derive a class like Dog from the base class and using a base's pointer try to call a derived overridden function, Here's what happens

#include <iostream>
using namespace std;

class Animals{

  public :

    virtual void speak(){
      cout<<"Animals speak random";
    }
};

class Dog: public Animals{

  public:
    
    void speak(){
      cout<<"Dogs woof";
    }
};

int main()
{
  Animals *a;
  Dog d;

  a = &d;

  a->speak();
}

Output:

//without virtual speak()

Animals speak random

//with virtual speak()

Dog woof



The Base class speak() function is called.

But if we add a virtual keyword in front of speak() , we would be able to access the derived class's function speak().

So Virtual Functions resolve to the most derived class's function which is overridden.

So user can have different functionality in Derived class for the same function using the virtual keyword.

Whenever a class declares a virtual function or is derived directly or indirectly from a class which declares a
virtual function, the compiler adds an extra hidden member variable which points to the virtual table. A virtual table is nothing but an array of pointers to the virtual functions. The entries in the virtual table are changed at run time to point to the correct function.

This is called Dynamic Binding where the resolution happens at runtime .

There is another variant of virtual function and that is a Pure Virtual Function . The only difference between the two being that a Pure Virtual Function needs the implementation to be done compulsorily in the derived classes too otherwise it'll throw a compiler error.And it does not let the base class do the implementation also.

#include <iostream>

using namespace std;

class Animals{

  public :

    void speak() = 0; //pure virtual function
    
};

class Dog: public Animals{

  public:
    
    void speak(){
      cout<<"Dogs woof";
    }
};

int main()
{
  Animals *a;
  Dog d;

  a = &d;

  a->speak();
}

Points to remember regarding virtual functions :

- Never call a virtual functions inside a constructor or a destructor

- There is no such thing called virtual constructor

Sunday, July 4, 2010

Hash Table

Hashing is one of the best techniques when it comes to storing a large amount of random data or it can be unrandom data too :)

It is generally easy to store your data into an array or a linked list. But the searching becomes very hectic and time consuming when this data grows to millions of records.

So the big guys came up with hashing as an alternative to store and retrieve large amounts of data. The search became much faster upto O(1) if there are no collisions!!

Well lets discuss how hashing works if you really want that whatever I have written above starts making sense.

We store data into Hash tables on the basis of a key generated by a hash function.
This hash function uses some formula to generate a key which is in the range of indexes of the Hash Table. And then we store that data into the Hash Table with the help of this key.

key = hash(data);
HashTable[key] = data ;

Now you may be wondering that how this function works.
Take an example :-
If the data to be stored are integers we can define our hash function to return

data % prime

where prime is any prime number(preferably a big prime number)

But now one more problem arises. If we are taking such a formula then the key could be duplicated. Well this situation is called a 'Collision'.

There are various methods for Collision Resoultion.
e.g. Rehashing , Separate Chaining

Separate Chaining is being used by the code snippet below.
Normally data is stored one at a single index. But to resolve collision, at each index we maintain a linked list instead to which we can add our data when the collision occurs. When at the time of searching we get an index , we actually reach at the head of the linked list and then we can continue searching the Linked List.

This has reduced our searching time from searching a million records to few hundreds.So enjoy the code.

P.S : As I am a normal human being , there would be bugs in this code too. Please point out those so that I can improve the quality of the code here.

//linklist_impl.hpp
#include<string>
using namespace std;
class linklist
{
    int c;
    struct node
    {
    public:
        string data;
        node *link;
    } *p;
public:
    linklist();
    void append(string &str);
    void del(string &str);
    void display();
    string getData();
    int searchlist(string);
    bool isListEmpty();
    ~linklist();
};


//linklist_impl.cpp
#include 
#include 
#include 
#include "linklist_impl.hpp"
using namespace std;


linklist::linklist()
{
    p = NULL;
    c = 0;
}

void linklist::append(string &str)
{
    node *q, *t;
    if(p==NULL)
    {
        p = new node;
        p->data = str;
        p->link = NULL;
        c += 1;
    }
    else
    {
        q = p;
        while(q->link != NULL)
        {
            q = q->link;
        }
        t = new node;
        t->data = str;
        t->link = NULL;
        q->link = t;
        c += 1;
    }
}

void linklist::del(string &str)
{
    node *q, *r;
    q = p;
    if(q->data == str)
    {
        p = q->link;
        delete q;
        c -= 1;
        return;
    }
    r = q;
    while(q != NULL)
    {
        if(q->data == str)
        {
            r->link = q->link;
            delete q;
            c -= 1;
            return;
        }
        r = q;
        q = q->link;
    }
    cout<<"Element "<<str<<" not found"<<endl;
}

void linklist::display()
{
    node *q;
    int i;
    for(q = p, i = 0; q != NULL, i < c; q = q->link, i++)
    {
        cout<<"\t"<<i<<": "<<q->data<<endl;
    }
}

string linklist::getData()
{
  return p->data;
}

bool linklist::isListEmpty()
{
    node *q;
    int i,flag = 0;
    for(q = p, i = 0; q != NULL, i < c; q = q->link, i++)
    {
      if(q->data != "")
        flag = 1;
    }
    if(flag == 1)
      return false;
    else 
      return true;
}

int linklist::searchlist(string searchItem)
{
    node *q;
    int i;
    for(q = p, i = 0; q != NULL, i < c; q = q->link, i++)
    {
      if(q -> data == searchItem)
        return i;
    }
    return -1;
}

linklist::~linklist()
{
    node *q;
    if(p == NULL)
    {
        return;
    }
    while(p != NULL)
    {
        q = p->link;
        delete p;
        p = q;
    }
}



//schashtable.cpp
#include<iostream>
#include<sys/time.h>
#include<stdlib.h>
#include<stdio.h>
#include<limits>
#include<cstring>
#include "linklist_impl.hpp"

using namespace std;
struct timeval starttime,endtime,timediff;
enum {FILLED = 0 , ALL};
const int sizeHTable = 5;


class table
{

private:
    linklist *items;
    int nel;
    int strhash(const char *str); 
public:
    table(int size);
    ~table();
    void addItem();
    int searchTable(string);
    void delItem();
    void display( int mode);
    int getCount();
    bool isEmpty();
};

#define BAD_INPUT_CUTOFF 3
unsigned int getIntInRange(unsigned int min, unsigned int max, 
                           const char *prompt)
{
    int input, //used to get input
    bad_count=0; //used to keep track of how many bad attempts.
    do
    {
        std::cout << prompt; 
        std::cin >> input; 
        if (!std::cin.good() || input < min || input > max)
        {
            std::cout << "\nInvalid Input!" << std::endl;
            std::cin.clear(); //resets the state flag
            
//clears out the buffer
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n'); 
                   
            bad_count++; //User made a bad input, count it
            input = 0;   // user did not enter a valid number
        }
        //See if this is a valid number (users are mean/stupid sometimes)
    }
    while (input == 0 && bad_count < BAD_INPUT_CUTOFF);
    return input;
}


table::table(int size)
{
    items = new linklist[size];
    for(int i = 0; i<sizeHTable ;i++)
    nel = 0;
}

table::~table()
{   
    if(items)
    delete[] items;
}

int table::strhash(const char *str) {
    unsigned long hash = 0;
      int i=0;
        while(i <= strlen(str)) {
              hash = hash + (hash<<5) + (unsigned long)(str[i]); 
                  i++;
                    }
          return (hash%sizeHTable); //return the hashed number which must be  
                                    //between 0 an size-1, this is why I used
                                    //hash%size
}

void table::addItem()
{
        string str;
        
        cout<<"\nEnter Data : ";
        cin>>str;

        
        int i = strhash(str.c_str());
        if( i >= 0 && i < sizeHTable )
        {
            items[i].append(str);
            cout<<"\nInserted";
            nel++;
            return;
        }

}

int table::searchTable(string searchItem)
{
    int pos;
    
    int i = strhash(searchItem.c_str());

    if((pos = items[i].searchlist(searchItem)) != -1 )
    {
        cout<<"Bucket["<<i<<"] -> pos : "<<pos<<"\t" <<"\t"<< endl;
        return i;
    }
    else
    {
            cout<<"Data "<<searchItem<<" not present in the table" << endl;
            return -1;
    }
}

void table::delItem()
{
    string item;
    cout<<"\nEnter an item to delete : ";
    cin>>item;
    
    int index;
    index = strhash(item.c_str());
        items[index].del(item);
        nel--;
}

bool table::isEmpty()
{
    if( nel > 0)
    {
        return false;
    }
    else
    {
        cout<<"\nTable is Empty"<<endl;
        return true;
    }
}

void table::display(int mode = FILLED)
{
    if(isEmpty())
        return;

   if(mode == FILLED)
   {
     int i;
     for(i=0; i<sizeHTable; i++)
     {  
        if(items[i].isListEmpty() == false)
        {
          cout<<"Bucket["<<i<<"] :"<<endl;
          items[i].display(); //call the function of our linked list, 
                              //which outputs it's records with their indexes
        }
     }
   }  
   else if(mode == ALL)
   { 
     int i;
     for(i=0; i<sizeHTable; i++)
     {
        cout<<"Bucket["<<i<<"] :"<<endl;
        items[i].display(); //call the function of our linked list, 
                            //which outputs it's records with their indexes
     }
   }  
}

int table::getCount()
{
    return nel;
}

int main()
{
    int choice;
    
    string item;
    table T1(sizeHTable);
    int mode;

    while(1)
    {
        choice = getIntInRange(1,6,"\n1.Add New Item\n2.Delete Item 
                 \n3.Search Item \n4.Display Hash Table \n5.Get the 
                  number of elements \n6.Exit\nEnter your choice : ");
        
            switch(choice)
            {
            case 1 :
                T1.addItem();
                break;
            case 2 :
                T1.delItem();
                break;
            case 3 :
                if(T1.isEmpty() != true)
                {
                    cout<<"\nEnter an item to search : ";
                    cin>>item;
                    T1.searchTable(item);
                }
                break;
            case 4 :
                cout<<"\nEnter display mode (0 - FILLED / 1- ALL) : ";
                cin>>mode;
                T1.display(mode);
                break;
             case 5 :
                cout<<"Total no. of elements : "<<T1.getCount()<<endl;
                break;
             case 6 :
                exit(0);
            }
        
    }
    
    
}



Run the example in gnu compiler as

user@linux~> g++ linklist_impl.cpp schashtable.cpp
user@linux~> ./a.out

or you can also use makefile.

Saturday, July 3, 2010

Linked List

Here's a simple implementation of Singly linked list in C++ , which includes insertion , deletion and searching .

#include <cstdio>
#include <stdlib.h>
#include <iostream>
#include <limits>
#define BAD_INPUT_CUTOFF 3

using namespace std;


struct node
{
    int data;
    struct node* next;
};

struct searchDS
{
    int occurence;
    int posit[100];
};

typedef struct node Node;
typedef struct searchDS SD;

Node *start = NULL;
Node *new1;

void print_list(Node*);
int print_no();
int count();
unsigned int getIntInRange(unsigned int min, unsigned int max, const char *prompt);

Node* create_node()
{
    Node* newnode;

    newnode = (Node*)malloc(sizeof(struct node));

    printf("\nEnter the data (numeric only): ");
    scanf("%d", &newnode -> data);
    newnode -> next = NULL;

    return newnode;
}

int isEmpty()
{
    if(start == NULL)
    {
        printf("\nList is empty");
        return true;
    }
    else
        return false;
}

Node* search(int data)
{
    Node* ptr;

    int flag = 0;

    for(ptr = start ; ptr; ptr = ptr -> next)
    {
        if(ptr -> data == data)
        {
            flag = 1;
            printf("\nData %d found at %x ",data,ptr);
        }
    }

    if(flag == 1 )
    {
        return ptr;
    }
    else
    {
        printf("\nData %d not found !!!",data);
        return NULL;
    }
}

void adv_search(int data, SD* sp)
{

    Node *ptr,*prev;

    int i ,j, pos = 1;

    if(start ==  NULL)
    {
        printf("\nList is empty ");
        return;
    }
    sp->occurence = 0;

    for(i=0,ptr = start; (ptr); ptr = ptr->next,pos++)
    {
        if(ptr -> data == data)
        {
            (sp->occurence)++;
            sp->posit[i++] = pos ;
        }
    }

    if(sp->occurence == 0)
    {
        printf("\nData %d not in the list!!!",data);
        return;
    }
    printf("\nOcc: %d , Positions : ", sp->occurence);
    for(j=0; j<i; j++)
        printf("%d, ",sp->posit[j]);
    printf("\n");
}

void insert_beg()
{
//printf("\n In function %s\n",__func__);

    new1 = create_node();

    if(start == NULL)
    {
        start = new1;
        print_list(start);
        return;
    }
    else
    {
        new1 -> next = start ;
        start = new1;
        print_list(start);
        return;
    }
}
void insert_end()
{
    Node *ptr,*prev;
//printf("\n In function %s\n",__func__);

    new1 = create_node();

    if(start == NULL)
    {
        start = new1;
        print_list(start);
        return;
    }
    else
    {
        for(prev = start , ptr = start -> next ; ptr ; prev = ptr , ptr = ptr -> next);

        prev -> next = new1;
        print_list(start);
    }
}
void insert_at_pos()
{
    Node *ptr , *prev;
    int pos,i;
//printf("\n In function %s\n",__func__);

    new1 = create_node();

    printf("\nWhat position do you want to enter ? ");
    scanf("%d",&pos);

    if (pos < 1 || pos > print_no())
    {
        printf("\n Inserting failed! Out of bounds!!!");
        return;
    }
    else if(pos == 1)
    {
        new1 -> next = start;
        start = new1;
        print_list(start);
    }
    else if(pos > 1)
    {
        for(i = 1 ,prev = start, ptr = start -> next; (ptr) && (i < pos -1); prev = ptr , ptr = ptr->next,i++);
        prev -> next = new1 ;
        new1 -> next = ptr ;

        print_list(start);
    }
}

void delete_node_by_pos()
{
    Node *prev, *ptr, *temp;
    int pos,i;
    //printf("\n In function %s\n",__func__);

    if(isEmpty() != true)
    {
        printf("\nEnter the node no. you want to delete: ");
        scanf("%d",&pos);

        if (pos < 1 || pos > count())
        {
            printf("\n Deletion failed! Out of bounds!!!");
            return;
        }
        else if(pos == 1)
        {
            temp = start;
            start = start -> next;
            free(temp);
            print_list(start);
        }
        else if(pos > 1)
        {
            for(i = 1 ,prev = start, ptr = start -> next; (ptr) && (i < pos -1); prev = ptr , ptr = ptr->next,i++)
            {
                //`printf("\n prev-> data : %d\tptr->data :%d" ,prev-> data, ptr->data);
            }
            temp = ptr;
            prev -> next = ptr -> next;
            free(temp);
            print_list(start);
        }
    }
}

void delete_node_by_data()
{
    Node *ptr,*prev,*temp;
    int info, ch;
    SD sp;
    static int visited = 0;
    //printf("\n In function %s\n",__func__);

    if(isEmpty() != true)
    {
        printf("\nEnter the data you want to delete: ");
        scanf("%d",&info);
        adv_search(info, &sp);

        {
            if(start -> data == info )
            {
                temp = start;
                start = start -> next;
                free(temp);
                print_list(start);
                return;
            }
            for(prev = start , ptr = start -> next ; ptr ; prev = ptr , ptr = ptr -> next)
            {
                if( ptr -> data == info)
                {
                    temp = ptr;
                    prev -> next = ptr -> next;
                    free(temp);
                    print_list(start);
                    return;
                }
            }
        }
        print_list(start);
    }
}


void print_list(Node* start)
{
    Node *ptr;
//printf("\n In function %s\n",__func__);

    printf("\n");
    for(ptr = start; ptr ; ptr = ptr ->next )
    {
        printf("-> %d ",ptr->data);
    }
    printf("\n");
}
int print_no()
{
//printf("\n In function %s\n",__func__);
    printf("\nThe total no. of members in the list are : %d \n", count());
}

int count()
{

    Node *ptr;
    int count = 0;

    ptr = start ;
    while(ptr!=NULL)
    {
        ptr = ptr -> next;
        count++;
    }

    return count;
}

Node* reverse(Node* root)
{
    Node* ret_val;

    if ( root == NULL || root->next == NULL )
    {
        return root;
    }
    ret_val = reverse ( root -> next );

    root -> next->next = root;
    root->next = NULL;
    return ret_val;
}

unsigned int getIntInRange(unsigned int min, unsigned int max, 
                           const char *prompt)
{
    int input, //used to get input
        bad_count=0; //used to keep track of how many bad attempts.
    do
    {
        cout << prompt; //print out our prompt
        cin >> input; //get the input
        if (!cin.good() || input < min || input > max)
        {
            cout << "\nInvalid Input!" << std::endl;
            cin.clear(); //resets the state flag
            cin.ignore(numeric_limits<streamsize>::max(),'\n'); 
                        //clears out the buffer
            bad_count++; //User made a bad input, count it
            input = 0; // user did not enter a valid number
        }
    }
    while (input == 0 && bad_count < BAD_INPUT_CUTOFF);
    return input;
}

int main()
{
    int choice,searchKey,info;
    SD sp;
    Node* temp;
    while(1)
    {

        printf("\n1.Insert a node at beg\n2.Insert a node at end
                \n3.Insert a node at a given position\n4.Delete a 
                node by data\n5.Delete a node by position\n6.Print
                the list\n7.Print the no. of elements\n8.Reverse the 
                list\n9.Search \n10.Advanced Search\n11.Exit\n");

         choice  = getIntInRange(1,11,"\n Choose your option (1-11):\n");

        switch(choice)
        {
        case 1 :
            insert_beg();
            break;
        case 2 :
            insert_end();
            break;
        case 3 :
            insert_at_pos();
            break;
        case 4 :
            delete_node_by_data();
            break;
        case 5 :
            delete_node_by_pos();
            break;
        case 6 :
            print_list(start);
            break;
        case 7 :
            print_no();
            break;
        case 8 :
            start = reverse(start);
            print_list(start);
            break;
        case 9 :
            printf("\nEnter the data you want to search : ");
            scanf("%d",&searchKey);

            if(search(searchKey)!=NULL)
                printf("\nData %d at %x",searchKey , search(searchKey));

            break;
        case 10 :
            printf("\nEnter the data you want to search : ");
            scanf("%d",&searchKey);
            adv_search(searchKey,&sp);
            break;
        case 11 :
            exit(0);

        default :
            printf("\nInvalid input !!!\n");
            break;

        }
    }
}