Tuesday, 1 October 2013

News Paper Delivery Boy

//============================================================================
// Name        : newspaperboy.cpp
// Author      : your name
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
/* Each vertex of the graph represents a lane.An edge of the graph gives distance between two adjacent lanes */

#include <iostream>
using namespace std;
struct path
{
  public:
         int length;
         int n;
         int a[10];
         void insert( int u, int v, int w)
         {
             a[n++] = v;
            length = length + w;
         }
         int member( int x);
          void display();
};

int path::member( int x )
{
    for( int i=0; i<n; i++)
        if(a[i] == x)
        return 1;
    return 0;
}

void path::display()
{
   int i;
   cout<<"\n Path length = " << length << " Path :";
   for( i =0; i<n; i++)
    cout<<a[i]<<" ";
}

class graph
{
  int adj[10][10];
  int vn;            //no. of vertices
  public:
         graph(){ vn = 0;}
         void readgraph();
         void findpath(int u);
};
void graph::findpath(int u)
{
  int top1 = -1,top2 = -1,i,v,minimum;
  path stack1[20], stack2[20];  //stack2 store the final path
  path temp, temp1;

  temp.n = 1;
  temp.length = 0;
  temp.a[0] = u;
  stack1[++top1] = temp;
  while( top1 != -1) // as long as stack1 is not empty
  {
     temp = stack1[top1--];
     // for each vertex adjacent to the last vertex of the path
     u = temp.a[temp.n-1];
     for( v=0; v<vn ; v++)
     {
         if( !temp.member(v) && adj[u][v] != 0)
         {
             temp1 = temp;
             temp1.insert(u,v,adj[u][v]);
             if ( temp1.n == vn)
                 stack2[++top2] = temp1;
             else
                 stack1[++top1] = temp1;
         }
     }
   }
   minimum = 999;
   cout<<"\nAll Paths : \n";
   for( i=0; i<=top2; i++)
   {
       if(stack2[i].length < minimum)
        minimum = stack2[i].length;
    stack2[i].display();
   }
   cout<<"\n Minimum Length Path : \n";
   for( i=0; i <= top2; i++)
   {
      if(stack2[i].length == minimum)
          stack2[i].display();
   }
}

void graph::readgraph()
{
   int i,j;
   int n,u,v,w;
   cout<<"\n Enter no. of vertices : ";
   cin>>vn;
   // initialize
   for( i=0; i<vn; i++)
       for( j=0; j<vn; j++)
           adj[i][j] = 0;
   cout<<"\n Enter no. of edges : ";
   cin>>n;
   cout<<"\nEnter each edge as (u v w) : ";
   for( i=0; i<n; i++)
   {
         cout<<"\n Enter the next edge : ";
         cin>>u>>v>>w;
         adj[u][v] = w;
         adj[v][u] = w;
    }
}

int main()
{
    graph g;
    int start;
    g.readgraph();
    cout<<"\n Enter the starting vertex : ";
    cin>>start;
    g.findpath(start);
    return 0;
}

Thursday, 5 September 2013

Shell sort in python

class shell:
    #constructor defined
    def __init__(self,datalist):
          self.datalist = datalist
#defining methods inside the class:Encapsulation feature
    def shellsort(self):
          n=len(self.datalist)
          step=int(n/2)
          while step>0:
               i=step
               while i<n:
                    temp=self.datalist[i]
                    j=i
                    while j>=step:
                          if temp<self.datalist[j-step]:
                              self.datalist[j]=self.datalist[j-step]
                          else:
                              break
                          j=j-step
                    self.datalist[j]=temp
                    i=i+1
               step=int(step/2)


    def display(self):
            print(self.datalist)


  # Main Program
input = raw_input("Enter the values: ")     # Accept input from user
inputList = input.split()                   # Convert into list with space separator
inputList = [int(i) for i in inputList]     # Convert input into int array

obj = shell(inputList)

obj.display()
obj.shellsort()
obj.display()

