Sie sind auf Seite 1von 77

Algorithm Analysis &

Design
Lab File

By:-
Atishay Jain
10783017
3T5
Table of Contents

Q1. Implement all operations of an array, including creation, deletion, insertion and deletion.. .4
Q2. Implement all operations of link list including creation, deletion, insertion and updating.....9
Q3. Implement all operations on stack including Push, Pop and Size.........................................15
Q4. Implement all operations in a queue including enqueue, dequeue, front, rear and size.... .17
Q5 Implementation of a binary search tree.............................................................................. ..20
Q6. Implementation of Linear Search..................................................................................... ....26
Q7.Implementation of Binary Search.........................................................................................27
Q8. Implementation of Bubble Sort.................................................................................. ..........28
Q9. Implementation of selection sort.........................................................................................29
Q10. Implementation of Insertion Sort.......................................................................................31
Q11. Implementation of Quick Sort................................................................................ ............32
Q12. Implementation of Radix Sort............................................................................................34
Q13. Counting Sort.................................................................................................................... .35
Q14. Josephus Problem................................................................................... ...........................37
Q15. Count the number of 1s............................................................................................. ........38
Q16. Missing Number...................................................................................................... ...........40
Q17. Evil king............................................................................................................... ..............41
Q18. Railroad car problem.........................................................................................................42
Q19. Parking Combination Problem...................................................................................... ......43
Q20. Magic Square........................................................................................................ .............45
Q21. Strassen Matrix Multiplication........................................................................................... .46
Q22. Integer Multiplication................................................................................................ .........51
Q23. Optimal Merge Pattern................................................................................................... ....52
Q24 Huffman Compression............................................................................... .........................54
Q25 n Queens Problem................................................................................ ..............................56
Q26 Knight Tour Problem......................................................................................................... ...58
Q27 Implement the depth first search.......................................................................................62
Q28 Implement Breadth First Search.........................................................................................64
Q29 Prim’s Algorithm............................................................................................. ....................65
Q30. Kruskal’s Algorithm......................................................................................................... ...67
Q31. Matrix Chain Multiplication................................................................................................69

2
Q32. 0/1 Knapsack Problem .............................................................................. ........................70
Q33. Anagram Problem............................................................................................. .................72
Q34 Substring Problem.................................................................................. ............................73
Q35. Travelling Salesman Problem............................................................................... ..............74

3
Q1. Implement all operations of an array, including creation, deletion,
insertion and deletion.

//////////////////////////////////////////////////////////////////////
//
//Name: Array: Insert, Delete & Update
//Author: Atishay Jain
//Date: 07-1-09
//Lang.: VC++
//Lab. : Assignment 1
//Question: 1
//
/////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include<conio.h>
#include<cstdio>
#include<cstdlib>
#include<iostream>
using namespace std;
#define MAX 100
//Insertion Module
void insert(int *a,int &no)
{
//Bound check
if(no>=MAX) {cout<<"\nOut of bounds"; return;}
//Insertion submenu
char ch;

cout<<endl<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome to
Insertion Module\n"<<"-----------------------------------------------------------------------------"<<endl;
cout<<"Press 1 to insert at start"<<endl<<"Press 2 to insert at index"<<endl<<"Press 3
to insert at the end"<<endl<<"Enter Choice:";
ch=getche();
cout<<endl;
switch(ch)
{
//insert at start
case '1':
//Displacing other elements
for(int i=no;i>0;i--)
{
a[i]=a[i-1];
}
no++;
//Insertion
cout<<"Enter Element:";
cin>>a[0];
break;
//insert at index
4
case '2':
int p;
cout<<"Enter Position:";
cin>>p;
//Checking Possibility at position
if(p<0 || p>no) {cout<<"Not Possible"; return;}
//Displacing other elements
for(int i=no;i>p;i--)
{
a[i]=a[i-1];
}
//Insertion
no++;
cout<<"Enter Element:";
cin>>a[p];
break;
//insert at the end
case '3':
cout<<"Enter Element:";
cin>>a[no];
no++;
break;
//Wrong choice entered
default:
cout<<"Wrong Choice";
return;
}
cout<<"Successfully Inserted";

}
//Deletion Module
void deleteE(int *a,int &no)
{
//Bound Check
if(no==0) {cout<<"\nUnder bounds"; return;}
//Deletion Submenu
char ch;

cout<<endl<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome to
Deletion Module\n"<<"-----------------------------------------------------------------------------"<<endl;
cout<<"Press 1 to delete at start"<<endl<<"Press 2 to delete at index"<<endl<<"Press
3 to delete at the end"<<endl<<"Enter Choice:";
ch=getche();
cout<<endl;
switch(ch)
{
//delete at start
case '1':
for(int i=0;i<no;i++)
{
a[i]=a[i+1];
}
5
no--;
break;
//delete at index
case '2':
int p;
cout<<"Enter Position:";
cin>>p;
//Checking Possibility
if(p<0 || p>no-1) {cout<<"Not Possible"; return;}
//Displacing other elements
for(int i=p;i<no;i++)
{
a[i]=a[i+1];
}
no--;
break;
//delete at the end
case '3':
no--;
break;
//Wrong choice entered
default:
cout<<"Wrong Choice";
return;
}
cout<<"Successfully Deleted";

}
//Updation Module
void update(int *a,int &no)
{
//Bound Check
if(no==0) {cout<<"\nUnder bounds"; return;}
char ch;
//Updation Module Display

cout<<endl<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome to
Updation Module\n"<<"-----------------------------------------------------------------------------"<<endl;
int p;
//Position enquiry
cout<<"Enter Position:";
cin>>p;
//Checking Possibility
if(p<0 || p>no-1) {cout<<"Not Possible"; return;}
//Updation
cout<<"Enter new element:";
cin>>a[p];
cout<<"Sucessfully Updated";
}

//Access Module
int access(int *a,int &no, int index)
6
{

cout<<endl<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome to
Access Module\n"<<"-----------------------------------------------------------------------------"<<endl;

if(index<0 || index>no-1) {cout<<"Not Possible"; return -1;}


return a[index];
}

