DSA MANUAL WITH MINIPROJECT
DSA MANUAL WITH MINIPROJECT
INDEX
Sr.No Name Of Experiment Page
No
1 Consider telephone book database of N clients. Make use of a
hash table implementation to quickly look up client‘s telephone
number. Make use of two collision handling techniques and
compare them using number of comparisons required to find
a set of telephone numbers
2 Implement all the functions of a dictionary (ADT) using
hashing and handle collisions using chaining with / without
replacement.
Data: Set of (key, value) pairs, Keys are mapped to values,
Keys must be comparable,
Keys must be unique. Standard Operations: Insert(key, value),
Find(key), Delete(key)
3 A book consists of chapters, chapters consist of sections and
sections consist of subsections. Construct a tree and print the
nodes. Find the time and space requirements of your method.
4 Beginning with an empty binary search tree, Construct binary
search tree by inserting the values in the order given. After
constructing a binary tree -
i. Insert new node, ii. Find number of nodes in longest path
from root, iii. Minimum data value found in the tree, iv.
Change a tree so that the roles of the left and right pointers
are swapped at every node, v. Search a value
5 Convert given binary tree into threaded binary tree. Analyze
time and space complexity
of the algorithm
6 Represent a given graph using adjacency matrix/list to
perform DFS and using adjacency list to perform BFS. Use
the map of the area around the college as the graph. Identify
the prominent land marks as nodes and perform DFS and BFS
on that.
7 There are flight paths between cities. If there is a flight
between city A and city B then there is an edge between the
cities. The cost of the edge can be the time that flight take to
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Experiment No-1
Aim:- Consider telephone book database of N clients Make use of Hash Table Implementation
to quickly look up clients telephone number make use two collision handling technique and
compare this using number of comparison required to find a set of telephone number.
Prerequisite:
C++ Programming
Theory:
Hashing is a technique that uses fewer key comparisons and searches the element in O(n) time
in the worst case and in O(1) time in the average case.
The task is to implement all functions of phone directory:
1. create_record
2. display_record
3. delete_record
4. search_record
5. update_record
Approach:
We are creating a hash table, and inserting records. For deleting, searching, or updating an
entity, the client ID is asked and on the basis of equality operator, details are displayed or
processed. If the record is not found, then an appropriate message is displayed.
.Collision is the major problem in the hashing technique. In open addressing (closed hashing),
all collisions are resolved in the prime area i.e., the area that contains all of the home
addresses.
When a collision occurs, the prime area addresses are searched for an open or unoccupied
element using linear probing.
Steps for inserting entities in a hash table:
1. If the location is empty, directly insert the entity.
2. If mapped location is occupied then keep probing until an empty slot is found. Once an
empty slot is found, insert the entity.
1. Create Record: This method takes details from the user like ID, Name and Telephone
number and create new record in the hashtable.
2. Display Record: This function is created to display all the record of the diary.
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
3. Delete Record: This method takes the key of the record to be deleted. Then, it searches in
hash table if record id matches with the key. Then, that record is deleted.
4. Search Record: This method takes the key of the record to be searched. Then, it traverses
the hash table, if record id matches with the key it displays the record detail.
5. Update Record: This method takes the key of the record to be searched. Then, it traverses
the hash table, if record id matches with the key then it displays the record detail.
a) Chaining:
This technique implements a linked list and is the most popular collision resolution techniques.
Below is an example of a chaining process.
Here, since one slot has 3 elements – {50, 85, 92}, a linked list is assigned to include the other
2 items {85, 92}. When you use the chaining technique, inserting or deleting of items with the
hash table is fairly simple and high performing. Likewise, a chain hash table inherits the pros
and cons of a linked list. Alternatively, chaining can use dynamic arrays instead of linked lists.
b) Open Addressing:
This technique depends on space usage and can be done with linear or quadratic probing
techniques. As the name says, this technique tries to find an available slot to store the record. It
can be done in one of the 3 ways –
Linear probing – Here, the next probe interval is fixed to 1. It supports best caching but
miserably fails at clustering.
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Quadratic probing – the probe distance is calculated based on the quadratic equation.
This is considerably a better option as it balances clustering and caching.
Double hashing – Here, the probing interval is fixed for each record by a second
hashing function. This technique has poor cache performance although it does not have
any clustering issues.
Below are some of the hashing techniques that can help in resolving collision.
c) Probabilistic hashing:
This is memory based hashing that implements caching. When collision occurs, either the old
record is replaced by the new or the new record may be dropped. Although this scenario has a
risk of losing data, it is still preferred due to its ease of implementation and high performance.
d) Perfect hashing:
When the slots are uniquely mapped, there is very less chances of collision. However, it can be
done where there is a lot of spare memory.
e) Coalesced hashing:
This technique is a combo of open address and chaining methods. A chain of items are stored
in the table when there is a collision. The next available table space is used to store the items to
prevent collision.
Program;-
#include <iostream>
using namespace std;
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
else
index=(index+1)%size;
} }
// Function to search for record based on name input
void search_record(string name){
int index1,k,flag=0;
k=ascii_generator(name);
index1=k%size;
for(int a=0;a<size;a++){
if(data[index1].key==k){
flag=1;
cout<<"\nRecord found\n";
cout<<"Name :: "<<data[index1].name<<endl;
cout<<"Telephone :: "<<data[index1].telephone<<endl;
break;
}
else
index1=(index1+1)%size;
}
if(flag==0)
cout<<"Record not found";
}
// Function to delete existing record
void delete_record(string name){
int index1,key,flag=0;
key=ascii_generator(name);
index1=key%size;
for(int a=0;a<size;a++){
if(data[index].key==key){
flag=1;
data[index1].key=0;
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
data[index1].name=" ";
data[index1].telephone=" ";
cout<<"\nRecord Deleted successfully"<<endl;
break;
}
else
index1=(index1+1)%size;
}
if(flag==0)
cout<<"\nRecord not found";
}
// Function to update existing record
void update_record(string name){
int index1,key,flag=0;
key=ascii_generator(name);
index1=key%size;
for(int a=0;a<size;a++){
if(data[index1].key==key){
flag=1;
break;
}
else
index1=(index1+1)%size;
}
if(flag==1){
cout<<"Enter the new telephone number :: ";
cin>>tele;
data[index1].telephone=tele;
cout<<"\nRecord Updated successfully";
}}
// Function to display the directory
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
void display_record(){
cout<<"\t Name \t\t Telephone";
for (int a = 0; a < size; a++) {
if(data[a].key!=0){
cout<<"\n\t"<<data[a].name<<" \t\t\t "<<data[a].telephone;
} } }};
// Main Function
int main(){
hashing s;
string name;
string telephone;
int choice,x;
bool loop=1;
// Menu driven code
while(loop){
cout<<"\n-------------------------"<<endl
<<" Telephone book Database "<<endl
<<"-------------------------"<<endl
<<"1. Create Record"<<endl
<<"2. Display Record"<<endl
<<"3. Search Record"<<endl
<<"4. Update Record"<<endl
<<"5. Delete Record"<<endl
<<"6. Exit"<<endl
<<"Enter choice :: ";
cin>>choice;
switch (choice)
{
case 1:
cout<<"\nEnter name :: ";
cin>>name;
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Output:
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Experiment No-2
Aim: Implement all the functions of a dictionary (ADT) using hashing and handle collisions using
chaining with / without replacement. Data: Set of (key, value) pairs, Keys are mapped to values, Keys
must be comparable, Keys must be unique. Standard Operations: Insert(key, value), Find(key),
Delete(key).
Prerequisite:
C++ Programming
Theory:
What is Collision?
Since a hash function gets us a small number for a key which is a big integer or string, there is a
possibility that two keys result in the same value. The situation where a newly inserted key maps to an
already occupied slot in the hash table is called collision and must be handled using some collision
handling technique.
Separate Chaining:
The idea is to make each cell of hash table point to a linked list of records that have same hash function
value.
haining is a possible way to resolve collisions. Each slot of the array contains a link to a singly-linked
list containing key-value pairs with the same hash. New key-value pairs are added to the end of the
list. Lookup algorithm searches through the list to find matching key. Initially table slots contain nulls.
List is being created, when value with the certain hash is added for the first time.
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Chaining illustration
Complexity analysis
Assuming, that hash function distributes hash codes uniformly and table allows dynamic resizing,
amortized complexity of insertion, removal and lookup operations is constant. Actual time, taken by
those operations linearly depends on table's load factor.
Note. Even substantially overloaded hash table, based on chaining, shows well performance. Assume
hash table with 1000 slots storing 100000 items (load factor is 100). It requires a bit more memory
(size of the table), than a singly-linked list, but all basic operations will be done about 1000 times
faster on average. Draw attention, that computational complexity of both singly-linked list and
constant-sized hash table is O(n).
chaining is a concept which introduces an additional field with data i.e. chain. A separate chain table
is maintained for colliding data. When collision occurs, we store the second colliding data by linear
probing method. The address of this colliding data can be stored with the first colliding element in the
chain table, without replacement.
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
From the example, you can see that the chain is maintained from the number who demands for location 1.
First number 131 comes, we place it at index 1. Next comes 21, but collision occurs so by linear probing
we will place 21 at index 2, and chain is maintained by writing 2 in chain table at index 1. Similarly next
comes 61, by linear probing we can place 61 at index 5 and chain will maintained at index 2. Thus any
element which gives hash key as 1 will be stored by linear probing at empty location but a chain is
maintained so that traversing the hash table will be efficient.
Program:
#include<iostream>
#include<conio.h>
#include<stdlib.h>
# define max 10
int data;
} node_type;
node_type *ptr[max],*root[max],*temp[max];
class Dictionary
public:
int index;
Dictionary();
void insert(int);
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
void search(int);
void delete_ele(int);
};
Dictionary::Dictionary()
index=-1;
root[i]=NULL;
ptr[i]=NULL;
temp[i]=NULL;
index=int(key%max);
ptr[index]=(node_type*)malloc(sizeof(node_type));
ptr[index]->data=key;
if(root[index]==NULL)
root[index]=ptr[index];
root[index]->next=NULL;
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
temp[index]=ptr[index];
else
temp[index]=root[index];
while(temp[index]->next!=NULL)
temp[index]=temp[index]->next;
temp[index]->next=ptr[index];
int flag=0;
index=int(key%max);
temp[index]=root[index];
while(temp[index]!=NULL)
if(temp[index]->data==key)
flag=1;
break;
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
else temp[index]=temp[index]->next;
if (flag==0)
index=int(key%max);
temp[index]=root[index];
ptr[index]=temp[index];
temp[index]=temp[index]->next;
ptr[index]->next=temp[index]->next;
temp[index]->data=-1;
temp[index]=NULL;
free(temp[index]);
main()
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
int val,ch,n,num;
char c;
Dictionary d;
do
cout<<"\nMENU:\n1.Create";
cin>>ch;
switch(ch)
case 1:
cin>>n;
cin>>num;
d.insert(num);
break;
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
case 2:
cin>>n;
d.search(n);
case 3:
cin>>n;
d.delete_ele(n);
break;
default:
cout<<"\nInvalid Choice.";
cout<<"\nEnter y to Continue:";
cin>>c;
while(c=='y');
getch();
output
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Experiment No-03
Aim: A book consists of chapters, chapters consist of sections and sections consist of subsections.
Construct a tree and print the nodes. Find the time and space requirements of your method.
Prerequisite:
C++ Programming
Input: : A book consists of chapters, chapters consist of sections and sections consist of subsections.
Theory:
What is Tree
Tree represents the nodes connected by edges. We will discuss binary tree or binary search tree
specifically.
Binary Tree is a special datastructure used for data storage purposes. A binary tree has a special
condition that each node can have a maximum of two children. A binary tree has the benefits of both an
ordered array and a linked list as search is as quick as in a sorted array and insertion or deletion
operation are as fast as in linked list.
Important Terms
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Parent − Any node except the root node has one edge upward to a node called parent.
Child − The node below a given node connected by its edge downward is called its child node.
Leaf − The node which does not have any child node is called the leaf node.
Subtree − Subtree represents the descendants of a node.
Visiting − Visiting refers to checking the value of a node when control is on the node.
Traversing − Traversing means passing through nodes in a specific order.
Levels − Level of a node represents the generation of a node. If the root node is at level 0, then
its next child node is at level 1, its grandchild is at level 2, and so on.
keys − Key represents a value of a node based on which a search operation is to be carried out
for a node.
1
/ \
2 3
\
4
\
5
\
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
6
Top view of the above binary tree is
2136
Program:
#include<iostream>
using namespace std;
class TREE_CLASS
{
private:
typedef struct bin
{
char data[50];
struct bin *left;
struct bin *right;
}node;
public:
node *New,*root;
TREE_CLASS();
void create();
void insert(node *,node *);
void rec_inorder(node *);
void printLevelOrder(node* root);
void printLevel(node* root,int level);
int height(node* node);
};
TREE_CLASS::TREE_CLASS()
{
root = NULL;
}
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
void TREE_CLASS::create()
{
char ans='y';
do
{
New=new node;
cout<<"\nEnter the elemnets=";
cin>>New->data;
New->left=NULL;
New->right=NULL;
if(root==NULL)
root=New;
else
insert(root,New);
cout<<"\nDo you want to insert more elements?(y/n)=";
cin>>ans;
}while(ans=='y'||ans=='y');
}
void TREE_CLASS::insert(node *root,node *New)
{
char ch;
cout<<"\nWhere to insert left/right of(l/r)->"<<root->data<<":";
cin>>ch;
if((ch=='r')||(ch=='R'))
{
if(root->right==NULL)
{
root->right=New;
}
else
insert(root->right,New);
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
}
else
{
if(root->left==NULL)
{
root->left=New;
}
else
insert(root->left,New);
}}
void TREE_CLASS::rec_inorder(node *root)
{
if(root!=NULL)
{
rec_inorder(root->left);
cout<<""<<root->data;
rec_inorder(root->right);
}}
void TREE_CLASS::printLevelOrder(node* root)
{
int h=height(root);
int i;
for(i=1;i<=h;i++) {
cout<<"\n";
printLevel(root,i);
}}
void TREE_CLASS::printLevel(node* root,int level)
{
if(root==NULL)
return;
if(level==1)
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
cout<<""<<root->data;
else if(level>1)
{
printLevel(root->left,level-1);
printLevel(root->right,level-1);
}}
int TREE_CLASS::height(node* node)
{
if(node==NULL)
return 0;
else
{
int lheight=height(node->left);
int rheight=height(node->right);
if(lheight>rheight)
return(lheight+1);
else
return(rheight+1);
}}
int main()
{
int choice;
TREE_CLASS obj;
Do {
cout<<"\nMAIN MENU";
cout<<"\n1.create";
cout<<"\n2.display";
cout<<"\n3.Exit";
cout<<"\nEnter your choice:";
cin>>choice;
switch(choice) {
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
case 1: obj.create();
break;
case 2: if(obj.root==NULL)
cout<<"TREE IS NOT CREATED";
else
obj.printLevelOrder(obj.root);
break; }
}while(choice<=2);
return 0; }
output
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Experiment No-4
Aim -Beginning with an empty binary search tree, Construct binary search tree by inserting the
values in the order given. After constructing a binary tree -
i. Insert new node, ii. Find number of nodes in longest path from root, iii. Minimum data value
found in the tree, iv. Change a tree so that the roles of the left and right pointers
are swapped at every node, v. Search a value
Prerequisite:
C++ Programming
Theory
The following is the definition of Binary Search Tree(BST) according to Wikipedia
Binary Search Tree is a n ode-based binary tree data structure which has the following
properties:
The left subtree of a node contains only nodes with keys lesser than the node’s key.
The right subtree of a node contains only nodes with keys greater than the node’s key.
The left and right subtree each must also be a binary search tree.
There must be no duplicate nodes.
The above properties of Binary Search Tree provides an ordering among keys so that the
operations like search, minimum and maximum can be done fast. If there is no ordering, then we
may have to compare every key to search for a given key.
Searching a key
For searching a value, if we had a sorted array we could have performed a binary search. Let’s
say we want to search a number in the array what we do in binary search is we first define the
complete list as our search space, the number can exist only within the search space. Now we
compare the number to be searched or the element to be searched with the mid element of the
search space or the median and if the record being searched is lesser we go searching in the left
half else we go searching in the right half, in case of equality we have found the element. In
binary search we start with ‘n’ elements in search space and then if the mid element is not the
element that we are looking for, we reduce the search space to ‘n/2’ and we go on reducing the
search space till we either find the record that we are looking for or we get to only one element in
search space and be done with this whole reduction.
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Search operation in binary search tree will be very similar. Let’s say we want to search for the
number, what we’ll do is we’ll start at the root, and then we will compare the value to be
searched with the value of the root if it’s equal we are done with the search if it’s lesser we know
that we need to go to the left subtree because in a binary search tree all the elements in the left
subtree are lesser and all the elements in the right subtree are greater. Searching an element in the
binary search tree is basically this traversal in which at each step we will go either towards left or
right and hence in at each step we discard one of the sub-trees. If the tree is balanced, we call a
tree balanced if for all nodes the difference between the heights of left and right subtrees is not
greater than one, we will start with a search space of ‘n’nodes and when we will discard one of
the sub-trees we will discard ‘n/2’ nodes so our search space will be reduced to ‘n/2’ and then in
the next
Insertion of a key
A new key is always inserted at the leaf. We start searching a key from the root until we hit a
leaf node. Once a leaf node is found, the new node is added as a child of the leaf node.
100 100
/ \ Insert 40 / \
20 500 ---------> 20 500
/ \ / \
10 30 10 30
\
40
Program:
#include<iostream>
struct node
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
int data;
node *left,*right;
};
class BST
public:
node *root;
BST()
root=NULL;
node *create_BST();
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
};
node * BST::create_BST()
int n, i, x;
cin>>n;
for(i=0;i<n;i++)
cin>>x;
root=insert(root,x);
return root;
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
if(T==NULL)
T=new node;
T->data=x;
T->left=NULL;
T->right=NULL;
return T;
else
if(x>T->data)
T->right=insert(T->right,x);
return T;
if(x<T->data)
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
T->left=insert(T->left,x);
return T;
void BST::display(node * T)
if(T!=NULL)
display(T->left);
cout<<T->data<<" ";
display(T->right);
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
node * BST::findmin(node * T)
while(T->left!=NULL)
T=T->left;
return T;
node * BST::findmax(node * T)
while(T->right!=NULL)
T=T->right;
return T;
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
if(T==NULL)
return NULL;
if(T->data==x)
cout<<"found"<<T->data;
return T;
if (x > T->data )
T=find(T->right,x);
return T;
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
T=find(T->left,x);
return T;
if(T==NULL)
return 0;
else
int main()
BST b1;
int ch,x1;
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
char ans;
int key;
node *temp,*temp1;
do
cin>>ch;
switch(ch)
case 1: b1.root=b1.create_BST();
break;
case 2:
cin>>x1;
b1.root=b1.insert(b1.root,x1);
break;
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
case 3:
b1.display(b1.root);
break;
case 4: temp=b1.findmin(b1.root);
break;
case 5: temp=b1.findmax(b1.root);
break;
cin>>key;
temp1=b1.find(b1.root,key);
if(temp1!=NULL)
cout<<"Present "<<temp1->data;
else
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
break;
case 7: x1=b1.height(b1.root);
break;
cin>>ans;
}while(ans=='y');
return 0;}
Output
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Experiment No-05
Aim Convert given binary tree into threaded binary tree. Analyze time and space complexity
of the algorithm
Prerequisite:
C++ Programming
Idea of Threaded Binary Tree is to make inorder traversal faster and do it without stack and
without recursion. In a simple threaded binary tree, the NULL right pointers are used to store
inorder successor. Where-ever a right pointer is NULL, it is used to store inorder successor.
Following diagram shows an example Single Threaded Binary Tree. The dotted lines represent
threads.
Here we will see the threaded binary tree data structure. We know that the binary tree nodes may
have at most two children. But if they have only one children, or no children, the link part in the
linked list representation remains null. Using threaded binary tree representation, we can reuse
that empty links by making some threads.
If one node has some vacant left or right child area, that will be used as thread. There are two
types of threaded binary tree. The single threaded tree or fully threaded binary tree. In single
threaded mode, there are another two variations. Left threaded and right threaded.
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
In the left threaded mode if some node has no left child, then the left pointer will point to its
inorder predecessor, similarly in the right threaded mode if some node has no right child, then
the right pointer will point to its inorder successor. In both cases, if no successor or predecessor
is present, then it will point to header node.
For fully threaded binary tree, each node has five fields. Three fields like normal binary tree
node, another two fields to store Boolean value to denote whether link of that side is actual link
or thread.
Program
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
struct Node
int key;
bool isThreaded;
};
Program:-
#include<iostream>
using namespace std;
struct TTREE
{
struct TTREE *lc;
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
char lt;
char data;
char rt;
struct TTREE *rc;
};
class myttree
{
private :
ttree *head;
public :
myttree();
void create_btree();
void insert_btree(ttree *);
void thread_btree();
void display_ttree();
void display_btree();
};
myttree :: myttree()
{
head = NULL;
}
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
par->lc = node;
flag = 1;
}
else
par = par->lc;
}
else
{
if(par->rc == NULL)
{
par->rc = node;
flag = 1;
}
else
par = par->rc;
}
}
}
}
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
{
if(head == NULL)
cout<<"\nBinary tree is empty";
else
{
cout<<"Inorder Traversal of the tree : ";
inorder(head);
}
}
int main()
{
int ch;
myttree t1;
do
{
cout<<"\n\t1: Create Binary Tree";
cout<<"\n\t2: Display Binary Tree";
cout<<"\n\t3: Thread the Tree ";
cout<<"\n\t4: Display the threaded tree";
cout<<"\n\t5: Exit";
cout<<"\n\nEnter ur choice : ";
cin>>ch;
switch(ch)
{
case 1 : t1.create_btree();
break;
case 2 : t1.display_btree();
break;
case 3 : t1.thread_btree();
break;
case 4 : t1.display_ttree();
break;
case 5 : cout<<"\nend\n";
break;
default: cout<<"\nTry again\n";
}
}while(ch != 5);
return 0;
}
Output:-
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Experiment No-06
Aim: Represent a given graph using adjacency matrix/list to perform DFS and using adjacency
list to perform BFS. Use the map of the area around the college as the graph. Identify
the prominent land marks as nodes and perform DFS and BFS on that.
Prerequisite:
C++ Programming
Breadth First Search (BFS) has been discussed in this article which uses adjacency list for the
graph representation. In this article, adjacency matrix will be used to represent the graph.
Adjacency matrix representation: In adjacency matrix representation of a graph, the
matrix mat[][] of size n*n (where n is the number of vertices) will represent the edges of the
graph where mat[i][j] = 1 represents that there is an edge between the
vertices i and j while mat[i][j] = 0 represents that there is no edge between the vertices i and j.
Below is the adjacency matrix representation of the graph shown in the above image:
0123
00110
11001
21000
30100
Input: source = 0
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Output: 0 1 2 3
Input: source = 1
Output:1 0 2 3 4
DFS has been discussed in this article which uses adjacency list for the graph representation. In
this article, adjacency matrix will be used to represent the graph.
Adjacency matrix representation: In adjacency matrix representation of a graph, the
matrix mat[][] of size n*n (where n is the number of vertices) will represent the edges of the
graph where mat[i][j] = 1 represents that there is an edge between the
vertices i and j while mat[i][i] = 0 represents that there is no edge between the vertices i and j.
Below is the adjacency matrix representation of the graph shown in the above image:
01234
0 01111
1 10000
2 10000
3 10000
4 10000
Examples:
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Input: source = 0
Output: 0 1 3 2
Input: source = 0
Output: 0 1 2 3 4
Program
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
// Adjacency List - Adding O(1), Lookup O(N), Space O(N^2) but usually better.
// Each vector position represents a node - the vector inside that position represents that node's
friends.
vector< vector<int> > FormAdjList()
{
// Our adjacency list.
vector< vector<int> > adjList;
// We have 10 vertices, so initialize 10 rows.
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
const int n = 9;
for(int i = 0; i < n; i++)
{
// Create a vector to represent a row, and add it to the adjList.
vector<int> row;
adjList.push_back(row);
}
// Now "adjList[0]" has a vector<int> in it that represents the friends of vertex 1.
// (Remember, we use 0-based indexing. 0 is the first number in our vector, not 1.
// Now let's add our actual edges into the adjacency list.
// See the picture here: https://www.srcmake.com/uploads/5/3/9/0/5390645/adjl_4_orig.png
adjList[0].push_back(2);
adjList[0].push_back(4);
adjList[0].push_back(6);
adjList[1].push_back(4);
adjList[1].push_back(7);
adjList[2].push_back(0);
adjList[2].push_back(5);
adjList[3].push_back(4);
adjList[3].push_back(5);
adjList[4].push_back(1);
adjList[4].push_back(3);
adjList[4].push_back(0);
adjList[5].push_back(2);
adjList[5].push_back(3);
adjList[5].push_back(8);
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
adjList[6].push_back(0);
adjList[7].push_back(1);
adjList[8].push_back(5);
// Our graph is now represented as an adjacency list.
return adjList;
}
// Adjacency Matrix - Adding O(N), Lookup O(1), Space O(N^2)
vector< vector<int> > FormAdjMatrix()
{
// We could use an array for the adjMatrix if we knew the size, but it's safer to use a vector.
vector< vector<int> > adjMatrix;
// Initialize the adjMatrix so that all vertices can visit themselves.
// (Basically, make an identity matrix.)
const int n = 9;
for(int i = 0; i < n; i++)
{
// Initialize the row.
vector<int> row;
adjMatrix.push_back(row);
// Set the row to have all 0's. (Except the vertex ing itself.)
for(int j = 0; j < n; j++)
{
int value = 0;
if(i == j)
{ value = 1; }
adjMatrix[i].push_back(value);
}
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
}
// Our matrix is set up, we just need to set up the edges (vertex connections).
// See this image: https://www.srcmake.com/uploads/5/3/9/0/5390645/adjm_2_orig.png
adjMatrix[0][2] = 1;
adjMatrix[2][0] = 1;
adjMatrix[0][4] = 1;
adjMatrix[4][0] = 1;
adjMatrix[0][6] = 1;
adjMatrix[6][0] = 1;
adjMatrix[1][4] = 1;
adjMatrix[4][1] = 1;
adjMatrix[1][7] = 1;
adjMatrix[7][1] = 1;
adjMatrix[2][5] = 1;
adjMatrix[5][2] = 1;
adjMatrix[3][4] = 1;
adjMatrix[4][3] = 1;
adjMatrix[3][5] = 1;
adjMatrix[5][3] = 1;
adjMatrix[5][8] = 1;
adjMatrix[8][5] = 1;
// Our adjacency matrix is complete.
return adjMatrix;
}
// Given an Adjacency List, do a BFS on vertex "start"
void AdjListBFS(vector< vector<int> > adjList, int start)
{
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
}
cout << endl << endl;
return;
}
// Given an Adjacency Matrix, do a BFS on vertex "start"
void AdjMatrixBFS(vector< vector<int> > adjMatrix, int start)
{
cout << "\nDoing a BFS on an adjacency list.\n";
int n = adjMatrix.size();
// Create a "visited" array (true or false) to keep track of if we visited a vertex.
bool visited[n] = { false };
// Create a queue for the nodes we visit.
queue<int> q;
// Add the starting vertex to the queue and mark it as visited.
q.push(start);
visited[start] = true;
// While the queue is not empty..
while(q.empty() == false)
{
int vertex = q.front();
q.pop();
// Doing +1 in the cout because our graph is 1-based indexing, but our code is 0-based.
cout << vertex+1 << " ";
// Loop through all of it's friends.
for(int i = 0; i < adjMatrix[vertex].size(); i++)
{
// The neighbor is the column number, and the edge is the value in the matrix.
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
int neighbor = i;
int edge = adjMatrix[vertex][i];
// If the edge is "0" it means this guy isn't a neighbor. Move on.
if(edge == 0) { continue; }
// If the friend hasn't been visited yet, add it to the queue and mark it as visited
if(visited[neighbor] == false)
{
q.push(neighbor);
visited[neighbor] = true;
}
}
}
cout << endl << endl;
return;
}
int main()
{
cout << "Program started.\n";
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
OUTPUT:
/* DFS coding:
// Create a "visited" array (true or false) to keep track of if we visited a vertex.
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
// Each vector position represents a node - the vector inside that position represents that node's
friends.
vector< vector<int> > FormAdjList()
{
// Our adjacency list.
vector< vector<int> > adjList;
// We have 10 vertices, so initialize 10 rows.
const int n = 9;
for(int i = 0; i < n; i++)
{
// Create a vector to represent a row, and add it to the adjList.
vector<int> row;
adjList.push_back(row);
}
// Now let's add our actual edges into the adjacency list.
// See the picture here: https://www.srcmake.com/uploads/5/3/9/0/5390645/adjl_4_orig.png
adjList[0].push_back(2);
adjList[0].push_back(4);
adjList[0].push_back(6);
adjList[1].push_back(4);
adjList[1].push_back(7);
adjList[2].push_back(0);
adjList[2].push_back(5);
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
adjList[3].push_back(4);
adjList[3].push_back(5);
adjList[4].push_back(1);
adjList[4].push_back(3);
adjList[4].push_back(0);
adjList[5].push_back(2);
adjList[5].push_back(3);
adjList[5].push_back(8);
adjList[6].push_back(0);
adjList[7].push_back(1);
adjList[8].push_back(5);
// Our graph is now represented as an adjacency list.
return adjList;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////
// Adjacency Matrix - Adding O(N), Lookup O(1), Space O(N^2)
vector< vector<int> > FormAdjMatrix()
{
// We could use an array for the adjMatrix if we knew the size, but it's safer to use a vector.
vector< vector<int> > adjMatrix;
// Initialize the adjMatrix so that all vertices can visit themselves.
// (Basically, make an identity matrix.)
const int n = 9;
for(int i = 0; i < n; i++)
{
// Initialize the row.
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
vector<int> row;
adjMatrix.push_back(row);
// Set the row to have all 0's. (Except the vertex ing itself.)
for(int j = 0; j < n; j++)
{
int value = 0;
if(i == j)
{ value = 1; }
adjMatrix[i].push_back(value);
}
}
// Our matrix is set up, we just need to set up the edges (vertex connections).
// See this image: https://www.srcmake.com/uploads/5/3/9/0/5390645/adjm_2_orig.png
adjMatrix[0][2] = 1;
adjMatrix[2][0] = 1;
adjMatrix[0][4] = 1;
adjMatrix[4][0] = 1;
adjMatrix[0][6] = 1;
adjMatrix[6][0] = 1;
adjMatrix[1][4] = 1;
adjMatrix[4][1] = 1;
adjMatrix[1][7] = 1;
adjMatrix[7][1] = 1;
adjMatrix[2][5] = 1;
adjMatrix[5][2] = 1;
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
adjMatrix[3][4] = 1;
adjMatrix[4][3] = 1;
adjMatrix[3][5] = 1;
adjMatrix[5][3] = 1;
adjMatrix[5][8] = 1;
adjMatrix[8][5] = 1;
// Our adjacency matrix is complete.
return adjMatrix;
}
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
// Recursively visit vertices.
void AdjListDFS(vector< vector<int> > &adjList, int &vertex, vector<bool> &visited)
{
// Mark the vertex as visited.
visited[vertex] = true;
// Outputting vertex+1 because that's the way our graph picture looks.
cout << vertex+1 << " ";
// Look at this vertex's neighbors.
for(int i = 0; i < adjList[vertex].size(); i++)
{
int neighbor = adjList[vertex][i];
// Recursively call DFS on the neighbor, if it wasn't visited.
if(visited[neighbor] == false)
{
AdjListDFS(adjList, neighbor, visited);
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
}
}
}
// Given an Adjacency List, do a BFS on vertex "start"
void AdjListDFSInitialize(vector< vector<int> > &adjList, int start)
{
cout << "\nDoing a DFS on an adjacency list.\n";
int n = adjList.size();
// Create a "visited" array (true or false) to keep track of if we visited a vertex.
vector<bool> visited;
for(int i = 0; i < n; i++)
{
visited.push_back(false);
}
AdjListDFS(adjList, start, visited);
cout << endl << endl;
return;
}
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
// Recursively visit vertices.
void AdjMatrixDFS(vector< vector<int> > &adjMatrix, int &vertex, vector<bool> &visited)
{
// Mark the vertex as visited.
visited[vertex] = true;
// Outputting vertex+1 because that's the way our graph picture looks.
cout << vertex+1 << " ";
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
return 0;
}
//////////////////////////////////////////////////////////////////////////////
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Experiment No-07
Aim:-There are flight paths between cities. If there is a flight between city A and city B then
there is an edge between the cities. The cost of the edge can be the time that flight take to reach
city B from A, or the amount of fuel used for the journey. Represent this as a graph. The node
can be represented by airport name or name of the city. Use adjacency list representation of the
graph or use adjacency matrix representation of the graph.
Check whether the graph is connected or not. Justify the storage representation used.
Prerequisite:
C++ Programming
Theory:
A graph is a data structure that consists of the following two components:
1. A finite set of vertices also called as nodes.
2. A finite set of ordered pair of the form (u, v) called as edge. The pair is ordered because (u, v)
is not the same as (v, u) in case of a directed graph(di-graph). The pair of the form (u, v)
indicates that there is an edge from vertex u to vertex v. The edges may contain
weight/value/cost.
Graphs are used to represent many real-life applications: Graphs are used to represent networks.
The networks may include paths in a city or telephone network or circuit network. Graphs are
also used in social networks like linkedIn, Facebook. For example, in Facebook, each person is
represented with a vertex(or node). Each node is a structure and contains information like person
id, name, gender, and locale. See this for more applications of graph.
Following is an example of an undirected graph with 5 vertices.
The following two are the most commonly used representations of a graph.
1. Adjacency Matrix
2. Adjacency List
There are other representations also like, Incidence Matrix and Incidence List. The choice of
graph representation is situation-specific. It totally depends on the type of operations to be
performed and ease of use.
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Adjacency Matrix:
Adjacency Matrix is a 2D array of size V x V where V is the number of vertices in a graph. Let
the 2D array be adj[][], a slot adj[i][j] = 1 indicates that there is an edge from vertex i to vertex j.
Adjacency matrix for undirected graph is always symmetric. Adjacency Matrix is also used to
represent weighted graphs. If adj[i][j] = w, then there is an edge from vertex i to vertex j with
weight w.
Adjacency List:
An array of lists is used. The size of the array is equal to the number of vertices. Let the array
be an array[]. An entry array[i] represents the list of vertices adjacent to the ith vertex. This
representation can also be used to represent a weighted graph. The weights of edges can be
represented as lists of pairs. Following is the adjacency list representation of the above graph.
Program
#include<iostream>
using namespace std;
struct node
{
string data;
int fuel;
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
node *next;
};
class graph1
{
public:
node * Head[10];
int v,e;
void create();
void display();
void edge();
};
void graph1::create()
{
cout<<"How many Vertices : ";
cin>>v;
cout<<"Enter Name of Cities : \n ";
for(int i=0;i<v;i++)
{
Head[i]=new node;
cin>>Head[i]->data;
Head[i]->next=NULL;
}
void graph1::display()
{
node *n2;
for(int i=0;i<v;i++)
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
{
cout<<"\nSource :"<<Head[i]->data;
n2=Head[i]->next;
while(n2!=NULL)
{
cout<<" Dest : "<<n2->data;
cout<<" Fuel Required : "<<n2->fuel;
n2=n2->next;
}}}
void graph1::edge()
{
int i,j;
string s,d;
node *n1 ,*temp;
cout<<"How many Edges : ";
cin>>e;
for( i=0;i<e;i++)
{
cout<<"Enter Source n Dest :";
cin>>s>>d;
for(j=0;j<v;j++)
{
if(s==Head[j]->data)
break; }
n1=new node;
n1->data=d;
cout<<"\n Enter Fuel Required : ";
cin>>n1->fuel;
n1->next=NULL;
temp=Head[j];
while(temp->next!=NULL)
{
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
temp=temp->next;
}
temp->next=n1;
}}
int main()
{
graph1 g1;
g1.create();
g1.edge();
g1.display();
return 0;
}
Output
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Experiment No-08
Aim: Given sequence k = k1 <k2 < … <kn of n sorted keys, with a search probability pi for each key ki .
Build the Binary search tree that has the least search cost given the access probability for each
key?
Prerequisite:
C++ Programming
Input: BST
Theory:
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
20 10 12 12
I II III IV V
Among all possible BSTs, cost of the fifth BST is minimum.
Cost of the fifth BST is 1*50 + 2*34 + 3*8 = 142
1) Optimal Substructure:
The optimal cost for freq[i..j] can be recursively calculated using the following formula.
We need to calculate optCost(0, n-1) to find the result.
The idea of above formula is simple, we one by one try all nodes as root (r varies from i
to j in second term). When we make rth node as root, we recursively calculate optimal
cost from i to r-1 and r+1 to j.
We add sum of frequencies from i to j (see first term in the above formula), this is added
because every search will go through root and one comparison will be done for every
search.
Program
#include<iostream>
using namespace std;
#define MAX 10
int find(int,int);
void print(int,int);
int p[MAX],q[MAX],w[10][10],c[10][10],r[10][10],i,j,k,n,m;
char idnt[7][10];
int main()
{
cout<<"enter a number of identifiers : ";
cin>>n;
cout<<"enter idntifiers : ";
for(i=1;i<=n;i++)
cin>>idnt[i];
cout<<"enter success probability for identifiers : ";
for(i=1;i<=n;i++)
cin>>p[i];
for(i=0;i<=n;i++)
cin>>q[i];
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
for(i=0;i<=n;i++)
w[i][i]=q[i];
c[i][i]=r[i][i]=0;
for(i=0;i<n;i++)
j=i+1;
w[i][j]=q[i]+q[j]+p[j];
c[i][j]=q[i]+c[i][j-1]+c[j][j];
r[i][j]=j;
cout<<"\n"<<w[i][j]<<" "<<c[i][j]<<" "<<r[i][j];
for(m=2;m<=n;m++)
for(i=0;i<=n-m;i++)
j=i+m;
w[i][j]=w[i][j-1]+p[i]+q[j];
k=find(i,j);
r[i][j]=k;
c[i][j]=w[i][j]+c[i][k-1]+c[k][j];
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
return 0;
int min=2000,m,l;//c[i][j];
for(m=i+1;m<=j;m++)
if(c[i][m-1]+c[m][j]<min)
min=c[i][m-1]+c[m][j];
l=m;
return l;
if(i<j)
cout<<"\n"<<idnt[r[i][j]];
else
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
return;
print(i,r[i][j]-1);
print(r[i][j],j);
output
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Experiment No:-09
Aim:-
A Dictionary stores keywords and its meanings. Provide facility for adding new keywords,
deleting keywords, updating values of any entry. Provide facility to display whole data sorted in
ascending/ Descending order. Also find how many maximum comparisons may require for
finding any keyword. Use Height balance tree and find the complexity for finding a keyword.
Prerequisite:
C++ Programming
Theory
The height of a binary tree is the number of edges between the tree's root and its furthest leaf.
Function Description
Complete the getHeight or height function in the editor. It must return the height of a binary tree
as an integer.
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Note -The Height of binary tree with single node is taken as zero.
Input Format
The first line contains an integer , the number of nodes in the tree.
Next line contains space separated integer where th integer denotes node[i].data.
Note: Node values are inserted into a binary search tree before a reference to the tree's root node
is passed to your function. In a binary search tree, all nodes on the left branch of a node are less
than the node value. All values on the right branch are greater than the node value.
Constraints
Output Format
Your function should return a single integer denoting the height of the binary tree.
Sample Input
Sample Output
3
Explanation
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
There are nodes in this path that are connected by edges, meaning our binary tree's .
Program
#include<iostream>
#include<string.h>
using namespace std;
class dict
{
dict *root,*node,*left,*right,*tree1;
string s1,s2;
int flag,flag1,flag2,flag3,cmp;
public:
dict()
{
flag=0,flag1=0,flag2=0,flag3=0,cmp=0;
root=NULL;
}
void input();
void create_root(dict*,dict*);
void check_same(dict*,dict*);
void input_display();
void display(dict*);
void input_remove();
dict* remove(dict*,string);
dict* findmin(dict*);
void input_find();
dict* find(dict*,string);
void input_update();
dict* update(dict*,string);
};
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
void dict::input()
{
node=new dict;
cout<<"\nEnter the keyword:\n";
cin>>node->s1;
cout<<"Enter the meaning of the keyword:\n";
cin.ignore();
getline(cin,node->s2);
create_root(root,node);
}
void dict::create_root(dict *tree,dict
*node1)
{
int i=0,result;
char a[20],b[20];
if(root==NULL)
{
root=new dict;
root=node1;
root->left=NULL;
root->right=NULL;
cout<<"\nRoot node created
successfully"<<endl;
return;
}
for(i=0;node1->s1[i]!='\0';i++)
{
a[i]=node1->s1[i];
}
for(i=0;tree->s1[i]!='\0';i++)
{
b[i]=tree->s1[i];
}
result=strcmp(b,a);
check_same(tree,node1);
if(flag==1)
{
cout<<"The word you entered
already exists.\n";
flag=0;
}
else
{
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
if(result>0)
{
if(tree->left!=NULL)
{
create_root(tree->left,node1);
}
else
{
tree->left=node1;
(tree->left)->left=NULL;
(tree->left)->right=NULL;
cout<<"Node added to left of "<<tree-
>s1<<"\n";
return;
}
}
else if(result<0)
{
if(tree->right!=NULL)
{
create_root(tree->right,node1);
}
else
{
tree->right=node1;
(tree->right)->left=NULL;
(tree->right)->right=NULL;
cout<<"Node added to right of
"<<tree->s1<<"\n";
return;
}
}
}
}
void dict::check_same(dict *tree,dict *node1)
{
if(tree->s1==node1->s1)
{
flag=1;
return;
}
else if(tree->s1>node1->s1)
{
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
if(tree->left!=NULL)
{
check_same(tree->left,node1);
}
}
else if(tree->s1<node1->s1)
{
if(tree->right!=NULL)
{
check_same(tree->right,node1);
}
}
}
void dict::input_display()
{
if(root!=NULL)
{
cout<<"The words entered in the dictionary
are:\n\n";
display(root);
}
else
{
cout<<"\nThere are no words in the dictionary.\n";
}
}
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
>s2<<"\n\n";
if(tree->right!=NULL)
{
display(tree->right);
}
}
}
void dict::input_remove()
{
char t;
if(root!=NULL)
{
cout<<"\nEnter a keyword to be deleted:\n";
cin>>s1;
remove(root,s1);
if(flag1==0)
{
cout<<"\nThe word '"<<s1<<"' has been deleted.\n";
}
flag1=0;
}
else
{
cout<<"\nThere are no words in the dictionary.\n";
}
}
dict* dict::remove(dict *tree,string s3)
{
dict *temp;
if(tree==NULL)
{
cout<<"\nWord not found.\n";
flag1=1;
return tree;
}
else if(tree->s1>s3)
{
tree->left=remove(tree->left,s3);
return tree;
}
else if(tree->s1<s3)
{
tree->right=remove(tree->right,s3);
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
return tree;
}
else
{
if(tree->left==NULL&&tree->right==NULL)
{
delete tree;
tree=NULL;
}
else if(tree->left==NULL)
{
temp=tree;
tree=tree->right;
delete temp;
}
else if(tree->right==NULL)
{
temp=tree;
tree=tree->left;
delete temp;
}
else
{
temp=findmin(tree->right);
tree=temp;
tree->right=remove(tree->right,temp->s1);
}
}
return tree;
}
dict* dict::findmin(dict *tree)
{
while(tree->left!=NULL)
{
tree=tree->left;
}
return tree;
}
void dict::input_find()
{
flag2=0,cmp=0;
if(root!=NULL)
{
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
{
cmp++;
find(tree->right,s3);
}
}
return tree;
}
void dict::input_update()
{
if(root!=NULL)
{
cout<<"\nEnter the keyword to be updated:\n";
cin>>s1;
update(root,s1);
}
else
{
cout<<"\nThere are no words in the dictionary.\n";
}
}
dict* dict::update(dict *tree,string s3)
{
flag3=0;
find(tree,s3);
if(flag3==0)
{
cout<<"\nEnter the updated meaning of the keyword:\n";
cin.ignore();
getline(cin,tree1->s2);
cout<<"\nThe meaning of '"<<s3<<"' has been
updated.\n";
}
return tree;
}
int main()
{
int ch;
dict d;
do
{
cout<<"\n==========================================\n"
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
"\n********DICTIONARY***********:\n"
"\nEnter your choice:\n"
"1.Add new keyword.\n"
"2.Display the contents of the
Dictionary.\n"
"3.Delete a keyword.\n"
"4.Find a keyword.\n"
"5.Update the meaning of a
keyword.\n"
"6.Exit.\n"
"===============================================\n";
cin>>ch;
switch(ch)
{
case 1:d.input();
break;
case 2:d.input_display();
break;
case 3:d.input_remove();
break;
case 4:d.input_find();
break;
case 5:d.input_update();
break;
default:cout<<"\nPlease enter a valid
option!\n";
break;
}
}while(ch!=6);
return 0;
}
Output
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Experiment No-10
Aim:- Implement the Heap/Shell sort algorithm implemented in Java demonstrating heap/shell
data structure with modularity of programming language
Prerequisite:
JAVA
Objectives:
1. To understand concept of heap in data structure.
2. To understand concept & features of java language.
Theory:
Heap Sort:
A Binary Heap is a Complete Binary Tree where items are stored in a special order such that
value in a parent node is greater(or smaller) than the values in its two children nodes. The former
is called as max heap and the latter is called min heap. The heap can be represented by binary
tree or array.
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Algorithm:
STEP 1: Logically, think the given array as Complete Binary Tree,
STEP 2: For sorting the array in ascending order, check whether the tree is satisfying Max-heap
property at each node, (For descending order, Check whether the tree is satisfying Min-heap
property) Here we will be sorting in Ascending order,
STEP 3: If the tree is satisfying Max-heap property, then largest item is stored at the root of the
heap. (At this point we have found the largest element in array, Now if we place this element at
the end(nth position) of the array then 1 item in array is at proper place.)
We will remove the largest element from the heap and put at its proper place(nth position) in
array.
After removing the largest element, which element will take its place? We will put last element
of the heap at the vacant place. After placing the last element at the root, The new tree formed
may or may not satisfy max-heap property. So, If it is not satisfying max-heap property then first
task is to make changes to the tree, So that it satisfies max-heap property.
(Heapify process: The process of making changes to tree so that it satisfies max-heap property is
called heapify)
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
When tree satisfies max-heap property, again largest item is stored at the root of the heap. We
will remove the largest element from the heap and put at its proper place(n-1 position) in array.
Repeat step 3 until size of array is 1 (At this point all elements are sorted.)
Program:-
int n = arr.length;
heapify(arr, n, i);
arr[0] = arr[i];
arr[i] = temp;
heapify(arr, i, 0);
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
largest = l;
largest = r;
if (largest != i) {
arr[i] = arr[largest];
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
arr[largest] = swap;
heapify(arr, n, largest);
int n = arr.length;
System.out.println();
// Driver code
int n = arr.length;
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
ob.sort(arr);
printArray(arr); }}
Output
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Experiment No:-11
Aim:
Company maintains employee information as employee ID, name, designation and salary.
Allow user to add, delete information of employee. Display information of particular employee.
If employee does not exist an appropriate message is displayed. If it is, then the system displays
the employee details. Use index sequential file to maintain the data.
Prerequisite:
C++ Programming
ISAM method is an advanced sequential file organization. In this method, records are stored in
the file using the primary key. An index value is generated for each primary key and mapped
with the record. This index contains the address of the record in the file.If any record has to be
retrieved based on its index value, then the address of the data block is fetched and the record is
retrieved from the memory.
Pros of ISAM:
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
o In this method, each record has the address of its data block, searching a record in a huge
database is quick and easy.
o This method supports range retrieval and partial retrieval of records. Since the index is
based on the primary key values, we can retrieve the data for the given range of value. In
the same way, the partial value can also be easily searched, i.e., the student name starting
with 'JA' can be easily searched.
Cons of ISAM
o This method requires extra space in the disk to store the index value.
o When the new records are inserted, then these files have to be reconstructed to maintain
the sequence.
o When the record is deleted, then the space used by it needs to be released. Otherwise, the
performance of the database will slow down.
Program:-
#include<iostream>
#include<iomanip>
#define max 10
// Structure of Employee
struct employee {
string name;
string designation;
int salary;
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
};
// of the Array
employee emp[max];
void insert()
num++;
cout<<"Salary: ";
cin>>emp[num].salary;
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
else {
void deleteIndex(int i)
return;
void displayAllRecords(){
if(num == -1){
return;
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
else{
cout<<endl<<setw(5)<<"ID"<<setw(10)<<"NAME"<<setw(18)<<"DESIGNATION"<<setw(10
)<<"SALARY\n";
cout<<setw(5)<<emp[i].employee_id<<setw(10)<<emp[i].name<<setw(18)<<emp[i].designatio
n<<setw(10)<<emp[i].salary<<endl;
} }}
void deleteRecord()
int employee_id;
if (emp[i].employee_id == employee_id) {
deleteIndex(i);
num--;
break;
} }}
void searchRecord()
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
int employee_id;
if (emp[i].employee_id == employee_id) {
cout<<endl<<setw(5)<<"ID"<<setw(10)<<"NAME"<<setw(18)<<"DESIGNATION"<<setw(10
)<<"SALARY\n";
cout<<setw(5)<<emp[i].employee_id<<setw(10)<<emp[i].name<<setw(18)<<emp[i].designatio
n<<setw(10)<<emp[i].salary<<endl;
return;
// Driver Code
int main()
int option = 0;
while(option != 5){
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
switch(option){
case 1:
insert();
break;
case 2:
displayAllRecords();
break;
case 3:
deleteRecord();
break;
case 4:
searchRecord();
break;
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
case 5:
break;
default:
break;
} }
return 0;
Output
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Experiment NO-12
Aim :Department maintains a student information. The file contains roll number, name, division
and address. Allow user to add, delete information of student. Display information of particular
employee. If record of student does not exist an appropriate message is displayed. If it is, then
the system displays the student details. Use sequential file to main the data
Prerequisite: C++
Input: File
Theory :
Attributes of a File
Protection. This controls and assigns the power of reading, writing, executing.
Time, date, and user identification. This is the data for protection, security, and usage
monitoring.
The way that files are accessed and read into memory is determined by Access methods. Usually
a single access method is supported by systems while there are OS's that support multiple access
methods.
1. Sequential Access
Write command allocate space for the record and move the pointer to the new End Of
File.
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
2. Direct Access
There are no restrictions on which blocks are read/written, it can be dobe in any order.
"n" is a number relative to the beginning of file, not relative to an absolute physical disk
location.
What is a Directory?
Information about files is maintained by Directories. A directory can contain multiple files. It can
even have directories inside of them. In Windows we also call these directories as folders.
Location : Device and location on the device where the file header is located.
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
FILE DIRECTORIES:
Collection of files is a file directory. The directory contains information about the files,
including attributes, location and ownership. Much of this information, especially that is
concerned with storage, is managed by the operating system. The directory is itself a file,
accessible by various file management routines.
Naming problem: Users cannot have same name for two files.
Grouping problem: Users cannot group files according to their need.
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
TWO-LEVEL DIRECTORY
In this separate directories for each user is maintained.
Path name:Due to two levels there is a path name for every file to locate that file.
Now,we can have same file name for different user.
Searching is efficient in this method.
TREE-STRUCTURED DIRECTORY :
Directory is maintained in the form of a tree. Searching is efficient and also there is grouping
capability. We have absolute or relative path name for a file.
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
1. Continuous Allocation: A single continuous set of blocks is allocated to a file at the time of
file creation. Thus, this is a pre-allocation strategy, using variable size portions. The file
allocation table needs just a single entry for each file, showing the starting block and the length
of the file. This method is best from the point of view of the individual sequential file. Multiple
blocks can be read in at a time to improve I/O performance for sequential processing. It is also
easy to retrieve a single block. For example, if a file starts at block b, and the ith block of the
file is wanted, its location on secondary storage is simply b+i-1.
Disadvantage
External fragmentation will occur, making it difficult to find contiguous blocks of space of
sufficient length. Compaction algorithm will be necessary to free up additional space on
disk.
Also, with pre-allocation, it is necessary to declare the size of the file at the time of
creation.
2. Linked Allocation(Non-contiguous allocation) : Allocation is on an individual block basis.
Each block contains a pointer to the next block in the chain. Again the file table needs just a
single entry for each file, showing the starting block and the length of the file. Although pre-
allocation is possible, it is more common simply to allocate blocks as needed. Any free block
can be added to the chain. The blocks need not be continuous. Increase in file size is always
possible if free disk block is available. There is no external fragmentation because only one
block at a time is needed but there can be internal fragmentation but it exists only in the last
disk block of file.
Disadvantage:
Internal fragmentation exists in last disk block of file.
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Program
#include<iostream>
#include<fstream>
#include<string.h>
class student
int roll;
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
char name[10];
char div;
char add[10];
}stud;
stud rec;
public:
void create();
void display();
int search();
void Delete();
};
void student::create()
char ans;
ofstream fout;
fout.open("stud.dat",ios::out|ios::binary);
do
cin>>rec.roll;
cin>>rec.name;
cin>>rec.div;
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
cin>>rec.add;
fout.write((char *)&rec,sizeof(stud))<<flush;
cin>>ans;
}while(ans=='y'||ans=='Y');
fout.close();
void student::display()
ifstream fin;
fin.open("stud.dat",ios::in|ios::binary);
fin.seekg(0,ios::beg);
cout<<"\n\tRoll\tName\tDiv\tAddress";
while(fin.read((char *)&rec,sizeof(stud)))
if(rec.roll!=-1)
cout<<"\n\t"<<rec.roll<<"\t"<<rec.name<<"\t"<<rec.div<<"\t"<<rec.add;
fin.close();
int student::search()
int r,i=0;
ifstream fin;
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
fin.open("stud.dat",ios::in|ios::binary);
fin.seekg(0,ios::beg);
cin>>r;
while(fin.read((char *)&rec,sizeof(stud)))
if(rec.roll==r)
cout<<"\n\tRecord Found...\n";
cout<<"\n\tRoll\tName\tDiv\tAddress";
cout<<"\n\t"<<rec.roll<<"\t"<<rec.name<<"\t"<<rec.div<<"\t"<<rec.add;
return i;
i++;
fin.close();
return 0;
void student::Delete()
int pos;
pos=search();
fstream f;
f.open("stud.dat",ios::in|ios::out|ios::binary);
f.seekg(0,ios::beg);
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
if(pos==0)
return;
int offset=pos*sizeof(stud);
f.seekp(offset);
rec.roll=-1;
strcpy(rec.name,"NULL");
rec.div='N';
strcpy(rec.add,"NULL");
f.write((char *)&rec,sizeof(stud));
f.seekg(0);
f.close();
cout<<"\n\tRecord Deleted";
int main()
student obj;
int ch,key;
char ans;
do
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
cin>>ch;
switch(ch)
case 1: obj.create();
break;
case 2: obj.display();
break;
case 3: obj.Delete();
break;
case 4: key=obj.search();
if(key==0)
break;
case 5:
break;
cin>>ans;
}while(ans=='y'||ans=='Y');
return 1;
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Output
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Mini project
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Experiment No-13
(Mini Project)
Aim: Design a mini project to implement Snake and Ladders Game using Python.
Prerequisite:
Python
Theory:
This article covers designing a complete Snake and Ladder game using object-oriented
programming (Python OOP) principles with the following rules and requirements. Below we
will discuss the rules of the game:
1. Here we create a board of size 10 and dice of side 6.
2. Each player puts their counter on the board at starting position at 1 and takes turns to roll
the dice.
3. Move your counter forward the number of spaces shown on the dice.
4. If your counter lands at the bottom of a ladder, you can move up to the top of the ladder. If
your counter lands on the head of a snake, you must slide down to the bottom of the snake.
5. Each player will get a fair chance to roll the dice.
6. On the dice result of 6, the user gets one more chance to roll the dice again. However, the
same user can throw the dice a maximum of 3 times.
Note: if the result of the dice is 6,6,6 the user can not throw the dice again as the maximum
attempts are over and the next user will get to throw the dice.
7. When the user rolls dice and it leads to an invalid move, the player should remain in the
same position.
Ex: when the user is in position 99 and rolling of dice yields any number more than one the
user remains in the same position.
8. Print the ranks of users who finished first, second, and so on…
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
Step 1: Define Game Player Class. This class encapsulates a player’s properties like _id, rank,
and its current_position on board.
Step 2: Define the Moving Entity class. This class can be extended by anything that can move
the player to another position, like a Snake or ladder. This is done in order to keep code
extensible and abstract common behavior like end position. We can define this class using
fixed end_position for a moving entity or can override the get_end_pos() function in order to
get dynamic end_pos as well.
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
2. Board also provides the next position from a given position. In this case, if the player lands
on 10, and the board knows there is a snake at 10, it will return the end_pos of the snake. If
no moving entity is present on the position, then just return the position itself.
Step 5: Define the Dice class as it contains a side and exposes a roll method, which returns a
random value from 1 to 6.
Step 6: In this step we will define Game class and its functions as below points:
1. The Game class encapsulates everything needed to play the game i.e. players, dice, and
board. Here we have last_rank(which is the last rank achieved in the game currently i.e. no
of players finished playing), and we have a turn that states which player turn it is.
2. The game can be initialized using the initialize_game() function, which needs a board
object, dice sides, and no_of_players.
3. The game can be played by calling the play() function:
1. The game is not finished until the last rank assigned to the player is not equal to the
total players, this is checked by can_play().
2. The get_next_player() is used to get the next player to play, which is the player which
has the current turn. In case the current turn player has already won, it returns the next
player which still has not reached the last position
3. The dice roll is done in order to get the dice result.
4. Using the board we get the next position of the player.
5. If the next position is valid, i.e. within bounds(this is checked by can_move()), we
change the player position to the next position
6. The next position for the player is set by move_player(), here we also check if the
player is at the last position, so we assign the rank as well.
7. Next, we change the turn using change_turn(), here we will only change the turn if the
current dice roll does not deal 6 or we have crossed the consecutive 3 6’s limit
8. We print the game state using print_game_state(), which prints all player and their
current positions and move back to step 1.
9. After all, players have finished playing, we print the final game state i.e. ranks of each
player using print_game_result()
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
In the code below, there is a sample_run() function defined, which will start the game basis
the current configuration defined. We can change the configurations as per our liking and start
a new game using any size of the board, any size of dice, and any number of players.
class GamePlayer:
"""
"""
self._id = _id
self.rank = -1
self.position = 1
self.position = pos
self.rank = rank
def get_pos(self):
return self.position
def get_rank(self):
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
return self.rank
class MovingEntity:
"""
"""
self.end_pos = end_pos
self.desc = None
self.desc = None
def get_end_pos(self):
if self.end_pos is None:
raise Exception("no_end_position_defined")
return self.end_pos
class Snake(MovingEntity):
"""Snake entity"""
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
super(Snake, self).__init__(end_pos)
class Ladder(MovingEntity):
"""Ladder entity"""
super(Ladder, self).__init__(end_pos)
class Board:
"""
"""
self.size = size
self.board = {}
def get_size(self):
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
return self.size
self.board[pos] = moving_entity
return player_pos
return player_pos
print(f'{self.board[player_pos].desc} at {player_pos}')
return self.board[player_pos].get_end_pos()
if pos == self.size:
return True
return False
class Dice:
self.sides = sides
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
def roll(self):
import random
return ans
class Game:
def __init__(self):
self.board = None
self.dice = None
self.players = []
# curr turn
self.turn = 0
self.winner = None
self.last_rank = 0
self.consecutive_six = 0
"""
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
"""
self.board = board
self.dice = Dice(dice_sides)
def can_play(self):
if self.last_rank != len(self.players):
return True
return False
def get_next_player(self):
"""
"""
while True:
if self.players[self.turn].get_rank() == -1:
return self.players[self.turn]
curr_player.set_position(next_pos)
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
if self.board.at_last_pos(curr_player.get_pos()):
curr_player.set_rank(self.last_rank + 1)
self.last_rank += 1
return True
return False
if dice_result != 6 or self.consecutive_six == 3:
if self.consecutive_six == 3:
else:
def play(self):
"""
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
game will be player until all players have not been assigned a rank
# roll dice
# change turn
Note: Currently everything is automated, ie. dice roll input is not taken from user.
"""
while self.can_play():
curr_player = self.get_next_player()
player_input = input(
dice_result = self.dice.roll()
print(f'dice_result: {dice_result}')
_next_pos = self.board.get_next_pos(
curr_player.get_pos() + dice_result)
if self.can_move(curr_player, _next_pos):
self.move_player(curr_player, _next_pos)
self.change_turn(dice_result)
self.print_game_state()
self.print_game_result()
def print_game_state(self):
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
print('-------------game state-------------')
print('-------------game state-------------\n\n')
def print_game_result(self):
print('-------------final result-------------')
def sample_run():
board = Board(10)
board.set_moving_entity(7, Snake(2))
board.set_moving_entity(4, Ladder(6))
game = Game()
game.initialize_game(board, 6, 2)
game.play()
sample_run()
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur
output
Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S