1st prac Veg_&_Fruits

#include <iostream>
#include<string.h>
#define MAX 30
using namespace std;
class veg
{
public:
string v;
int vcount;
void getveg(string s,int p)
{
v=s;
vcount=p;
}
void display_veg(void)
{
cout<<"\n";
cout<<v;
cout<<"\t\t"<<vcount;
}
};
 class fruit
 {
 public:
string f;
int fcount;
void getfruit(string s,int p)
{
f=s;
fcount=p;

}
void display_fruit(void)
{
cout<<"\n";
cout<<f;
cout<<"\t\t"<<fcount;
}
 };

 void arrange(veg *vobj[MAX],fruit *fobj[MAX],int n)
 {
int temp;
string s;
int i,j;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(vobj[i]->vcount<vobj[j+1]->vcount)
{
temp=vobj[i]->vcount;
s=vobj[j]->v;
vobj[j]->vcount=vobj[j+1]->vcount;
vobj[i]->v=vobj[j+1]->v;
vobj[j+1]->vcount=temp;
vobj[j+1]->v=s;

}
}
}
 for(i=0;i<n-1;i++)
  {
  for(j=0;j<n-i-1;j++)
  {
  if(fobj[i]->fcount<fobj[j+1]->fcount)
  {
  temp=fobj[i]->fcount;
  s=fobj[j]->f;
  fobj[j]->fcount=fobj[j+1]->fcount;
  fobj[i]->f=fobj[j+1]->f;
  fobj[j+1]->fcount=temp;
  fobj[j+1]->f=s;
  }
  }
  }
cout<<"\n veg \t\t fruit";
cout<<"\n------------------";
for(i=0;i<n;i++)
{
cout<<"\n";
cout<<vobj[i]->v<<"\t\t"<<fobj[i]->f;
}
}

 int main()
{
veg *vobj[MAX];
string vname="";
int vcount;
fruit *fobj[MAX];
string fname="";
int fcount,i,n;

void arrange(veg *vobj[MAX],fruit *fobj[MAX], int n);

cout<<"\n \t\t\t VEGETABLE AND FRUIT PURCHASE PATTERN";
cout<<"\n how many items?";
cin>>n;
cout<<"\n ENTRE THE VEGETABLE DETAILS \n";
for(i=0;i<n;i++)
{
cout<<"veg name:";
cin>>vname;
cout<<"Total purchase count:";
cin>>vcount;
vobj[i]=new veg;
vobj[i]->getveg(vname,vcount);
}
cout<<"\n Entre fruit details\n";
for(i=0;i<n;i++)
{
cout<<"fruit name:";
cin>>fname;
cout<<"Total purchase count:";
cin>>fcount;
fobj[i]=new fruit;
fobj[i]->getfruit(fname,fcount);
}
cout<<"\n vegetable \t purchase count";
cout<<"\n-----------------------------------------------------";
for(i=0;i<n;i++)
{
vobj[i]->display_veg();

}
cout<<"\n fruit \t\t\t purchase count";
cout<<"\n -----------------------------------------------------";
for(i=0;i<n;i++)
{
fobj[i]-> display_fruit();
}
      cout<<"\n\n arranging according to purchase pattern ---------";
      arrange(vobj,fobj,n);
      return 0;
}

Queue Operations

// Queue.java demonstrates operations on queue


import java.util.Scanner;