//Copy Module
void copy(int *a,int *a2,int &no)
{

cout<<endl<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome to
Copy Module\n"<<"-----------------------------------------------------------------------------"<<endl;
cout<<"The elements of array 2 are: ";
//Copy and display element by element...
for(int count=0;count<no;count++)
{
a2[count]=a[count];
cout<<a2[count]<<",";
}
cout<<"\nCopy Successful";
}
//Double Module
void doubleElement(int *a,int &no)
{

cout<<endl<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome to
Doubling Module\n"<<"-----------------------------------------------------------------------------"<<endl;
//Double element by element...
for(int count=0;count<no;count++)
{
//Bound check
if(a[count]>0 && 2*a[count]<a[count]) printf("Skipping %d as it exceeds
bounds",a[count]);
else if(a[count]<0 && 2*a[count]>a[count]) printf("Skipping %d as it exceeds
bounds",a[count]);
else
a[count]=2*a[count];
}
cout<<"\nDouble Successful";
}
int _tmain(int argc, _TCHAR* argv[])
{
//Creation of the Array
int array1[MAX],no=0;
char c='a';
//do..while for main menu
do{
//Main Menu Display
system ("CLS");
cout<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome to
Array Program\n"<<"-----------------------------------------------------------------------------";
7
//Display Module
cout<<endl<<"The Array is A["<<no<<"]={";
for(int i=0;i<no;i++)
{
cout<<array1[i];
if(i!=no-1) cout<<",";
}
cout<<"}"<<endl;
cout<<"Press 1 for insert"<<endl<<"Press 2 to delete"<<endl<<"Press 3 to
update"<<endl<<"Press 4 to access"<<endl<<"Press 5 to copy"<<endl<<"Press 6 to
double"<<endl<<"Press 7 to exit"<<endl<<"Enter choice:";
c=getche();
switch(c)
{
//Insertion Selected
case '1':
insert(array1,no);
getch();
break;
//Deletion Selected
case '2':
deleteE(array1,no);
getch();
break;
//Updation Selected
case '3':
update(array1,no);
getch();
break;
//Access Selected
case '4':
int index;
//Get element details:
printf("\nEnter element index:");
cin>>index;
cout<<"The element is: "<<access(array1,no,index);
getch();
break;
//Copy Selected
case '5':
int array2[MAX];
copy(array1,array2,no);
getch();
break;
//Double Selected - Assumin means doubling each element of the array
case '6':
doubleElement(array1,no);
getch();
break;
//Exit Selected
case '7':break;
//Incorrect Choice
default:
cout<<"\nWrong Choice";
8
getch();
}
}while(c!='7');
//End do..while to check for exit condion.
return 0;
}

Q2. Implement all operations of link list including creation, deletion,


insertion and updating
//////////////////////////////////////////////////////////////////////
//
//Name: Linear Link List: Insert, Delete & Update
//Author: Atishay Jain
//Date: 14-1-09
//Lang.: VC++
//Lab. : Assignment 2
//
/////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include<conio.h>
#include<cstdio>
#include<cstdlib>
#include<iostream>
using namespace std;
// Define an integer link list which is non circular and single directional
struct Linklist
{
int element;
struct Linklist* next;
} *root=0;

//Insertion Module
void insert(int &no)
{
//Insertion submenu
char ch;

cout<<endl<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome to
Insertion Module\n"<<"-----------------------------------------------------------------------------"<<endl;
cout<<"Press 1 to insert at start"<<endl<<"Press 2 to insert at index"<<endl<<"Press 3
to insert at the end"<<endl<<"Enter Choice:";
ch=getche();
cout<<endl;
//Creation of the link list
struct Linklist* newElement=(struct Linklist*) malloc(sizeof(struct Linklist));
//checking case that out of memory
if(newElement==0) { cout<<"Out of memory"; getch(); return;}
switch(ch)
{
//insert at start

9
case '1':
//Create New element
newElement->next=root;
root=newElement;
no++;
//Insertion
cout<<"Enter Element:";
cin>>(newElement->element);
break;
//insert at index
case '2':
int p;
cout<<"Enter Position:";
cin>>p;
//Checking Possibility at position
if(p<0 || p>no) {cout<<"Not Possible"; free(newElement); return;}
//Navigation to the element and assigning value
struct Linklist *currentpos;
currentpos=root;
for(int counter=0;counter<p-1;counter++)
{
currentpos=currentpos->next;
}
//Insertion
no++;
cout<<"Enter Element:";
cin>>newElement->element;
// Assigning appropriate position
newElement->next=currentpos->next;
currentpos->next=newElement;
break;
//insert at the end
case '3':
//Special case if root=0
if(root==0)
{
root=newElement;
root->next=0;
//Insertion
no++;
cout<<"Enter Element:";
cin>>newElement->element;
break;
}

//Navigation to the element and assigning value


struct Linklist *current;
current=root;
for(int counter=0;counter<no-1;counter++)
{
current=current->next;
}
//Insertion
no++;
10
cout<<"Enter Element:";
cin>>newElement->element;
// Assigning appropriate position
newElement->next=current->next;
current->next=newElement;
break;

//Wrong choice entered


default:
cout<<"Wrong Choice";
free(newElement);
return;
}
cout<<"Successfully Inserted";

//Deletion Module
void deleteE(int &no)
{
//Bound Check
if(no==0 || root==0) {cout<<"\nUnder bounds"; return;}
//Deletion Submenu
char ch;

cout<<endl<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome to
Deletion Module\n"<<"-----------------------------------------------------------------------------"<<endl;
cout<<"Press 1 to delete at start"<<endl<<"Press 2 to delete at index"<<endl<<"Press
3 to delete at the end"<<endl<<"Enter Choice:";
ch=getche();
cout<<endl;
struct Linklist *ptr=root,*toDelete;
switch(ch)
{
//delete at start
case '1':
//Move root;
root=root->next;
free(ptr);
no--;
break;
//delete at index
case '2':
//Asking Position
int p;
cout<<"Enter Position:";
cin>>p;
//Checking Possibility
if(p<0 || p>no-1) {cout<<"Not Possible"; return;}
//Special case when deleting at start
if(p==0)
11
{
root=root->next;
free(ptr);
no--;
break;
}
//Navigating to element before it
for(int i=0;i<p-1;i++)
{
ptr=ptr->next;
}
toDelete=ptr->next;
//Deleting
ptr->next=toDelete->next;
free(toDelete);
no--;
break;
//delete at the end
case '3':
//Special case when deleting at start
if(no==1)
{
root=root->next;
free(ptr);
no--;
break;
}
//Navigating to element before it
ptr=root;
for(int i=0;i<no-2;i++)
{
ptr=ptr->next;
}
toDelete=ptr->next;
//Deleting
ptr->next=toDelete->next;
free(toDelete);
no--;
break;
//Wrong choice entered
default:
cout<<"Wrong Choice";
return;
}
cout<<"Successfully Deleted";

}
//Updation Module
void update(int &no)
{
//Bound Check
if(no==0) {cout<<"\nUnder bounds"; return;}
12
char ch;
//Updation Module Display

cout<<endl<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome to
Updation Module\n"<<"-----------------------------------------------------------------------------"<<endl;
int p;
//Position enquiry
cout<<"Enter Position:";
cin>>p;
//Checking Possibility
if(p<0 || p>no-1) {cout<<"Not Possible"; return;}
//Navigating to element
struct Linklist *ptr=root;
for(int count=0;count<p;count++)
{
ptr=ptr->next;
//cout<<count;
}
//Updation
cout<<"Enter new element:";
cin>>(ptr->element);
cout<<"Sucessfully Updated";
}

//Access Module
int access(int &no, int p)
{
if(p<0 || p>no-1) {cout<<"Not Possible"; return -1;}
//Navigating to element
struct Linklist *ptr=root;
for(int count=0;count<p;count++)
{
ptr=ptr->next;
//cout<<count;
}
return ptr->element;
}

int _tmain(int argc, _TCHAR* argv[])


{
//Insert, Delete, Update in a Link List.
int no=0;
struct Linklist *ptr;
char c='a';
//do..while for main menu
do{
//Main Menu Display
system ("CLS");
cout<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome to
Link List Program\n"<<"-----------------------------------------------------------------------------";
//Display Module
cout<<endl<<"The Link List elements are List["<<no<<"]=";
ptr=root;
for(int i=0;i<no;i++)
13
{
cout<<ptr->element;
if(i!=no-1) cout<<"->";
ptr=ptr->next;
}
cout<<endl;
cout<<"Press 1 for insert"<<endl<<"Press 2 to delete"<<endl<<"Press 3 to
update"<<endl<<"Press 4 to access"<<endl<<"Press 5 to get size"<<endl<<"Press 6 to
exit"<<endl<<"Enter choice:";
c=getche();
switch(c)
{
//Insertion Selected
case '1':
insert(no);
getch();
break;
//Deletion Selected
case '2':
deleteE(no);
getch();
break;
//Updation Selected
case '3':
update(no);
getch();
break;
//Access Selected
case '4':
//Getting Element
int index;
cout<<"\nEnter element to access: ";
cin>>index;
cout<<"Element is: "<<access(no,index);
getch();
break;
//Get Size Selected
case '5':
cout<<"\nSize is :"<<no;
getch();
break;
//Exit Selected
case '6':
ptr=root;
struct Linklist *pptr;
//Iternating to each element and releasing assigned memory
for(int count=0;count<no;count++)
{
pptr=ptr;
ptr=ptr->next;
free(pptr);
}
break;
//Incorrect Choice
14
default:
cout<<"\nWrong Choice";
getch();
}
}while(c!='6');
//End do..while to check for exit condition.
return 0;
}

Q3. Implement all operations on stack including Push, Pop and Size.
//////////////////////////////////////////////////////////////////////
//
//Name: Stack: Push, Pop, Size, Top
//Author: Atishay Jain
//Date: 21-1-09
//Lang.: VC++
//Lab. : Assignment 3
//
/////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include<conio.h>
#include<cstdio>
#include<cstdlib>
#include<iostream>
using namespace std;
// Define an integer link list which is non circular and single directional
struct Linklist
{
int element;
struct Linklist* next;
} *root=0;

//Push Module
void push(int &no, int x)
{
//Creation of the Stack Element
struct Linklist* newElement=(struct Linklist*) malloc(sizeof(struct Linklist));
//checking case that out of memory
if(newElement==0) { cout<<"Out of memory"; getch(); return;}
//Create New element
newElement->next=root;
root=newElement;
no++;
newElement->element=x;
}
//Pop Module
int pop(int &no)
{
//Bound Check
if(no==0 || root==0) {cout<<"\nUnder bounds"; return -1;}
//Move root;
struct Linklist *ptr=root;
15
int element=ptr->element;
root=root->next;
free(ptr);
no--;
return element;
}
//Pop Module
int top(int &no)
{
//Bound Check
if(no==0 || root==0) {cout<<"\nUnder bounds"; return -1;}
//Move root;
return root->element;
}
int _tmain(int argc, _TCHAR* argv[])
{
//Push, Pop, Size, Top in a Stack.
int no=0;
struct Linklist *ptr;
char c='a';
//do..while for main menu
do{
//Main Menu Display
system ("CLS");
cout<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome to
Stack\n"<<"-----------------------------------------------------------------------------";
//Display Module
cout<<endl<<"The Stack elements are Stack["<<no<<"]=";
ptr=root;
for(int i=0;i<no;i++)
{
cout<<ptr->element;
if(i!=no-1) cout<<"/";
ptr=ptr->next;
}
cout<<endl;
cout<<"Press 1 for Push"<<endl<<"Press 2 to Pop"<<endl<<"Press 3 to
Top"<<endl<<"Press 4 to Size"<<endl<<"Press 5 to exit"<<endl<<"Enter choice:";
c=getche();
switch(c)
{
//Push Selected
case '1':
int element;
cout<<"\nEnter Element:";
cin>>element;
push(no,element);
break;
//Pop Selected
case '2':
cout<<"\nElement is :"<<pop(no);
getch();
break;
//Top Selected
16
case '3':
cout<<"\nElement is :"<<top(no);
getch();
break;
//Size Selected
case '4':
//Displaying Size
cout<<"\nSize is: "<<no;
getch();
break;
//Exit Selected
case '5':
ptr=root;
struct Linklist *pptr;
//Iternating to each element and releasing assigned memory
for(int count=0;count<no;count++)
{
pptr=ptr;
ptr=ptr->next;
free(pptr);
}
break;
//Incorrect Choice
default:
cout<<"\nWrong Choice";
getch();
}
}while(c!='5');
//End do..while to check for exit condition.
return 0;
}

Q4. Implement all operations in a queue including enqueue, dequeue,


front, rear and size.
//////////////////////////////////////////////////////////////////////
//
//Name: Queue: Enqueue, Dequeue, GetSize, Get Front Get Rear
//Author: Atishay Jain
//Date: 21-1-09
//Lang.: VC++
//Lab. : Assignment 4
//
/////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include<conio.h>
#include<cstdio>
#include<cstdlib>

17
#include<iostream>
using namespace std;

// Node for Linked list implementation


struct node
{
int data;
node *next;
}*front=NULL,*rear=NULL;

// Front and Rear pointers to define Front and Rear.

//Enqueue Module
void enqueue(int element)
{
//Creation of the Queue Element
struct node* newElement=(struct node*) malloc(sizeof(struct node));
newElement->data=element;
newElement->next=NULL;
// Case when both sides 0
if(front==NULL && rear==NULL)
front=rear=newElement;
else if(rear ==NULL)
{ struct node *ptr=front;
// Assigning Previous element
while(ptr->next!=NULL)
{
ptr=ptr->next;
}
ptr->next=newElement;
rear=newElement;
}
else
{
rear->next=newElement;
rear=newElement;
}

}
//Dequeue Module
void dequeue()
{
struct node *toDelete;
if(front==NULL)
cout<<endl<<"Underflow.";
else
{
// Dequeuing the front Element
toDelete=front;
front=front->next;
cout<<endl<<"The Deleted element is : "<<toDelete->data;
free(toDelete);
}
}
18
//Get Size Module
int getSize()
{
node *temp;
temp=front;
int count=0;
while(temp!=NULL)
{
count++;
temp=temp->next;
}
return count;
}

//Get Front Module


int getFront()
{
if(front==NULL)
{
cout<<"\nThe queue is empty";
return -1;
}
else
return front->data;
}

//Get Rear Module


int getRear()
{
if(rear==NULL)
{
cout<<endl<<"The queue is empty";
return -1;
}
else
return rear->data;

int _tmain(int argc, _TCHAR* argv[])


{
//Queue: Enqueue, Dequeue, GetSize, Get Front Get Rear
int choice;
int num;
// Display Module
// Main Menu
do
{
system ("CLS");
cout<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome to
Queue\n"<<"-----------------------------------------------------------------------------";
cout<<endl"Press 1 to Enqueue an element ";
cout<<endl<<"Press 2 to Dequeue an element";
19
cout<<endl<<"Press 3 to Display Size";
cout<<endl<<"Press 4 to Display front of queue";
cout<<endl<<"Press 5 to Display end of queue";
cout<<endl<<"Press 6 to Exit";

cout<<endl<<"Enter your choice : ";


choice=getche();
switch(choice)
{
// Enqueue Selected
case '1' :
cout<<endl<<"Enter the element ot be inserted : ";
cin>>num;
enqueue(num);
break;
// Dequeue Selected

case '2' :
dequeue();
break;
// Get Size Selected

case '3' :
cout<<endl<<"Size of the queue is : "<<getSize();
break;
// Get Front Selected

case '4' :
cout<<"The Front Element is: "<< getFront();
break;
// Get Rear Selected

case '5' :
cout<<"The rear of queue is : "<<getRear();
break;
// Exit Selected

case '6' :
break;
default : cout<<"\nWrong Choice";
}
}while(choice !=6);
//End do..while to check for exit condition.
return 0;
}

Q5 Implementation of a binary search tree.


//////////////////////////////////////////////////////////////////////
//
//Name: Binary Search Tree: Insertion, Traversal(Inorder, preorder, postorder),
// height, no of nodes, no of leaves, search etc.
20
//Author: Atishay Jain
//Date: 28-1-09
//Lang.: VC++
//Lab. : Assignment 5
//
/////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include<conio.h>
#include<cstdio>
#include<cstdlib>
#include<iostream>
using namespace std;

// Node for BST implementation


struct node
{
int value;
node *left;
node *right;
} *tree=NULL,*ptr1,*ptr2,*temp;
// Left and Right pointers to define left and right child.

// Function for insert in binary tree


void insert(int element)
{
temp=new node;
temp->value=element;
temp->left=NULL;
temp->right=NULL;
//Special Case: The first element
if(tree==NULL)
{
tree=temp;
}
else
{

ptr1=tree;
while(ptr1!=NULL)
{
//Traverse left if smaller else traverse right
if((ptr1->value) > element)
{
if(ptr1->left !=NULL)
ptr1=ptr1->left;
else
{
ptr1->left=temp;
break;
}
}
else
{
21
if(ptr1->right !=NULL)
ptr1=ptr1->right;
else
{
ptr1->right=temp;
break;
}
}
}

}
cout<<"Successfully Inserted";
getch();
}

// Pre-order traversal

void preOrderTraversal(node * tree)


{
if(tree!=NULL)
{
cout<<tree->value<<"->";
preOrderTraversal(tree->left);
preOrderTraversal(tree->right);
}
}

// In-order traversal
void inOrderTraversal(node * tree)
{
if(tree!=NULL)
{
inOrderTraversal(tree->left);
cout<<tree->value<<"->";
inOrderTraversal(tree->right);
}
}
// Post-Order traversal
void postOrderTraversal(node * tree)
{
if(tree!=NULL)
{
postOrderTraversal(tree->left);
postOrderTraversal(tree->right);
cout<<tree->value<<"->";
}
}

//Get the Height of the tree


int getHeight( node *tree)
{
int leftHeight,rightHeight;

if(tree==NULL)
22
return 0;

else
{
//Call for max height left side
leftHeight=getHeight(tree->left);
//Call for max. height right side
rightHeight=getHeight(tree->right);
//See which is greater
if(leftHeight < rightHeight)
{
rightHeight=rightHeight+1;
return rightHeight;
}
else
{
leftHeight=leftHeight+1;
return leftHeight;
}
}
}

//The Number of Nodes in the tree

int getNodes(node *tree)


{
if(tree==NULL)
return 0;

else
return(getNodes(tree->left) +getNodes(tree->right) +1);
}

// Search for an element


node * search(node * tree,int val)
{
if(tree->value ==val || tree==NULL)
return tree;

else if((tree->value) > val)


return( search(tree->left,val));
else
return( search(tree->right,val));
}

int _tmain(int argc, _TCHAR* argv[])


{
int choice,i=0;
// Main Menu
do
{
23
system ("CLS");
cout<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome
to Binary Search Tree\n"<<"-----------------------------------------------------------------------------";
cout<<endl<<"Press 1 to Insert an element ";
cout<<endl<<"Press 2 to do Preorder Traversal";
cout<<endl<<"Press 3 to do Inorder Traversal";
cout<<endl<<"Press 4 to do Postorder Traversal";
cout<<endl<<"Press 5 to get the Height of the tree";
cout<<endl<<"Press 6 to get the Number of Nodes";
cout<<endl<<"Press 7 to Search tree for a value";
cout<<endl<<"Press 8 to Exit";

cout<<endl<<"Enter your choice : ";


choice=getche();
switch(choice)
{
case 1:cout<<"Enter the value to bve inserted:";
cin>>i;
insert(i);
break;
case 2:preOrderTraversal(tree);
getch();
break;
case 3:inOrderTraversal(tree);
getch();
break;
case 4:postOrderTraversal(tree);
getch();
break;
case 5:
cout<<"The Height of the tree is:"<<getHeight(tree);
getch();
break;
case 6:
cout<<"The number of nodes in the tree are:"<<getNodes(tree);
getch();
break;
case 7: cout<<"Enter the element to be searched:";
cin>>i;
if(search(tree,i)==NULL)
cout<<"Element absent from the tree"<<endl;
else cout<<"Element is present in the tree"<<endl;
getch();
break;

case 8:
break;
default: cout<<"\nWrong Choice";
}
}while(choice !=8);
//End do..while to check for exit condition.
return 0;
}
24
25
Q6. Implementation of Linear Search
//////////////////////////////////////////////////////////////////////
//
//Name: Linear Search
//Author: Atishay Jain
//Date: 04-2-09
//Lang.: VC++
//Lab. : Assignment 6
//
/////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include<conio.h>
#include<cstdio>
#include<cstdlib>
#include<iostream>
using namespace std;
#define MAX 100
//Implement Linear Search
int _tmain(int argc, _TCHAR* argv[])
{
int array[MAX];
int size,flag=0,toFind;

system ("CLS");
cout<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome to
Linear Search\n"<<"-----------------------------------------------------------------------------";
do{
cout<<"\nEnter the size of the array : ";
cin>>size;
if(size>MAX) cout<<"\nSize has to be less than 100";
}while(size>MAX);

cout<<"\nEnter the elements in the Array: ";


//Insertion
for(int i=0;i<size;i++)
cin>>array[i];
cout<<"\nEnter the number to be searched : ";
cin>>toFind;
//Scan Linearly till the end of array....
for(int i=0;i<size;i++)
{
if(array[i]==toFind)
{
cout<<"\nPosition: "<<i+1;
//Flag for checking absence - Toggle to present
flag=1;
}
}
//Check absence
if(flag==0)
cout<<"\nNumber absent from the array";

26
return 0;
}

Q7.Implementation of Binary Search

//////////////////////////////////////////////////////////////////////
//
//Name: Binary Search
//Author: Atishay Jain
//Date: 04-2-09
//Lang.: VC++
//Lab. : Assignment 7
//
/////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include<conio.h>
#include<cstdio>
#include<cstdlib>
#include<iostream>
using namespace std;
#define MAX 100

int _tmain(int argc, _TCHAR* argv[])


{
int array[MAX];
int size;
int toFind;
int flag=0;
int beg,end,mid;
system ("CLS");
cout<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome to
Binary Search\n"<<"-----------------------------------------------------------------------------";
cout<<"\nEnter the size of the array : ";
cin>>size;
do{
cout<<"\nEnter the size of the array : ";
cin>>size;
if(size>MAX) cout<<"\nSize has to be less than 100";
}while(size>MAX);

cout<<"\nEnter the elements in the Array: ";


//Insertion
for(int i=0;i<size;i++)
cin>>array[i];
cout<<"\nEnter the number to be searched : ";
cin>>toFind;

//Initial Config...
beg=0;
end=size-1;
27
mid=(beg+end)/2;
//Loop to run till ranges possible
while(beg<=end)
{
//Checking Present toFind
if(array[mid]==toFind)
{
cout<<endl<<"Number found at position "<<mid+1;
flag=1;
break;
}
//Lower Half
else if(array[mid]<toFind)
beg=mid+1;
else
//Upper Half
end=mid-1;
mid=(beg+end)/2;
}

if(flag==0)
cout<<"\nNumber absent from the array";
return 0;
}

Q8. Implementation of Bubble Sort

//////////////////////////////////////////////////////////////////////
//
//Name: Bubble Sort
//Author: Atishay Jain
//Date: 04-2-09
//Lang.: VC++
//Lab. : Assignment 8
//
/////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include<conio.h>
#include<cstdio>
#include<cstdlib>
#include<iostream>
using namespace std;
#define MAX 100
int array[MAX];

void bubble(int size)


{
// Temporary variable for swapping
28
int temp;
//Loop for bubble sort
for(int i=0;i<size;i++)
{
for(int j=size-1;j>i;j--)
{
if(array[j]<array[j-1])
{
temp=array[j];
array[j]=array[j-1];
array[j-1]=temp;
}
}
}
}

//Implement Bubble sort


int _tmain(int argc, _TCHAR* argv[])
{
int size;
system ("CLS");
cout<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome to
Bubble Sort\n"<<"-----------------------------------------------------------------------------";
do{
cout<<"\nEnter the size of the array : ";
cin>>size;
if(size>MAX) cout<<"\nSize has to be less than 100";
}while(size>MAX);

cout<<"\nEnter the array elements: ";

//Insertion
for(int i=0;i<size;i++)
{
cin>>array[i];
}
bubble(size);
//Display
cout<<endl<<"\nThe Sorted array Contains: {";
for(int i=0;i<size;i++)
{
if( i !=size-1) cout<<array[i]<<",";
else cout<<array[i]<<"}";
}
return 0;
}

Q9. Implementation of selection sort

//////////////////////////////////////////////////////////////////////
//
29
//Name: Selection Sort
//Author: Atishay Jain
//Date: 04-2-09
//Lang.: VC++
//Lab. : Assignment 9
//
/////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include<conio.h>
#include<cstdio>
#include<cstdlib>
#include<iostream>
using namespace std;
#define MAX 100
int array[MAX];

void selectionSort(size)
{
int temp,pos;
for(int i=0;i<size;i++)
{
min=array[i];
pos=i;
for(int j=i+1;j<size;j++)
{
//Select Minimum
if(array[j]<min)
{
min=array[j];
pos=j;
}
}
//Swap
temp=array[i];
array[i]=array[pos];
array[pos]=temp;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int size,min;
system ("CLS");
cout<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome to
Selection Sort\n"<<"-----------------------------------------------------------------------------";
do{
cout<<"\nEnter the size of the array : ";
cin>>size;
if(size>MAX) cout<<"\nSize has to be less than 100";
}while(size>MAX);

cout<<"\nEnter the array elements: ";


//Insertion
for(int i=0;i<size;i++)
30
{
cin>>array[i];
}

selectionSort(size) ;

//Display
cout<<endl<<"\nThe Sorted array Contains: {";
for(int i=0;i<size;i++)
{
if( i !=size-1) cout<<array[i]<<",";
else cout<<array[i]<<"}";
}
return 0;
}

Q10. Implementation of Insertion Sort


//////////////////////////////////////////////////////////////////////
//
//Name: Insertion Sort
//Author: Atishay Jain
//Date: 04-2-09
//Lang.: VC++
//Lab. : Assignment 10
//
/////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include<conio.h>
#include<cstdio>
#include<cstdlib>
#include<iostream>
using namespace std;
#define MAX 100
int array[MAX];

void insertionSort(int size)


{
int j,pos;
for(int i=1;i<size;i++)
{
pos=array[i];
j=i-1;
//Move forward biger elements
while(j>=0 && pos<array[j])
{
array[j+1]=array[j];
j=j-1;
}
//Insert at correct position
array[j+1]=pos;
}
}
31
int _tmain(int argc, _TCHAR* argv[])
{
int size;
system ("CLS");
cout<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome to
Insertion Sort\n"<<"-----------------------------------------------------------------------------";
do{
cout<<"\nEnter the size of the array : ";
cin>>size;
if(size>MAX) cout<<"\nSize has to be less than 100";
}while(size>MAX);

insertionSort(size);

cout<<"\nEnter the array elements: ";


//Insertion
for(int i=0;i<size;i++)
{
cin>>array[i];
}

//Display
cout<<endl<<"\nThe Sorted array Contains: {";
for(int i=0;i<size;i++)
{
if( i !=size-1) cout<<array[i]<<",";
else cout<<array[i]<<"}";
}
return 0;
}

Q11. Implementation of Quick Sort.


//////////////////////////////////////////////////////////////////////
//
//Name: Quick Sort
//Author: Atishay Jain
//Date: 04-2-09
//Lang.: VC++
//Lab. : Assignment 11
//
/////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include<conio.h>
#include<cstdio>
#include<cstdlib>
#include<iostream>
using namespace std;
#define MAX 100
int array[MAX];
32
int partition(int first,int last)
{
int pElement=array[last];
int temp;
int j=first-1;
for(int i=first;i<last;i++)
{
// Move all smaller elements before
if(array[i]<=pElement)
{
j++;
temp=array[i];
array[i]=array[j];
array[j]=temp;
}
}
//Place it after that
array[last]=array[j+1];
array[j+1]=pElement;
return j+1;
}

void quickSort(int first, int last)


{
if(first<last)
{
int pos=partition(first,last);
quicksort(first,pos-1);
quicksort(pos+1,last);
}
}

int _tmain(int argc, _TCHAR* argv[])


{
int size,min;
system ("CLS");
cout<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome to
Quick Sort\n"<<"-----------------------------------------------------------------------------";
do{
cout<<"\nEnter the size of the array : ";
cin>>size;
if(size>MAX) cout<<"\nSize has to be less than 100";
}while(size>MAX);

cout<<"\nEnter the array elements: ";


//Insertion
for(int i=0;i<size;i++)
{
cin>>array[i];
}

33
quickSort(0,size-1);

//Display
cout<<endl<<"\nThe Sorted array Contains: {";
for(int i=0;i<size;i++)
{
if( i !=size-1) cout<<array[i]<<",";
else cout<<array[i]<<"}";
}
return 0;
}

Q12. Implementation of Radix Sort


//////////////////////////////////////////////////////////////////////
//
//Name: Radix Sort
//Author: Atishay Jain
//Date: 11-2-09
//Lang.: VC++
//Lab. : Assignment 12
//
/////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include<conio.h>
#include<cstdio>
#include<cstdlib>
#include<iostream>
using namespace std;
#define MAX 1000
int size;
void sortByDigit(int *A,int mod)
{
int temp,m;
int B[MAX];
int C[10];
int D[10];
for(int i=1;i<=size;i++)
{
temp=A[i];
m=mod;
while(m>=10)
{
temp=temp/10;
m=m/10;
}
B[i]=temp%10;
}
for(int i=0;i<=9;i++)
C[i]=0;
for(int i=1;i<=size;i++)
C[B[i]]=C[B[i]]+1;
34
for(int i=1;i<=9;i++)
C[i]=C[i]+C[i-1];
for(int i=size;i>0;i--)
{
D[C[B[i]]]=A[i];
C[B[i]]=C[B[i]]-1;
}
}
void radixSort(int *A, int digits)
{
int mod=1;
while(mod<pow(10,digits))
{
sortByDigit(A,mod);
mod=mod*10;
}

cout<<endl<<"The sorted array is :";


for(int i=1;i<=size;i++)
{
cout<<A[i];
if(i!-size) cout<<",";
}
}

int _tmain(int argc, _TCHAR* argv[])


{
int A[MAX],digits;
system ("CLS");
cout<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome to
Radix Sort\n"<<"-----------------------------------------------------------------------------";
do{
cout<<endl<<"Enter the number of elements:";
cin>>size;
if(size>MAX) cout<<"\nSize has to be less than 100";
}while(size>MAX);
cout<<endl<<"Enter the maximum number of digits:";
cin>>digits;
cout<<endl<<"Enter the array elements:";
for(int i=1;i<=size;i++)
cin>>A[i];
radixSort(A,digits);
getch();
}

Q13. Counting Sort


//////////////////////////////////////////////////////////////////////
//
//Name: Counting Sort
//Author: Atishay Jain
35
//Date: 11-2-09
//Lang.: VC++
//Lab. : Assignment 13
//
/////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include<conio.h>
#include<cstdio>
#include<cstdlib>
#include<iostream>
using namespace std;
#include<conio.h>
#define MAX 100

int _tmain(int argc, _TCHAR* argv[])


{
int size;
int inputArray[MAX],sortedArray[MAX],countArray[MAX];
int max;
int i;
system ("CLS");
cout<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome to
Counting Sort\n"<<"-----------------------------------------------------------------------------";
cdo{
cout<<"\nEnter the size of the array : ";
cin>>size;
if(size>MAX) cout<<"\nSize has to be less than 100";
}while(size>MAX);
//Input
for(i=0;i<=size;i++)
{
sortedArray[i]=0;
}
cout<<endl<<"Enter the array elements : ";
for(i=1;i<=size;i++)
cin>>inputArray[i];
max=inputArray[1];
//Maximum for counts array
for(i=2;i<=size;i++)
if(inputArray[i]>max)
max=inputArray[i];

//Empty the counts at start.


for(i=0;i<=max;i++)
countArray[i]=0;

//Counting
for(i=1;i<=size;i++)
countArray[inputArray[i]]=countArray[inputArray[i]]+1;

//Adding to perform cumulative count


for(i=1;i<=max;i++)
36
countArray[i]+=countArray[i-1];

// Generating the sorted array


for(i=size;i>0;i--)
{
sortedArray[countArray[inputArray[i]]]=inputArray[i];
countArray[inputArray[i]]-=1;
}

//Display
cout<<endl<<"The sorted array is : ";
for(i=1;i<=size;i++)
{
cout<<sortedArray[i];
if(i!=size) cout<<",";
}
getch();
}

Q14. Josephus Problem


//////////////////////////////////////////////////////////////////////
//
//Name: Josephus Problem
//Author: Atishay Jain
//Date: 11-2-09
//Lang.: VC++
//Lab. : Assignment 14
//
/////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include<conio.h>
#include<cstdio>
#include<cstdlib>
#include<iostream>
using namespace std;

//Create Circular LinkList


struct Circular
{
int number;
Circular *next;
}*start=NULL;

int _tmain(int argc, _TCHAR* argv[])


{
int noOfPeople;
int toKill;
system ("CLS");
cout<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome to
Josephus Problem\n"<<"-----------------------------------------------------------------------------";
37
cout<<"\nEnter the number of persons : ";
cin>>noOfPeople;
cout<<"\nEnter the person number who has to be Killed : ";
cin>>toKill;

struct Circular *temp,*ptr;


temp=(struct Circular *) malloc(sizeof(struct Circular));
temp->number=1;
start=temp;
//Formation of the Josephus List
for(int i=0;i<noOfPeople-1;i++)
{
ptr=(struct Circular *) malloc(sizeof(struct Circular));
ptr->number=i+2;
temp->next=ptr;
temp=ptr;

}
temp->next=start;

//Killing and finding of the winner


temp=start;
cout<<"\nKilled={";
for(int j=0;j<noOfPeople;j++)
{
for(int i=1;i<toKill-1;i++)
{
temp=temp->next;
}
ptr=temp->next;
cout<<ptr->number<<",";
temp->next=ptr->next;
free(ptr);
temp=temp->next;

//If winner found


if(temp->next==temp)
{
cout<<"}\nSurvivor: "<<temp.number;
break;
}
}
return 0;
}

Q15. Count the number of 1s.


//////////////////////////////////////////////////////////////////////
//
//Name: Number of 1s in an array
//Author: Atishay Jain
//Date: 11-02-09
38
//Lang.: VC++
//Lab. : Assignment 15
//
/////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include<conio.h>
#include<cstdio>
#include<cstdlib>
#include<iostream>
using namespace std;
#define MAX 100

int _tmain(int argc, _TCHAR* argv[])


{
int size;
int array[MAX][MAX];
system ("CLS");
cout<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome to
Number of 1s.\n"<<"-----------------------------------------------------------------------------";
do{
cout<<"\nEnter the size of the array : ";
cin>>size;
if(size>MAX) cout<<"\nSize has to be less than 100";
}while(size>MAX);
//Inputting
cout<<"Enter the array elements (only 0 and 1 with the zeroes following 1s in each row.):
";
for(int i=0;i<size;i++)
for(int j=0;j<size;j++)
{
do{
cin>>array[i][j];
}while(array[i][j] !=0 && array[i][j] !=1);
}
int count=0;
int j=0;
//Scanning from last row to Ist one
for(int i = size-1;i>=0;i--)
{
//Scanning till jth element is 0
while(array[i][j] == 1)
{
j++;
}
count+=(j+1);
}

cout<<"The number of 1s in the array is "<<count;


return 0;
}

39
Q16. Missing Number
//////////////////////////////////////////////////////////////////////
//
//Name: Find the missing Number
//Author: Atishay Jain
//Date: 28-1-09
//Lang.: VC++
//Lab. : Assignment 16
//
/////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include<conio.h>
#include<cstdio>
#include<cstdlib>
#include<iostream>
using namespace std;
#define MAX 100

int _tmain(int argc, _TCHAR* argv[])


{
int size;
int array[MAX];

system ("CLS");
cout<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome to
Find the Missing Number\n"<<"-----------------------------------------------------------------------------";
cout<<endl<<"Enter the size of the array : ";
do{
cout<<"\nEnter the size of the array : ";
cin>>size;
if(size>MAX) cout<<"\nSize has to be less than 100";
}while(size>MAX);
cout<<"\nEnter the array elements: ";
//Inputting
for(int i=0;i<size;i++)
cin>>array[i];

//Summing Up
int sum=0;
for(int i=0;i<size;i++)
{
sum+=array[i];

cout<<"\nThe missing number is : ";


//Sum of n elements is n(n-1)/2
cout<<(size*(size+1)/2)-sum;

return 0;
}

40
Q17. Evil king
//////////////////////////////////////////////////////////////////////
//
//Name: Evil King Problem
//Author: Atishay Jain
//Date: 18-2-09
//Lang.: VC++
//Lab. : Assignment 17
//
/////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include<conio.h>
#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<cmath>
using namespace std;
#define MAX 100

// Gwetting the bottle number based on the people dead....


int getBottleNumber(int *dead,int size)
{
int ret=0;
for(int i=0;i<size;i++)
{
ret+=dead[i]*pow(2,i);
}
return ret;
}

//Main module
int _tmain(int argc, _TCHAR* argv[])
{
int noOfWineBottles;
int noOfTesters;
int temp;
int testerStatus[MAX];
system ("CLS");
cout<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome to Evil
King Problem\n"<<"-----------------------------------------------------------------------------";
do{
cout<<"Enter the number of Wine bottles:";
cin>>noOfWineBottles;
noOfTesters=ceil(log2(noOfWineBottles));
if(noOfTesters>MAX) cout<<"\nToo many bottles";
}while(noOfTesters>MAX);

for(int i=0;i<noOfTesters;i++)
testerStatus[i]=0;
cout<<endl<<"The number of taste testers required : "<<noOfTesters;
41
//Display combinations
for(int i=0;i<noOfTesters;i++)
{
cout<<endl<<"Tester No:#"<<i+1<<" drinks from:";
int t=0;
for(int j=0;j<noOfWineBottles;j++)
{
if(t!=0) cout<<j+1<<",";
if(j%(pow(2,i)) ==0) t=1-t;
}
}
cout<<endl<<"Specify the taste testers who have died (Press 0 to finish):";
do
{
cin>>temp;
if(temp>noOfTesters || temp<0)
cout<<endl<<"Invalid Number.";
if(temp!=0)
{
testerStatus[temp-1]=1;
}
}while(temp!=0);
int poisonedBottle=getBottleNumber(testerStatus,noOfTesters)+1;
if(poisonedBottle>noOfWineBottles)
poisonedBottle=noOfWineBottles;
cout<<endl<<"The bottle which contained the poison is:"<<poisonedBottle;
getch();
}

Q18. Railroad car problem


//////////////////////////////////////////////////////////////////////
//
//Name: RailRoad Sequence Problem
//Author: Atishay Jain
//Date: 25-2-09
//Lang.: VC++
//Lab. : Assignment 18
//
/////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include<conio.h>
#include<cstdio>
#include<cstdlib>
#include<iostream>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])


{
42
int
inputSequence[4];
int
stack[4];
int
i;
int
top=-1;
int
temp;
system ("CLS");
cout<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome to
RailRoad Car Problem\n"<<"-----------------------------------------------------------------------------";
//Input
cout<<"Rail Road Sequence Problem"<<endl<<endl;
cout<<"Enter the sequence of the rail road cars : ";
for(i=0;i<4;i++)
cin>>inputSequence[i];

//Checking Possibility
int flag=1,ptr=0;
//Ptr is the pushed pointer(Deferred push)
for(i=0;i<4;i++)
{
while(ptr<=inputSequence[i])
{
stack[++top]=ptr;
ptr=ptr+1;
}
if(stack[top--]!=inputSequence[i])
flag=0;
}
if(flag==1)
cout<<"The given combination is possible";
else
cout<<"The permutation is not possible";
getch();
return 0;
}

Q19. Parking Combination Problem


//////////////////////////////////////////////////////////////////////
//
//Name: Find the missing Number
//Author: Atishay Jain
//Date: 10-3-09
//Lang.: VC++
//Lab. : Assignment 19
//
/////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include<conio.h>
#include<cstdio>
#include<cstdlib>
#include<iostream>
43
using namespace std;
#define MAX 100

int getLocation(int currentLocation, int size, int *parkingLot)


{
for(int i=currentLocation;i<size;i++)
if(parkingLot[i]==0)
return i;
return -1;
}

int _tmain(int argc, _TCHAR* argv[])


{
int cars[MAX];
int parkingLot[MAX];
int noOfParkingSpaces;
int noOfCars;
int i;
int loc;
system ("CLS");
cout<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome to
Parking Problem\n"<<"-----------------------------------------------------------------------------";
do{
cout<<"\nEnter the number of parking spaces:";
cin>>noOfParkingSpaces;
if(noOfParkingSpaces>MAX) cout<<"\nNo of Parking Spaces have to be less than
100";
}while(noOfParkingSpaces>MAX);

do{
cout<<"\nEnter the number of cars:";
cin>>noOfCars;
if(noOfCars>MAX) cout<<"\nNo of cars have to be less than 100";
}while(noOfCars>MAX);
cout<<endl<<"Enter the wife waking sequence:";
for(i=0;i<noOfCars;i++)
cin>>cars[i];

//Initializing the Parking Lot as empty


for(i=0;i<noOfParkingSpaces;i++)
parkingLot[i]=0;

//Checking Possibility
for(i=0;i<noOfCars;i++)
{
if(parkingLot[cars[i]-1]==0)
parkingLot[cars[i]-1]=i+1;
else
{
loc=getLocation(cars[i]-1,noOfParkingSpaces,parkingLot);
if(loc==-1)
{
cout<<endl<<"Safe Parking not possible.";
44
getch();
exit(0);
}
parkingLot[loc]=i+1;
}
}

//Display combination
cout<<endl<<"The Parking Sequence is given by:";
for(i=0;i<noOfParkingSpaces;i++)
{
cout<<parkingLot[i];
if(i!=noOfParkingSpaces-1) cout<<",";
}

getch();
}

Q20. Magic Square


//////////////////////////////////////////////////////////////////////
//
//Name: Creation of magic square
//Author: Atishay Jain
//Date: 25-2-09
//Lang.: VC++
//Lab. : Assignment 20
//
/////////////////////////////////////////////////////////////////////

//headers
#include "stdafx.h"
#include<conio.h>
#include<cstdio>
#include<cstdlib>
#include<iostream>
using namespace std;
#define MAX 200
int a[MAX][MAX]={};

///////////////////////////////////////////////////////////////////
//Magic Square Construction Module
///////////////////////////////////////////////////////////////////

int magicSquare(int n)
{
if(n%2==0 || n>MAX) return -1;
//Initialize to zero
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
a[i][j]=0;
45
//starting Position for 1
int posX=n/2;
int posY=0;
for(int i=1;i<=n*n;i++)
{
a[posX][posY]=i;
//Move top right
posX++;
posY--;
//Making the array circular
if(posX==n) posX=0;
if(posY<0) posY+=n;
//If filled go back to lower position
if(a[posX][posY] !=0)
{
posX-=1;
posY+=2;
if(posX==-1) posX=n-1;
if(posX==-2) posX=n-2;
if(posY>=n) posY=posY-n;
}
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
//Define array
int n;
//Ask Size
system ("CLS");
cout<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome to
Magic Square\n"<<"-----------------------------------------------------------------------------";

do{
cout<<"Enter n:";
cin>>n;
if(magicSquare(n)==-1) cout<<"Error, Odd Value <"<<MAX<<" has to be given";
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
printf("%3d",a[j][i])
;
cout<<endl;
}
cout<<"\nPress e to exit: ";
}while(getche() !='e');
return 0;
}

Q21. Strassen Matrix Multiplication


//////////////////////////////////////////////////////////////////////
//
46
//Name: strassen Multiplication
//Author: Atishay Jain
//Date: 23-3-09
//Lang.: VC++
//Lab. : Assignment 21
//
/////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include<conio.h>
#include<cstdio>
#include<cstdlib>
#include<iostream>
using namespace std;
#define MAX 100

//Adds two matrices x&y and saves the result in z, the size of which is nxn
void add(int x[MAX][MAX],int y[MAX][MAX], int z[MAX][MAX],int n)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
z[i][j]=x[i][j]+y[i][j];
}
}
}

//Subtracts two matrices y from x and saves the result in z, the size of which is nxn
void subtract(int x[MAX][MAX],int y[MAX][MAX], int z[MAX][MAX],int n)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
z[i][j]=x[i][j]-y[i][j];
}
}
}