class Queue
   {
   private int maxSize;
   private int[] queArray;
   private int front;
   private int rear;
   private int nItems;
   public Queue(int s)         
      {
      maxSize = s;
      queArray = new int[maxSize];
      front = 0;
      rear = -1;
      nItems = 0;
      }
   public void insert(int j)
   {
       if( !isFull())
             {                      
                 queArray[++rear] = j;
                 nItems++;
             }
       else
           System.out.println("Queue is Full");
           
   }
   public int remove()     
   {
       int temp=0;
       if(!isEmpty())
       {
           temp = queArray[front++];    
           nItems--;                               
           System.out.println("Element deleted : " +temp);
         
           if(isFull() )  
               front = 0;
       }
       else
           System.out.println("Queue is Empty");
       return temp;
    }
   public void display()   
      {
         long num;
         int n = front;
         if(isEmpty())
         {
             System.out.println("Queue is Empty");
             return;
         }
         while(n != rear + 1)
         {                           
             num = queArray[n];        
             System.out.print(num);
             System.out.print(" ");
             n++;
         }
         System.out.println("");
      }

   public boolean isEmpty()
      {    
       return (nItems==0);
      }

   public boolean isFull() 
      {
       return (nItems==maxSize);
      }
   }

class QueueApp
{
   public static void main(String[] args)
   {
      Queue theQueue = new Queue(5);
      int ch,num;
      do
      {
          System.out.println("1. Insert in Queue \n2. Delete from Queue");
          System.out.println("3. Display Queue \n4. Quit ");
          System.out.println(" Enter your Choice : ");
          Scanner input = new Scanner(System.in);
          ch = input.nextInt();
          switch(ch)
          {
              case 1:
                            System.out.println("Enter element in Queue");
                          num = input.nextInt();
                          theQueue.insert(num);
                          break;
              case 2:     theQueue.remove();
                          break;
              case 3:     theQueue.display();
                          break;
              case 4:     System.exit(0);                        
              default: System.out.println("Invalid choice!");
          }
      }while(ch > 0);
   }
}

Wednesday, 28 August 2013

Circular Doubly Linked List & Output

//==========================================
// Name        : circulardoublyll.cpp
// Author      : your name
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//==========================================

#include <iostream>
#include<stdlib.h>

using namespace std;

class sll
{
private:
    struct node
    {
        int data;
        struct node *prev;
        struct node *next;
    }*head;
public:
    sll();
    void create();
    void display();
    void insert_first();
    void insert_rear();
};

sll::sll()
{
    head=NULL;
}

void sll::create()
{
    char ans;
    int flag=1;
    node *newnode,*temp;

    do
    {
        newnode=new node;
        cout<<endl<<"Enter the element : ";
        cin>>newnode->data;

        if(flag==1)
        {
            head=newnode;
            newnode->next=head;
            newnode->prev=head;
            flag=0;
        }
        else
        {
            temp=head;
            while(temp->next!=head)
                temp=temp->next;
            temp->next=newnode;
            newnode->prev=temp;
            newnode->next=head;
            head->prev=newnode;
        }

        cout<<"\nDo you want to enter more nodes ?";
        cin>>ans;
    }while(ans=='y'||ans=='Y');
}

void sll::display()
{
    node *temp;
    temp=head;
    if(temp==NULL)
        cout<<"\nSorry !!, The list is empty !!"<<endl;
    else
    {   cout<<"->>";
        do
        {
            cout<<"\t"<<temp->data;
            temp=temp->next;
        }while(temp!=head);
    }
}

void sll::insert_first()
{
    node *p,*temp;
    p=new node;
    cout<<"\n\nEnter the element you want to insert : ";
    cin>>p->data;

    if(head==NULL)
    {
        head=p;
        p->next=head;
        p->prev=head;
    }

    else
    {
        temp=head;
        while(temp->next!=head)
            temp=temp->next;
        temp->next=p;
        p->next=head;
        head->prev=p;
        p->prev=temp;
        head=p;
        cout<<"\nThe node is inserted";
    }
}

void sll::insert_rear()
{
    node *p,*temp;
    p=new node;

    cout<<"\n\nEnter the element you want to insert : ";
    cin>>p->data;

    if(head==NULL)
    {
        head=p;
        p->next=head;
        p->prev=head;
        insert_first();
        void insert_rear();
    }
    else
    {
        temp=head;
        while(temp->next!=head)
            temp=temp->next;
        temp->next=p;
        p->next=head;
        p->prev=temp;
        head->prev=p;
        cout<<"\nThe node is inserted";
    }
}