//Splits matrix p from starti to strati+n in x and startj to startj+x in y and saves to c
void splitarray(int p[MAX][MAX],int c[MAX][MAX],int starti,int startj,int n)
{
for(int i=starti,ic=0;ic<n/2;i++,ic++)
{
for(int j=startj,jc=0;jc<n/2;j++,jc++)
{
c[ic][jc]=p[i][j];
}
}
}

47
//Jois a nxn matrix p to a matrix c with starting x starti and starting y startj
void joinarray(int p[MAX][MAX],int c[MAX][MAX],int starti,int startj,int n)
{
for(int i=starti,ic=0;ic<n;i++,ic++)
{
for(int j=startj,jc=0;jc<n;j++,jc++)
{
p[i][j]=c[ic][jc];
}
}
}

//displays a nxn matrix nxn a


void display(int a[MAX][MAX],int n)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cout<<a[i][j]<<" ";
}
cout<<endl;
}
}

//Multiplies using strassen algorithm matrices a&b and stores the result in c all of which are nxn
matrices
void strassan_mult(int a[MAX][MAX],int b[MAX][MAX], int c[MAX][MAX],int n)
{
//If 1x1 matrices
if(n==1)
{

c[0][0]=a[0][0]*b[0][0];
return;// c;
}
else
{
//Making matrix even
int x;
if(n%2==0)
x=n;
else
x=n+1;
//Declare submatrices
int a11[MAX][MAX];
int a12[MAX][MAX];
int a21[MAX][MAX];
int a22[MAX][MAX];
int b11[MAX][MAX];
int b12[MAX][MAX];
48
int b21[MAX][MAX];
int b22[MAX][MAX];
int c11[MAX][MAX];
int c12[MAX][MAX];
int c21[MAX][MAX];
int c22[MAX][MAX];
int temp1[MAX][MAX];
int temp2[MAX][MAX];

//Create proper submatrices


splitarray(a,a11,0,0,x/2);
splitarray(a,a12,0,x/2,x/2);
splitarray(a,a21,x/2,0,x/2);
splitarray(a,a22,x/2,x/2,x);
splitarray(b,b11,0,0,x/2);
splitarray(b,b12,0,x/2,x/2);
splitarray(b,b21,x/2,0,x/2);
splitarray(b,b22,x/2,x/2,x/2);

//Find P1
add(a11,a22,temp1,x/2);
add(b11,b22,temp2,x/2);
int p[MAX][MAX];
strassan_mult(temp1,temp2,p,x/2);

//Find P2
add(a21,a22,temp1,x/2);
int q[MAX][MAX];
strassan_mult(temp1,b11,q,x/2);

//Find P3
int r[MAX][MAX];
subtract(b12,b22,temp1,x/2);
strassan_mult(a11,temp1,r,x/2);

//Find P4
int s[MAX][MAX];
subtract(b21,b11,temp1,x/2);
strassan_mult(a22,temp1,s,x/2);

//Find P5
int t[MAX][MAX];
add(a11,a12,temp1,x/2);
strassan_mult(temp1,b22,t,x/2);

//Find P6
int u[MAX][MAX];
subtract(a21,a11,temp1,x/2);
add(b11,b12,temp2,x/2);
strassan_mult(temp1,temp2,u,x/2);

//Find P7
int v[MAX][MAX];
49
subtract(a12,a22,temp1,x/2);
add(b21,b22,temp2,x/2);
strassan_mult(temp1,temp2,v,x/2);

//find f11, c12,c21,c22


add(p,s,temp1,x/2);
subtract(temp1,t,temp2,x/2);
add(temp2,v,c11,x/2);
add(r,t,c12,x/2);
add(q,s,c21,x/2);
add(p,r,temp1,x/2);
subtract(temp1,q,temp2,x/2);
add(temp2,u,c22,x/2);

//Form c
joinarray(c,c11,0,0,x/2);
joinarray(c,c12,0,x/2,x/2);
joinarray(c,c21,x/2,0,x/2);
joinarray(c,c22,x/2,x/2,x/2);

}
}

int _tmain(int argc, _TCHAR* argv[]){


int a[MAX][MAX],n;
int b[MAX][MAX];
int r[MAX][MAX];
system ("CLS");
cout<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome to
Strassen Multiplication\n"<<"-----------------------------------------------------------------------------\n";

do{
cout<<"\nEnter the size of the array : ";
cin>>n;
if(n>MAX) cout<<"\nSize has to be less than 100";
}while(n>MAX);

//Inputting the matrices


cout<<"Enter elements of matrix 1:\n";
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cout<<"Enter element a["<<i<<"]["<<j<<"]:";
cin>>a[i][j];
}
}

cout<<"Enter elements of matrix 2:\n";


for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
50
{
cout<<"Enter element a["<<i<<"]["<<j<<"]:";
cin>>b[i][j];
}
}

strassan_mult(a,b,r,n);
cout<<"The resultant matrix is:\n";
display(r,n);
getch();
return 0;
}

Q22. Integer Multiplication


//////////////////////////////////////////////////////////////////////
//
//Name: Integer Multiplication by Divide & Conquer
//Author: Atishay Jain
//Date: 23-3-09
//Lang.: VC++
//Lab. : Assignment 22
//
/////////////////////////////////////////////////////////////////////

#include<conio.h>
#include<cstdio>
#include<cstdlib>
#include<iostream>
using namespace std;
#define MAX 100