int main()
{
    sll l;
    char ans;
    int ch;
    do
    {
        cout<<endl<<"program for Circular Linked List"<<endl;
        cout<<"1. Creat a circular linked list"<<endl;
        cout<<"2. Display"<<endl;
        cout<<"3. Insert more node at front"<<endl;
        cout<<"4. Insert more node at rear"<<endl;
        cout<<endl<<"Enter your choice";
        cin>>ch;

        switch(ch)
        {
        case 1:l.create();
                break;
        case 2:l.display();
                break;
        case 3:l.insert_first();
                break;
        case 4:l.insert_rear();
                break;
        default:cout<<"\t\tWrong Entry !!!!!";
                break;
        }

        cout<<endl<<"do you want to go to the main manu to continue(y/n)";
        cin>>ans;
    }while(ans=='y'||ans=='y');

return 0;
}

                               Output of Program
program for Circular Linked List
1. Creat a circular linked list
2. Display
3. Insert more node at front
4. Insert more node at rear

Enter your choice1

Enter the element : 11

Do you want to enter more nodes ?
y

Enter the element : 22

Do you want to enter more nodes ?
y

Enter the element : 33

Do you want to enter more nodes ?
y

Enter the element : 44

Do you want to enter more nodes ?
y

Enter the element : 55

Do you want to enter more nodes ?
n

do you want to go to the main manu to continue(y/n)
y

program for Circular Linked List
1. Creat a circular linked list
2. Display
3. Insert more node at front
4. Insert more node at rear

Enter your choice2
->>    11    22    33    44    55
do you want to go to the main manu to continue(y/n)
y

program for Circular Linked List
1. Creat a circular linked list
2. Display
3. Insert more node at front
4. Insert more node at rear

Enter your choice3


Enter the element you want to insert : 00

The node is inserted
do you want to go to the main manu to continue(y/n)
y

program for Circular Linked List
1. Creat a circular linked list
2. Display
3. Insert more node at front
4. Insert more node at rear

Enter your choice2
->>    0    11    22    33    44    55
do you want to go to the main manu to continue(y/n)
y

program for Circular Linked List
1. Creat a circular linked list
2. Display
3. Insert more node at front
4. Insert more node at rear

Enter your choice4


Enter the element you want to insert : 66

The node is inserted
do you want to go to the main manu to continue(y/n)
y

program for Circular Linked List
1. Creat a circular linked list
2. Display
3. Insert more node at front
4. Insert more node at rear

Enter your choice2
->>    0    11    22    33    44    55    66
do you want to go to the main manu to continue(y/n)
n

Dictionary Program for insert,display,modify,search,delete & sort

//====================================
// Name        : dictionary.cpp
// Author      : your name
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//====================================

#include <iostream>
#include<string.h>
#include<stdlib.h>
#define SIZE 30

struct dict
{
    char keyword[20];
    char meaning[20];
}D[SIZE];

using namespace std;

int main()
{
    int choice,n=0;
    char ans;
    void init();
    int insert(int n);
    void display(int n);
    void modify(int n);
    void search(int n);
    void del(int n);
    void sort(int n);

    init();

    do
    {
        cout<<"Prpgram for dictionary";
        cout<<"\n\nDictionary Menu\n";
        cout<<"1.insert"<<endl<<"2.display"<<endl<<"3.Modify"<<endl<<"4.Search"<<endl<<"5.Delete"<<endl<<"6.sort";
        cout<<"\nEnter your choice\n";
        cin>>choice;
        switch(choice)
        {
        case 1:n=insert(n);
                break;
        case 2:display(n);
                break;
        case 3:modify(n);
                break;
        case 4:search(n);
                break;
        case 5:del(n);
                break;
        case 6:sort(n);
               display(n);
                break;
        default:cout<<"Wrong Entry !!!";
                break;
        }

        cout<<"Want to Enter more ??\n";
        cin>>ans;
    }while(ans=='y'||ans=='Y');

    return 0;
}