//Multiplies integers a & b both of which are having 'bits' bits


int mul(int i,int j, int bits)
{
//If 1 bit return the multiplication
if(bits==1)
{
return i*j;
}
//Initialize all multipliers to 0
int ih=0,jh=0,il=0,jl=0;
int ihjh=0,iljl=0,temp;
int fact=0;

//Find Multiplication Factor to divide highs and lows as having bits/2 1s.
for(int k=0;k<bits/2;k++)
{
fact=fact<<1;
fact=fact+1;
}
//find il and ih
51
il=i&fact;
jl=j&fact;
ih=i-ih;
jh=j-jh;
ih=ih>>bits/2;
jh=jh>>bits/2;
//Find ihjh and iljl by recursion
ihjh=mul(ih,jh,bits/2);
iljl=mul(il,jl,bits/2);
//Find the third multiplication (ih-il)(jl-jl)
temp=mul(ih-il,jl-jh,bits/2)+ihjh+iljl;

//return the third multiplication*2^n/2 +ihjh*2^n + iljl


return ((temp<<bits/2) +(ihjh<<bits)+iljl);

int _tmain(int argc, _TCHAR* argv[])


{
int a,b;
system ("CLS");
cout<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome to
Integer Multiplication\n"<<"-----------------------------------------------------------------------------\n";
cout<<"Enter the two numbers:";
cin>>a;
cin>>b;
cout<<a<<"x"<<b<<"="<<mul(a,b,sizeof(a)*8);
getch();
return 0;

Q23. Optimal Merge Pattern


//////////////////////////////////////////////////////////////////////
//
//Name: Optimal Merge Pattern
//Author: Atishay Jain
//Date: 8-3-09
//Lang.: VC++
//Lab. : Assignment 27
//
/////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include<conio.h>
#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<queue>
using namespace std;
#define MAX 100

52
//array structure with array and its length
struct array
{
int val[500];
int n;

};

//Merge function for merging two given arrays


void merge(struct array a,struct array b,struct array *c)
{
a.val[a.n]=9999;
b.val[b.n]=9999;
(*c).n=a.n + b.n;
int i=0,j=0,index=0;
while(i<a.n || j<b.n)
{
if((a.val[i]<b.val[j] && i<a.n) || j>=b.n) (*c).val[index++]=a.val[i++];
else (*c).val[index++]=b.val[j++];

int _tmain(int argc, _TCHAR* argv[])


{
system ("CLS");
int n;
struct array arraySet[6];
//Menu
int e[5];
cout<<endl<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome
to Optimal Merge Pattern
Problem\n"<<"-----------------------------------------------------------------------------"<<endl;
do{
cout<<"Enter the number of arrays:";
cin>>n;
if(n>5) cout<<"Max. 5 allowed";
}while(n>5);
//input
for(int i=0;i<n;i++)
{
do{
cout<<"Enter the no. of elements in array #"<<i+1<<":";
cin>>arraySet[i].n;
if(arraySet[i].n>MAX) cout<<"Max size is "<<MAX;
}while(arraySet[i].n>MAX);
for(int j=0;j<arraySet[i].n;j++)
{
//Making sure that the ipuit is always is always in increasign order
do{
cout<<"Enter element no "<<j+1<<":";
cin>>arraySet[i].val[j];
if(j!=0 && arraySet[i].val[j] < arraySet[i].val[j-1])
53
{
cout<<"Please insert a greater value:";
}
}while(j!=0 && arraySet[i].val[j] < arraySet[i].val[j-1]);
}
e[i]=i ;
}
//Idea of merge - find the smallest two and merge them first
//Requires n-1 merges
int min,bmin,next=5;
for(int i=0;i<n-1;i++)
{
//setting min the smaller of first two
min=arraySet[e[0]].n>arraySet[e[1]].n?1:0;
bmin=arraySet[e[0]].n<=arraySet[e[1]].n?1:0;
//Finding smallest and second smallest
for(int j=2;j<n-i;j++)
{
if(arraySet[e[j]].n<arraySet[e[min]].n)
{
bmin=min;
min=j;
}
else if(arraySet[e[j]].n<arraySet[e[bmin]].n)
bmin=j;
}
//merging the smallest two
merge(arraySet[e[min]],arraySet[e[bmin]],arraySet+next);
e[min]=next;
e[bmin]=n-i-1;
next=min;
}
//Display Conpleted array
cout<<"Merged Sorted array is:"<<endl;
for(int i=0;i<arraySet[e[min]].n;i++)
{
cout<<arraySet[e[min]].val[i];
if(i+1!=arraySet[e[min]].n) cout <<" < ";
}
getch();
return 0;

Q24 Huffman Compression


//////////////////////////////////////////////////////////////////////
//
//Name: Huffman algorithm
//Author: Atishay Jain
//Date: 1-4-09
//Lang.: VC++
//Lab. : Assignment 1
54
//
/////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include<cstdio>
#include<iostream>
#include<conio.h>
#include<cstring>
#include<map>
using namespace std;
#define MAX 100

//structure to define a node with probability, character, and left and right child
struct node
{
int p;
char c;
node *left;
node *right;
};

//A huffman tree creator algorithm


node huffman(multimap<int,node> element)
{
int n=element.size();
struct node *ptr;
//we need n-1 more nodes for n leaves
for(int i=1;i<n;i++)
{
//Create a new node
ptr=new node;
multimap<int,node>::iterator it=element.begin();
//Gets smallest in the map for left
ptr->left=&(*it).second;
ptr->p=(*it).second.p;
element.erase(it);
//erases the smallest and brings next smallest for right
it=element.begin();
ptr->right = &(*it).second;

ptr->p+=(*it).second.p;
ptr->c='';
element.erase(it);
//now current node is also added
element.insert(pair<int,node>(ptr->p,*ptr));

}
multimap<int,node>::iterator it=element.begin();
//returns root
return (*it).second;
}

//Prints hash code of characters


void codeHash(node *n,char *s)
55
{
char p[MAX];
strcpy(p,s);
//Prints if leaf
if(n->left==NULL && n->right==NULL)
{
cout<<n->c<<" "<<s<<endl;
}
//Concats 0 for left and calls child
else if(n->left != NULL)
{
strcat(s,"0");
codeHash(n->left,s);
}
strcpy(s,p);
//Concats 1 for right and calls child
if(n->right != NULL)
{
strcat(s,"1");
codeHash(n->right,s);
}
}

int _tmain(int argc, _TCHAR* argv[])


{
int n;
multimap<int,node> element;
struct node root;
//Input
cout<<"Enter the number of letters wanted:";
cin>>n;
for(int i=0;i<n;i++)
{
struct node *ptr=new node;
cout<<"Enter character #"<<i+1<<" followed by its probability:";
cin>>ptr->c>>ptr->p;
ptr->left=NULL;
ptr->right=NULL;
element.insert(pair<int, node>(ptr->p,*ptr));
}
//call huffman
root=huffman(element);
char s[MAX]="";
//display codes
codeHash(&root,s);
getch();
return 0;
}

Q25 n Queens Problem


//////////////////////////////////////////////////////////////////////
//
//Name: nQueens Problem - Backtracking Soln.
//Author: Atishay Jain
56
//Date: 1-4-09
//Lang.: VC++
//Lab. : Assignment 1
//
/////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include<cstdio>;
#include<iostream>
#include<conio.h>
using namespace std;
int count=0;
int nQueen(int x,int *arr,int n);
int _tmain(int argc, _TCHAR* argv[])
{
int *a,n;
system ("CLS");
cout<<endl<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome
to n Queens Problem\n"<<"-----------------------------------------------------------------------------"<<endl;
cout<<"Enter the value of n in n Queens Problem:";
cin>>n;
//Declares array fro generic n queens
a = new int[n];
//Calls recursively
nQueen(0,a,n);
cout<<"Total Solns:"<<count;
getch();
return 0;
}

//Recursive soln. to the problem...


int nQueen(int x,int *arr,int n)
{
int flag;
//Check terminating condition. Prints the final matrix..
//If only 1 soln. is wanted, return 1 here and also check for 1 after the recursive call step.
if(x==n)
{
printf("Soln No. %d:",++count);
for(int i=0;i<n;i++)
{
cout<<"\n";
for(int j=0;j<arr[i];j++)
{
cout<<" .";
}
cout<<" @";
for(int j=0;j<n-arr[i]-1;j++)
cout<<" .";
}
cout<<"\n";
getch();
return -1;
}
57
//Checks all columns in the current row....
for(int i=0;i<n;i++)
{
arr[x]=i;
flag=0;
//Loop for check for conditions such that the queens attack.
for(int j=0;j<x;j++)
{
//Checking same Column
if(arr[x]==arr[j])
{
flag=-1;
break;
}
//Checking First Diagonal
if(i==arr[x-j-1]+j+1)
{
flag=-1;
break;
}
//Checking Second Diagonal
if(i==arr[x-j-1]-j-1)
{
flag=-1;
break;
}
}
//Calling recursive to for the next row if this one is possible.
if(flag==0)
{
//If only the first soln. is wanted, then check for the return of 1 in this step and
return the same.
nQueen(x+1,arr,n);
}
}
//Returns -1 to tell not possible and to backtrack....
return -1;
}

Q26 Knight Tour Problem


//////////////////////////////////////////////////////////////////////
//
//Name: Knight Tour Problem
//Author: Atishay Jain
//Date: 12-4-09
//Lang.: VC++
//Lab. : Assignment 26
//
/////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include<cstdio>
58
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<conio.h>
using namespace std;

const int size=8;


int board[size][size];

//Checks if the position entered is a valid position on the chessboard, returns 0 if not
//also checks if position is visited.
int valid_pos (int row, int col, int size){
if(row>=size || col>=size || row<0 || col<0){//Test for chosen location being within board
dimensions
return 1;

}
else{//Check to see if location was not previously visited
if((board[row][col]) == 0){
return 0;

}
else{
return 1;

}
}
}

//Checks whether
int check_board(int size)
{
int rows, cols, checker;

for(rows=0;rows<size;rows++)
{
for(cols=0;cols<size;cols++)
{
if(valid_pos(rows,cols,size)!=1)
{
checker=0;
}
}
}
return(checker);
}

//Recursively checks knight tour possibility


void recursive(int row, int col, int size, int count)
{

int checked;
59
board[row][col]=count;

//sees one move of knight is possible


if(valid_pos (row+2, col+1, size)!=1){
count++;
recursive(row+2, col+1, size, count);
//sees if tour completes, otherwise reverts changes
checked=check_board(size);
if(checked==0){
board[row+2][col+1]=0;
count--;
}
}
//repeats for other options
if(valid_pos (row+2, col-1, size)!=1){
count++;
recursive(row+2, col-1, size, count);
checked=check_board(size);
if(checked==0){
board[row+2][col-1]=0;
count--;

}
}
if(valid_pos (row+1, col+2, size)!=1){
count++;
recursive(row+1, col+2, size, count);
checked=check_board(size);
if(checked==0){
board[row+1][col+2]=0;
count--;
}
}
if(valid_pos (row+1, col-2, size)!=1){
count++;
recursive(row+1, col-2, size, count);
checked=check_board(size);
if(checked==0){
board[row+1][col-2]=0;
count--;
}
}
if(valid_pos(row-2, col+1, size)!=1){
count++;
recursive(row-2, col+1, size, count);
checked=check_board(size);
if(checked==0){
board[row-2][col+1]=0;
count--;
}
}

if(valid_pos (row-2, col-1, size)!=1){


60
count++;
recursive(row-2, col-1, size, count);
checked=check_board(size);
if(checked==0){
board[row-2][col-1]=0;
count--;
}
}
if(valid_pos (row-1, col+2, size)!=1){
count++;
recursive(row-1, col+2, size, count);
checked=check_board(size);
if(checked==0){
board[row-1][col+2]=0;
count--;
}
}
if(valid_pos (row-1, col-2, size)!=1){
count++;
recursive(row-1, col-2, size, count);
checked=check_board(size);
if(checked==0){
board[row-1][col-2]=0;
count--;
}
}

checked=check_board(size);
if(checked==0){
board[row][col]=0;
count--;
}
}

int _tmain(int argc, _TCHAR* argv[])


{
int row, col;
do{
int count=1;
for(int a=0;a<=size;a++)
{
for(int b=0;b<=size;b++)
{
board[a][b]=0;
}
}
system ("CLS");
cout<<endl<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome
to Knight tour Problem\n"<<"-----------------------------------------------------------------------------"<<endl;

cout<<"Enter the start row of the knight: ";


cin>>row;
cout<<"Enter the starting column of the knight: ";
cin>>col;
61
if((valid_pos (row, col, size)==1)
cout<<"Invalid Position";

//Call Knight Tour


recursive(row, col, size, count);

//Display Output

//contains the positions as per knight moves


for(int c=0;c<size;c++)
{
for(int d=0;d<size;d++)
{
if(d==size-1)
{
cout<<"| "<<board[c][d]<<" |"<<endl;
}
else
{
cout<<"| "<<board[c][d]<<" ";
}
}
}
cout<<"\n Press e to exit";
}while(getche()!='e');

return 0;
}

Q27 Implement the depth first search


//////////////////////////////////////////////////////////////////////
//
//Name: Depth First Search Algo
//Author: Atishay Jain
//Date: 8-3-09
//Lang.: VC++
//Lab. : Assignment 27
//
/////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include<conio.h>
#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<set>
#include<queue>
#include<stack>
62
using namespace std;
#define MAX 100

int _tmain(int argc, _TCHAR* argv[])


{
int a[MAX][MAX],size;
//Menu
system ("CLS");
cout<<endl<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome
to Depth First Search\n"<<"-----------------------------------------------------------------------------"<<endl;
do{
cout<<"\nEnter the size of the array : ";
cin>>size;
if(size>MAX) cout<<"\nSize has to be less than 100";
}while(size>MAX);
//Input the adjacency Matrix
cout<<"Enter the adjacency matrix(Enter 0 for not reachable):\n";
for(int i=0;i<size;i++)
{
for(int j=0;j<size;j++)
{
cin>>a[i][j];
}
}
//Set of nodes visited
set<int> visited;
//Stack for DFS
stack<int> list;
//Next element to be traversed
int next;
//Starts with 0
visited.insert(0);
list.push(0);
cout<<"The route travelled during Depth First Search is:";
do{
next=list.top();
list.pop();
cout<<next;
for(int i=0;i<size;i++)
{
//Checks if route is reachable and not visited and pushes it onto stack
if(a[next][i] !=0 && visited.find(i)== visited.end())
{
visited.insert(i);
list.push(i);
}
}
//If stack empty
if(!list.empty()) cout<<"->";
}while(!list.empty());
getch();
return 0;

63
}

Q28 Implement Breadth First Search


//////////////////////////////////////////////////////////////////////
//
//Name: Breadth First Search Algo
//Author: Atishay Jain
//Date: 8-3-09
//Lang.: VC++
//Lab. : Assignment 27
//
/////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include<conio.h>
#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<set>
#include<queue>
#include<stack>
using namespace std;
#define MAX 100

int _tmain(int argc, _TCHAR* argv[])


{
int a[MAX][MAX],size;
//Menu
system ("CLS");
cout<<endl<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome
to Depth First Search\n"<<"-----------------------------------------------------------------------------"<<endl;
do{
cout<<"\nEnter the size of the array : ";
cin>>size;
if(size>MAX) cout<<"\nSize has to be less than 100";
}while(size>MAX);
//Input the adjacency Matrix
cout<<"Enter the adjacency matrix(Enter 0 for not reachable):\n";
for(int i=0;i<size;i++)
{
for(int j=0;j<size;j++)
{
cin>>a[i][j];
}
}
//Set of nodes visited
set<int> visited;
//Queue for BFS
queue<int> list;
//Next element to be traversed
int next;
//Starts with 0
64
visited.insert(0);
list.push(0);
cout<<"The route travelled during Depth First Search is:";
do{
next=list.front();
list.pop();
cout<<next;
for(int i=0;i<size;i++)
{
//Checks if route is reachable and not visited and pushes it onto stack
if(a[next][i] !=0 && visited.find(i)== visited.end())
{
visited.insert(i);
list.push(i);
}
}
//If stack empty
if(!list.empty()) cout<<"->";
}while(!list.empty());
getch();
return 0;

Q29 Prim’s Algorithm


//////////////////////////////////////////////////////////////////////
//
//Name: Prim's Algo
//Author: Atishay Jain
//Date: 8-3-09
//Lang.: VC++
//Lab. : Assignment 22
//
/////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include<conio.h>
#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<set>
using namespace std;
//Defining MAX and Infinite
#define MAX 100
#define INF 1000
int _tmain(int argc, _TCHAR* argv[])
{
//Set to contain the set of nodes traversed
set<int> nodes;
//Array for adjacency matrix
int x[MAX][MAX];
65
int n;
system ("CLS");
cout<<endl<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome
to Prim's Algorithm\n"<<"-----------------------------------------------------------------------------"<<endl;
//Input no of nodes.
do{
cout<<"Enter the no of nodes:";
cin>>n;
}while(n>=100);
//Input Adjacency Matrix
cout<<"Enter the adjacency Matrix:\n";
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
cin>>x[i][j];
x[i][i]=INF;
}
//Start with the first node
nodes.insert(0);
//Check till all nodes have been inserted
while(nodes.size() != n)
{
int min=INF,minj=INF,mini=INF;
//Iterate all nodes in set
for(set<int>::iterator i=nodes.begin();i!=nodes.end();i++)
{
//Iterate the adjacency matrix for all elements in node
for(int j=0;j<n;j++)
{
//Check if this route is the optimal for MST
if(x[*i][j]<min && nodes.find(j) == nodes.end())
{
min=x[*i][j];
minj=j;
mini =*i;
}
}
}
//If no route comes out optimal
if(minj == INF)
{
printf("Not possible");
getch();
return 0;
}
//If there is a possible route
nodes.insert(minj);
//Gives output......
printf("\nConnect%d --- %d",mini+1,minj+1);
}

getch();
return 0;
}
66
Q30. Kruskal’s Algorithm
//////////////////////////////////////////////////////////////////////
//
//Name: Kruskal's Algorithm
//Author: Atishay Jain
//Date: 13-4-09
//Lang.: VC++
//Lab. : Assignment 30
//
/////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include<cstdio>;
#include<iostream>
#include<conio.h>
using namespace std;
#define MAXVEX 6
#define MAX 9999999

//storing the graph, can alternatively be two variables.


struct graphMatrix {
int n;
float arcs[MAXVEX][MAXVEX];
};

//Structure to store the output, can intead be preinted whenever found


struct Edge{
int startVertex, endVertex;
float weight;
};

struct Edge mst[5];

//Implementation of Kruskal's Algorithm


int kruskal(struct graphMatrix graph,struct Edge mst[]) {
int i, j, num = 0, start, stop;
float minweight;
int status[1000];
//The status variable corresponds to the equality of reach in case the tree has a vertex
for (i = 0; i < graph.n; i++)
status[i] = i;
while (num < graph.n - 1){
minweight = MAX;
//Find the smallest vertex
for (i = 0; i < graph.n-1; i++)
for (j = i+1; j < graph.n; j++)
if (graph.arcs[i][j] < minweight){
start = i; stop = j;
minweight = graph.arcs[i][j];
}
67
//If smallest vertex is MAX, it means Kruskal not possible(No MST)
if (minweight == MAX) return 0;
//If the vertext is not shorted(Making a circuit)
if (status[start] != status[stop]){
//Saves vertex information, can be displayed here
mst[num].startVertex = start;
mst[num].endVertex = stop;
mst[num].weight = graph.arcs[start][stop];
num++;
j = status[stop];
//Shorts the vertex, that is makes the vertices have the same weights or the
weight now is zero ad uncountable for those vertices
for (i = 0; i < graph.n; i++)
if(status[i] == j)
status[i] = status[start];
}
//Makes thsi vertex unreachable.
graph.arcs[start][stop] = MAX;
}//Terminates if n-1 edges in tree.
return 1;
}

struct graphMatrix graph;

int main(){
int i;
//Menu
system ("CLS");
cout<<endl<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome
to Kruskal's Algorithm\n"<<"-----------------------------------------------------------------------------"<<endl;
do{
cout<<"Enter the number of Vertices:";
cin>>graph.n;
if(graph.n>MAXVEX) cout<<"\nToo many vertices(MAX is 6)";
}while(graph.n>MAX);
//Input Adjacency
cout<<"Enter the Adjacency Matrix:\n";
for(i=0;i<graph.n;i++)
{
for(int j=0;j<n;j++)
{
cout<<"Enter the dajaceny value at M["<<i<<"]["<<j<<"]:";
cin>>graph.arcs[i][j];
}
}
//see kruskal
if (kruskal(graph,mst) == 1)
{
cout<<"The vertices to combine include:";
for (i = 0; i < graph.n-1; i++)
printf("(%d %d %f)\n", mst[i].startVertex,mst[i].endVertex, mst[i].weight);
}
getch();
return 0;
68
}

Q31. Matrix Chain Multiplication


//////////////////////////////////////////////////////////////////////
//
//Name: Matrix Multiplication Problem
//Author: Atishay Jain
//Date: 20-04-09
//Lang.: VC++
//Lab. : Assignment 31
//
/////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include<conio.h>
#include<cstdio>
#include<cstdlib>
#include<iostream>
using namespace std;
#define MAX 999999

//Display function
void display(int partitionPoint[100][100],int i,int j)
{
//if single dimesntion print value
if(i==j)
printf("%c",'A'+i-1);
else
{
//If it is compound, print inside bracket, till partition point and then beyond
cout<<"(";
display(partitionPoint,i,partitionPoint[i][j]);
display(partitionPoint,partitionPoint[i][j]+1,j);
cout<<")";
}
}

int _tmain(int argc, _TCHAR* argv[])


{
int size[100],n,partitionPoint[100][100]
int minMultiplications[100][100]={0};
system ("CLS");
cout<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome to
Matrix Chain Multiplication\n"<<"-----------------------------------------------------------------------------";
do{
printf("Enter number of matrices:");
scanf("%d",&n);
if(n>100) cout<<"Not more than 100 matrices\n";
}while(n>100);

69
cout<<"Enter matrix dimensions(Note that matrix a(mxn)'s n will directly be taken for
b(nxp)):\n";
printf("Enter m for mxn in Matrix 1:");
cin>>size[0];
for(int i=1;i<=n;i++)
{
printf("Enter n for mxn in Matrix %d:",i);
cin>>size[i];
}
//Matrix Multiplications Possible
for(int chainLength=2;chainLength<=n;chainLength++)
{
for(int i=1;i<=n-chainLength+1;i++)
{
int j=i+chainLength-1;
//Finding the minimum for i,j
minMultiplications[i][j]=MAX;
for(int k=i;k<=j-1;k++)
{
//minizimization Formula for i,j - Smallest from i to k + k+1to j
and the joining of the two
int temp=minMultiplications[i][k]+minMultiplications[k+1][j]+size[i-
1]*size[k]*size[j];
if(temp<minMultiplications[i][j])
{
minMultiplications[i][j]=temp;
//Save partition point for bracketing
partitionPoint[i][j]=k;
}
}
}
}

display(partitionPoint,1,n);
getch();
}

Q32. 0/1 Knapsack Problem


//////////////////////////////////////////////////////////////////////
//
//Name: 0/1 Knapsack Problem - DP solution
//Author: Atishay Jain
//Date: 1-4-09
//Lang.: VC++
//Lab. : Assignment 1
//
/////////////////////////////////////////////////////////////////////

//#include "stdafx.h"

70
#include<cstdio>
#include<iostream>
#include<conio.h>
using namespace std;
#define MAXN 100
//MAXN is the maximum value of n, no of elements
#define MAXK 100
//MAXK is the maximum bag size

int sackValues[MAXN][MAXK+1];
int cost[MAXN];
int profit[MAXN];

int knapsack(int n,int k) {


int c;
//Clear the matrix first
for(int i=0; i<n; i++)
for (int j=0;j<=k;j++)
sackValues[i][j] = 0;
//Initialize all elements
for(int i=cost[0]; i<=k; i++)
sackValues[0][i] = profit[0];
//Introduct each element 1 by 1.
for(int i=1;i<n;i++)
for(int j=0;j<=k;j++)
{
//See if by adding the element can help improve the cost, by adding it to n-cost and
replacing if possible at all positions
if(j-cost[i] >= 0)
c = sackValues[i-1][j-cost[i]]+profit[i];
else
c = 0;
if(c < sackValues[i-1][j])
c = sackValues[i-1][j];
sackValues[i][j] = c;
}
return sackValues[n-1][k];
}

//int _tmain(int argc, _TCHAR* argv[])


int main()
{
int n,k;
//Menu
system ("CLS");
cout<<endl<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome to
0/1 Knapsack Problem\n"<<"-----------------------------------------------------------------------------"<<endl;
do{
cout<<"Enter the no of items:";
cin>>n;
if(n>MAXN) cout<<"it should be less than 100:";
}while(n>MAXN);
for(int i=0;i<n;i++)
71
{
cout<<"Enter Cost for item no. "<<i+1<<":";
cin>>cost[i];
cout<<"Enter Profit for item no. "<<i+1<<":";
cin>>profit[i];
}
do{
cout<<"Enter the size of the Knapsack:";
cin>>k;
if(n>MAXK) cout<<"it should be less than 100:";
}while(n>MAXK);
cout<<"The maximum profit possible is:"<<knapsack(n,k);
getch();
return 0;
}

Q33. Anagram Problem


//////////////////////////////////////////////////////////////////////
//
//Name: Find if two strings are Anagrams
//Author: Atishay Jain
//Date: 22-2-09
//Lang.: VC++
//Lab. : Assignment 27
//
/////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include<cstdio>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<conio.h>
using namespace std;

int _tmain(int argc, _TCHAR* argv[])


{
char word1[100],word2[100];
system ("CLS");
cout<<endl<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome
to Anagram\n"<<"-----------------------------------------------------------------------------"<<endl;
int a[26]={0};
//Input
cout<<"Enter Words:";
cin>>word1>>word2;
//Check if equal length
if(strlen(word1)!=strlen(word2))
{
printf("No");
getch();
exit(0);
}

72
//Use an array and ascii-<ascii of 'a'> as hash. Add for first word, subtract for second
for(int i=0;i<strlen(word1);i++)
{
a[tolower(word1[i])-'a']++;
a[tolower(word2[i])-'a']--;
}
int flag=0;
//Check if all array elements are zero, meaning both ++ and -- are performed same
for(int i=0;i<26;i++)
{
if(a[i]!=0)
{
flag=1;
break;
}
}
//Print on the basis of the above check
if(flag==1) printf("No");
else printf("Yes");
getch();
return 0;
}

Q34 Substring Problem


//////////////////////////////////////////////////////////////////////
//
//Name: Substring
//Author: Atishay Jain
//Date: 22-2-09
//Lang.: VC++
//Lab. : Assignment 27
//
/////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include<cstdio>
#include<iostream>
#include<conio.h>
using namespace std;
/////////////////////////
// Name: Substring
// Return Type: int:position of substring(-1 if not found)
// Arguments: char* MainString, char* Subtring
////////////////////////
int substring(char *a,char *b)
{
char *p=a;
//Scanning mainstring linearly
while(*a!=NULL)
{
//Checking substring first letter match
73
if(*a==*b)
{
int c=1,flag=0;
//Scanning subsequent methods of substring
while(*(b+c) != NULL)
{
//If no match, stop scan
if(*(b+c) != *(a+c))
{
flag=1;
break;
}
c++;
}
//If scan successful, return the correct value
if(flag==0)
{
return a-p;
}
}
a++;
}
//Falls here if no match possible.
return -1;
}
int _tmain(int argc, _TCHAR* argv[])
{
//Display Heasder
system ("CLS");
cout<<endl<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome
to Substring\n"<<"-----------------------------------------------------------------------------"<<endl;
char word1[100],word2[100];
//Input
cout<<"Enter words";
cin>>word1>>word2;
//Call substring and check
if(substring(word1,word2) == -1) printf("Not a Substring");
else printf("Substring");
getch();
return 0;
}

Q35. Travelling Salesman Problem


//////////////////////////////////////////////////////////////////////
//
//Name: TSP
//Author: Atishay Jain
//Date: 8-3-09
//Lang.: VC++
//Lab. : Assignment 35
//
/////////////////////////////////////////////////////////////////////

74
#include "stdafx.h"
#include<conio.h>
#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<set>
using namespace std;
//Defining MAX and Infinite
#define MAX 100
#define INF 1000

int branch(int start,int cost, int end, set<int> nodes, int a[MAX][MAX], int n )
{
//Terminating Condition
if(start==end)
{
//If route is complete
if(nodes.size() == n) return cost;
//not to return -1 right at the start
if(nodes.size() != 0) return -1;
}
int l=0;
int x[MAX]={0};
x[0]=-1;
for(int i=0;i<n;i++)
{
//goto each node traversible from start......
if(a[start][i] != 0 && nodes.find(i) == nodes.end())
{
nodes.insert(i);
//Branch to the traversible nodes to get cost
x[l++]=branch(i,cost+a[start][i],end,nodes,a,n);
nodes.erase(i);
//If that branch fails, remove it....
if(x[l-1] == -1) l--;

}
}
//find minimum cost
int min=x[0];
for(int i=0;i<l;i++)
{
if(x[i]<min)
{
min=x[i];
}
}
return min;
}

int _tmain(int argc, _TCHAR* argv[])


{
75
//Set to contain the set of nodes traversed
set<int> nodes;
//Array for adjacency matrix
int x[MAX][MAX];
int n;
system ("CLS");
cout<<endl<<"-----------------------------------------------------------------------------"<<"\t\t\t\tWelcome
to Travelling salesman
problem\n"<<"-----------------------------------------------------------------------------"<<endl;
//Input no of nodes.
do{
cout<<"Enter the no of nodes:";
cin>>n;
}while(n>=100);
//Input Adjacency Matrix
cout<<"Enter the adjacency Matrix(0=Not reachable):\n";
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
cin>>x[i][j];
x[i][i]=0;
}
//Display results....
cout<<"Minimum Cost is:"<<branch(0,0,0,nodes,x,n);
getch();
return 0;
}

76
-----------------------------------------------------------------------------
x--------------------------------------------------------------------------------

77

Das könnte Ihnen auch gefallen