void init()
{
    int i;
    for(i=0;i<SIZE;i++)
        {
            strcpy(D[i].keyword,"");
            strcpy(D[i].meaning,"");

        }
}

int insert(int i)
{
    if(i<SIZE)
    {
        cout<<"\nEnter the keyword : ";
        cin>>D[i].keyword;
        cout<<"\nEnter the meaning : ";
        cin>>D[i].meaning;
        i++;
    }
    else
        cout<<"Database full";
    return i;
}

void display(int n)
{
    int i;
    for(i=0;i<SIZE;i++)
    {
        if(strcmp(D[i].keyword,"")!=0)
        {
            {
                cout<<D[i].keyword<<"\t\t"<<D[i].meaning<<endl;
            }
        }
    }
}

void search(int n)
{
    int i,flag=0;
    int count=0;
    char key[20];

    cout<<endl<<"Enter the keyword to be searched";
    cin>>key;

    for(i=0;i<n;i++)
    {
        count++;
        if(strcmp(D[i].keyword,key)==0)
        {
            flag=1;
            break;
        }
    }
    if(flag==1)
    {
        cout<<endl<<"Meaning : "<<D[i].meaning;
        cout<<endl<<"Totle comparisons are "<<count<<endl;
    }
    else
        cout<<endl<<"The keyword is not present";
}


void modify(int n)
{
    int i;
    char newkey[20],newmean[20];
    char key[20];

    cout<<endl<<"Enter the keyword for the entry to be modified";
    cin>>key;

    for(i=0;i<n;i++)
    {
        if((strcmp(D[i].keyword,key))==0)
        {
            cout<<"Enter the new keyword : "<<endl;
            cin>>newkey;
            cout<<"Enter the new meaning : "<<endl;
            cin>>newmean;
            strcpy(D[i].keyword,newkey);
            strcpy(D[i].meaning,newmean);
            cout<<endl<<"The entry is modified !!\n";
        }
    }
}


void del(int n)
{
    int i,flag=0;
    char key[20];
    cout<<endl<<"Enter the keyword to be deleted ";
    cin>>key;

    for(i=0;i<n;i++)
    {
        if(strcmp(D[i].keyword,key)==0)
        {
            strcpy(D[i].keyword,"");
            strcpy(D[i].meaning,"");
            flag=1;
        }
    }
    if(flag==0)
    {
        cout<<endl<<"The word is not in dictionary";
    }
}

void sort(int n)
{
    int i,j;
    char tempkey[20];
    char tempmean[20];

    for(i=0;i<n-1;i++)
        for(j=i+1;j<n;j++)
        {
            if(strcmp(D[i].keyword,D[j].keyword)>0)
            {
            strcpy(tempkey,D[i].keyword);
            strcpy(tempmean,D[i].meaning);

            strcpy(D[i].keyword,D[j].keyword);
            strcpy(D[i].meaning,D[j].meaning);

            strcpy(D[j].keyword,tempkey);
            strcpy(D[j].meaning,tempmean);

            }
        }
}


                                          Output of Program--

Prpgram for dictionary

Dictionary Menu
1.insert
2.display
3.Modify
4.Search
5.Delete
6.sort
Enter your choice
1

Enter the keyword : bird

Enter the meaning : bird
Want to Enter more ??
y
Prpgram for dictionary

Dictionary Menu
1.insert
2.display
3.Modify
4.Search
5.Delete
6.sort
Enter your choice
1

Enter the keyword : cat

Enter the meaning : animal
Want to Enter more ??
y
Prpgram for dictionary

Dictionary Menu
1.insert
2.display
3.Modify
4.Search
5.Delete
6.sort
Enter your choice
1

Enter the keyword : dog

Enter the meaning : animal
Want to Enter more ??
y
Prpgram for dictionary

Dictionary Menu
1.insert
2.display
3.Modify
4.Search
5.Delete
6.sort
Enter your choice
1

Enter the keyword : ant

Enter the meaning : ant
Want to Enter more ??
y
Prpgram for dictionary

Dictionary Menu
1.insert
2.display
3.Modify
4.Search
5.Delete
6.sort
Enter your choice
2
bird        bird
cat        animal
dog        animal
ant        ant
Want to Enter more ??
y
Prpgram for dictionary

Dictionary Menu
1.insert
2.display
3.Modify
4.Search
5.Delete
6.sort
Enter your choice
6
ant        ant
bird        bird
cat        animal
dog        animal
Want to Enter more ??
y
Prpgram for dictionary

Dictionary Menu
1.insert
2.display
3.Modify
4.Search
5.Delete
6.sort
Enter your choice
3

Enter the keyword for the entry to be modifiedant
Enter the new keyword :
ant
Enter the new meaning :
animal

The entry is modified !!
Want to Enter more ??
y
Prpgram for dictionary

Dictionary Menu
1.insert
2.display
3.Modify
4.Search
5.Delete
6.sort
Enter your choice
4

Enter the keyword to be searchedcat

Meaning : animal
Totle comparisons are 3
Want to Enter more ??
n

Thursday, 22 August 2013

Binary Tree Traversal

from collections import deque

class Node:
    left , right, data = None, None, 0
 
    def __init__(self, data):
        # initializes the data members
        self.left = None
        self.right = None
        self.data = data

class BTree:
    def __init__(self):
        # initializes the root member
        self.root = None
 
    def addNode(self, data):
        # creates a new node and returns it
        return Node(data)

    def insert(self, root, data):
        # inserts a new data
        if root == None:
            # it there isn't any data
            # adds it and returns
            return self.addNode(data)
        else:
            # enters into the tree
            if data <= root.data:
                # if the data is less than the stored one
                # goes into the left-sub-tree
                root.left = self.insert(root.left, data)
            else:
                # processes the right-sub-tree
                root.right = self.insert(root.right, data)
            return root
     
    def pre_order_traversal(self, root, result=[]):
        if root == None:
            pass
        else:
            result.append(root.data)
            self.pre_order_traversal(root.left, result)
            self.pre_order_traversal(root.right, result)
        return result
 
    def in_order_traversal(self, root, result=[]):
        if root == None:
            pass
        else:
            self.in_order_traversal(root.left, result)
            result.append(root.data)
            self.in_order_traversal(root.right, result)
        return result

    def post_order_traversal(self, root, result=[]):
        if root == None:
            pass
        else:
            self.post_order_traversal(root.left, result)
            self.post_order_traversal(root.right, result)
            result.append(root.data)
        return result
 
    # breadth first traversal
    def bfs_traversal(self, root):
        if root == None:       # empty tree
            return

        # keep a queue which will hold all the nodes
        q = deque([root])

        while len(q) != 0:     # keep going until queue is empty
            node = q.popleft()
            if node == None:
                break
         
            print node.data
            if node.left != None:
                q.append(node.left)
            if node.right != None:
                q.append(node.right)

if __name__ == "__main__":
    # create the binary tree
    BTree = BTree()
    # add the root node
    root = BTree.addNode(0)
 
    # ask the user to insert values
    for i in range(0, 3):
        data = int(raw_input("insert the node value for node %d: " % i))
        # insert values
        BTree.insert(root, data)
 
    result = BTree.in_order_traversal(root, result=[])
    print "Inorder Traversal  "
    print ", ".join(map(str, result))
 
    result = BTree.pre_order_traversal(root, result=[])
    print "Preorder Traversal "
    print ", ".join(map(str, result))
 
    result = BTree.post_order_traversal(root, result=[])
    print "PostOrder Traversal "
    print ", ".join(map(str, result))
 
    print "BFS Traversal "



    BTree.bfs_traversal(root)