0% found this document useful (0 votes)
18 views133 pages

DSA MANUAL WITH MINIPROJECT

The document outlines a series of experiments related to data structures and algorithms, focusing on implementations using hashing techniques, binary search trees, and graph representations. It includes objectives, prerequisites, theoretical background, and practical coding examples in C++. The experiments cover various topics such as collision handling, tree construction, and dictionary operations, aimed at enhancing understanding of data management and algorithm efficiency.

Uploaded by

Aditya Salve
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views133 pages

DSA MANUAL WITH MINIPROJECT

The document outlines a series of experiments related to data structures and algorithms, focusing on implementations using hashing techniques, binary search trees, and graph representations. It includes objectives, prerequisites, theoretical background, and practical coding examples in C++. The experiments cover various topics such as collision handling, tree construction, and dictionary operations, aimed at enhancing understanding of data management and algorithm efficiency.

Uploaded by

Aditya Salve
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 133

Sharadchandra Pawar College Of Engineering Otur

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

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.
8 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?
9 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
10 Implement the Heap/Shell sort algorithm implemented in Java
demonstrating heap/shell data structure with modularity of
programming language
11 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

12 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.

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

Objective: To understand the use functions for Collision Handling Technique.

Input: N Number of Clients

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.

Collision Resolution Techniques:


When one or more hash values compete with a single hash table slot, collisions occur. To
resolve this, the next available empty slot is assigned to the current hash value. The most
common methods are open addressing, chaining, probabilistic hashing, perfect hashing and
coalesced hashing technique.

Let’s understand them in more 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;

// Store details : Node-> Key Name Telephone


class node{
private:
string name;
string telephone;
int key;
public:
node(){
key=0;
}

Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur

friend class hashing; // To access the private members of class node


};

// Hashng Fuction that generates different key value


// Sum of ascii value of each character in string
int ascii_generator(string s){
int sum=0;
for (int i = 0; s[i] != '\0'; i++)
sum = sum + s[i];
return sum%100; }
// Class -> Hashing
class hashing{
private:
node data[100]; // Size of directory -> 100
string n;
string tele;
int k, index;
int size=100;
public:
hashing(){
k=0; }
// Function to create record
void create_record(string n,string tele){
k=ascii_generator(n); //using ascii value of string as key
index=k%size;
for (int j=0;j<size;j++){
if(data[index].key==0){
data[index].key=k;
data[index].name=n;
data[index].telephone=tele;
break }

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

cout<<"Enter Telephone number :: ";


cin>>telephone;
s.create_record(name,telephone);
break;
case 2:
s.display_record();
break;
case 3:
cout<<"\nEnter the name :: ";
cin>>name;
s.search_record(name);
break;
case 4:
cout<<"\nEnter the name :: ";
cin>>name;
s.update_record(name);
break;
case 5:
cout<<"\nEnter name to Delete :: ";
cin>>name;
s.delete_record(name);
break;
case 6:
loop=0;
break;
default:
cout<<"\nYou Entered something wrong!";
break;
}}
return 0;
}

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

Objective: To understand the use functions for Collision Handling Technique.

Input: Set of (key, Value ) Pairs keys mapped Value

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.

How to handle Collisions?


There are mainly two methods to handle collision:
1) Separate Chaining
2) Open Addressing
In this article, only separate chaining is discussed. We will be discussing Open addressing in the next
post.

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.

Hashing with Chaining

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 WITHOUT REPLACEMENT

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.

For example, consider elements:

131, 3, 4, 21, 61, 6, 71, 8, 9

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>

using namespace std;

# define max 10

typedef struct list

int data;

struct list *next;

} 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;

for(int i=0; i<max; i++)

root[i]=NULL;

ptr[i]=NULL;

temp[i]=NULL;

void Dictionary::insert(int key)

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];

void Dictionary::search(int key)

int flag=0;

index=int(key%max);

temp[index]=root[index];

while(temp[index]!=NULL)

if(temp[index]->data==key)

cout<<"\nSearch key is found!!";

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)

cout<<"\nsearch key not found.......";

void Dictionary::delete_ele(int key)

index=int(key%max);

temp[index]=root[index];

while(temp[index]->data!=key && temp[index]!=NULL)

ptr[index]=temp[index];

temp[index]=temp[index]->next;

ptr[index]->next=temp[index]->next;

cout<<"\n"<<temp[index]->data<<" has been deleted.";

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";

cout<<"\n2.Search for a value\n3.Delete an value";

cout<<"\nEnter your choice:";

cin>>ch;

switch(ch)

case 1:

cout<<"\nEnter the number of elements to be inserted:";

cin>>n;

cout<<"\nEnter the elements to be inserted:";

for(int i=0; i<n; i++)

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:

cout<<"\nEnter the element to be searched:";

cin>>n;

d.search(n);

case 3:

cout<<"\nEnter the element to be deleted:";

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

Objective: To understand the use Terminology of Tree and Construct a tree

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

Following are the important terms with respect to tree.


 Path − Path refers to the sequence of nodes along the edges of a tree.
 Root − The node at the top of the tree is called root. There is only one root per tree and one path
from the root node to any node.

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.

Print Nodes in Top View of Binary Tree


Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. Given a binary
tree, print the top view of it. The output nodes can be printed in any order.
A node x is there in output if x is the topmost node at its horizontal distance. Horizontal distance of left
child of a node x is equal to horizontal distance of x minus 1, and that of right child is horizontal distance
of x plus 1.
1
/ \
2 3
/ \ /\
4 5 6 7

Top view of the above binary tree is


42137

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

Objective: To understand the use functions for Binary Search Tree

Input: 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

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

Illustration to search 6 in below tree:


1. Start from the root.
2. Compare the searching element with root, if less than root, then recurse for left, else recurse
for right.
3. If the element to search is found anywhere, return true, else return false.

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>

using namespace std;

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();

node * insert(node *, int);

void display(node *);

node * findmin(node *);

node * findmax(node *);

node * find(node *, int );

int height(node *);

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;

cout<<"Enter total number of nodes : ";

cin>>n;

for(i=0;i<n;i++)

cout<<"Enter Data : ";

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

node * BST ::insert(node * T, int x)

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

node * BST::find(node *T, int x)

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;

else if (x < T->data)

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;

int BST::height(node *T)

if(T==NULL)

return 0;

else

return max(height(T->left), height(T->right))+1;

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

cout<<" \n MAIN MENU \n 1. Create \n 2. Insert \n 3.Display \n 4.Findmin \n 5.


Findmax \n 6.Find \n 7. Height";

cout<<"\n\n Enter your choice : ";

cin>>ch;

switch(ch)

case 1: b1.root=b1.create_BST();

break;

case 2:

cout<<"Enter Data : ";

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:

cout<<"THE BST TREE in INORDER : \n ";

b1.display(b1.root);

break;

case 4: temp=b1.findmin(b1.root);

cout<<"\n Min value from BST is :"<<temp->data;

break;

case 5: temp=b1.findmax(b1.root);

cout<<"\n Max value from BST is :"<<temp->data;

break;

case 6: cout<<" \n Enter Key value to be search : ";

cin>>key;

temp1=b1.find(b1.root,key);

if(temp1!=NULL)

cout<<"Present "<<temp1->data;

else

cout<<"\n Key is not Present in BST ";

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);

cout<<" Height of BST tree is : "<<x1-1;

break;

cout<<"\n \n Go to Main Menu ??(y or n) : ";

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

Objective: To Convert general tree to Binary tree.

Input: General tree

Convert a Binary Tree to Threaded binary tree

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.

Following is structure of a single-threaded binary tree.

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.

These are the examples of left and right threaded tree

This is the fully threaded binary tree

Program

Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur

struct Node

int key;

Node *left, *right;

// Used to indicate whether the right pointer is a normal right

// pointer or a pointer to inorder successor.

bool isThreaded;

};

How to convert a Given Binary Tree to Threaded Binary Tree?


We have discussed a Queue-based solution here. In this post, space-efficient solution is
discussed that doesn’t require a queue.
The idea is based on the fact that we link from inorder predecessor to a node. We link those
inorder predecessor which lie in subtree of node. So we find inorder predecessor of a node if its
left is not NULL. Inorder predecessor of a node (whose left is NULL) is a rightmost node in the
left child. Once we find the predecessor, we link a thread from it to the current node.
Following is the implementation of the above idea.

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;
};

typedef struct TTREE ttree;

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;
}

void myttree :: insert_btree(ttree *node)


{
if(head == NULL)
head = node;
else
{
int flag = 0;
char ans;
ttree *par;
par = head;
while(flag == 0)
{
cout<<"\nWhere to add (l/r) of "<<par->data<< " : ";
cin>>ans;
if(ans == 'l')
{
if(par->lc == 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;
}
}
}
}

void myttree :: create_btree()


{
int i,n;
ttree *node;
cout<<"\nEnter the total no. of nodes in btree : ";
cin>>n;
for(i = 1; i<=n; i++)
{
node = new ttree;
node->lc = NULL; node->lt = 'f';
node->rc = NULL; node->rt = 'f';
cout<<"\nEnter the data field of node "<<i<<" : ";
cin>>node->data;
insert_btree(node);
}
cout<<"\nBinary tree created successfully";
}

void preorder(ttree *node, ttree *A[],int & n)


{
if(node != NULL)
{
A[n++] = node;
preorder(node->lc,A,n);
preorder(node->rc,A,n);
}

Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur

void myttree :: thread_btree()


{
ttree *A[20];
ttree *node;
int n = 0,i;
if(head == NULL)
{
cout<<"\nBinary tree is empty";
}
else
{
preorder(head,A,n);
cout<<"\nPreorder traversal is : ";
for(i = 0 ; i < n ;i++)
{
cout<<A[i]->data<<" ";
}
node = new ttree;
node->lt = 'f';
node->lc = head;
node->data = '\0';
node->rt = 't';
node->rc = node;
head = node;
for(i = 0 ; i < n ;i++)
{
if(A[i]->lc == NULL)
{
if(i ==0)
A[i]->lc = head;
else
A[i]->lc = A[i-1];
A[i]->lt = 't';
}
if(A[i]->rc == NULL)
{
if(i == n - 1)
A[i]->rc = head;
else
A[i]->rc = A[i+1];
A[i]->rt = 't';
}
}

Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur

cout<<"\nBinary Tree Threaded successfully\n";


}
}

void myttree :: display_ttree()


{
if(head == NULL)
cout<<"\nBinary tree is empty";
else
{
cout<<"Preorder Traversal of the tree : ";
ttree *temp = head->lc;
while( temp != head)
{
while(temp->lt == 'f')
{
cout<<temp->data<<" ";
temp = temp->lc;
}
cout<<temp->data<<" ";
while(temp->rt == 't' && temp->rc != head)
{
temp = temp->rc;
cout<<temp->data<<" ";
}
if(temp->lt == 'f')
temp = temp->lc;
else
temp = temp->rc;
}
}
}

void inorder(ttree *node)


{
if(node != NULL)
{
inorder(node->lc);
cout<<node->data<<" ";
inorder(node->rc);
}
}

void myttree :: display_btree()

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

Objective: To understand the use functions for DFS and BFS

Input: Insert the elements


Theory

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

Depth First Search (DFS)

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

cout << "\nDoing a BFS 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.
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 < adjList[vertex].size(); i++)
{
// If the friend hasn't been visited yet, add it to the queue and mark it as visited
int neighbor = adjList[vertex][i];
if(visited[neighbor] == false)
{
q.push(neighbor);
visited[neighbor] = true;
}
}

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";

// Get the adjacency list/matrix.


vector< vector<int> > adjList = FormAdjList();
vector< vector<int> > adjMatrix = FormAdjMatrix();

// Call BFS on Vertex 5. (Labeled as 4 in our 0-based-indexing.)


AdjListBFS(adjList, 4);
AdjMatrixBFS(adjMatrix, 4);

Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur

cout << "Program ended.\n";


return 0;
}

OUTPUT:

/* DFS coding:
// Create a "visited" array (true or false) to keep track of if we visited a vertex.

Recursively call DFS(vertex, visited, adjList/Matrix), which for each node...


// Marks it as visited
// Checks for all neighbors...
// Makes a recursive call if the neighbor is not visited.
*/
// The example graph: https://www.srcmake.com/uploads/5/3/9/0/5390645/graph_orig.jpg
#include <iostream>
#include <vector>
using namespace std;
//////////////////////////////////////////////////////////////////////////////////////////////
// Adjacency List - Adding O(1), Lookup O(N), Space O(N^2) but usually better.

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 "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);

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

// Look at this vertex's neighbors.


for(int i = 0; i < adjMatrix[vertex].size(); i++)
{
int edge = adjMatrix[vertex][i];
int neighbor = i;
//cout << "Neighbor: " << i << endl;
// If the edge doesn't exist, move on.
if(edge == 0) { continue; }
// Recursively call DFS on the neighbor, if it wasn't visited.
if(visited[neighbor] == false)
{
AdjMatrixDFS(adjMatrix, neighbor, visited);
}
}
}

// Given an Adjacency Matrix, do a BFS on vertex "start"


void AdjMatrixDFSInitialize(vector< vector<int> > &adjMatrix, int start)
{
cout << "\nDoing a DFS on an adjacency matrix.\n";
int n = adjMatrix.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);
}

Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur

AdjMatrixDFS(adjMatrix, start, visited);


cout << endl << endl;
return;
}
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
int main()
{
cout << "Program started.\n";
// Get the adjacency list/matrix.
vector< vector<int> > adjList = FormAdjList();
vector< vector<int> > adjMatrix = FormAdjMatrix();
// Call BFS on Vertex 5. (Labeled as 4 in our 0-based-indexing.)
AdjListDFSInitialize(adjList, 4);
AdjMatrixDFSInitialize(adjMatrix, 4);
cout << "Program ended.\n";

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

Objective: To understand the use functions for adjacency list representation

Input: graph Image and weight.

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.

The adjacency matrix for the above example graph is:

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

Objective: To understand the use functions for Binary search Tree

Input: BST

Theory:

Optimal Binary Search Tree


Given a sorted array key [0.. n-1] of search keys and an array freq[0.. n-1] of frequency counts,
where freq[i] is the number of searches for keys[i]. Construct a binary search tree of all keys
such that the total cost of all the searches is as small as possible.
Let us first define the cost of a BST. The cost of a BST node is the level of that node multiplied
by its frequency. The level of the root is 1.
Examples:
Input: keys[] = {10, 12}, freq[] = {34, 50}
There can be following two possible BSTs
10 12
\ /
12 10
I II
Frequency of searches of 10 and 12 are 34 and 50 respectively.
The cost of tree I is 34*1 + 50*2 = 134
The cost of tree II is 50*1 + 34*2 = 118
Input: keys[] = {10, 12, 20}, freq[] = {34, 8, 50}
There can be following possible BSTs
10 12 20 10 20
\ / \ / \ /
12 10 20 12 20 10
\ / / \

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];

cout<<"enter failure probability for identifiers : ";

for(i=0;i<=n;i++)

cin>>q[i];

cout<<"\n Weight Cost Root \n";

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;

cout<<"\n"<<w[i][i]<<" "<<c[i][i]<<" "<<r[i][i];

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

cout<<"\n"<<w[i][j]<<" "<<c[i][j]<<" "<<r[i][j];

cout<<"\n THE FINAL OBST IS : \n ";


print(0,n);

return 0;

int find(int i,int j)

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;

void print(int i,int j)

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

Objective: To understand the use functions for height of balance tree

Input: data elements

Theory

The height of a binary tree is the number of edges between the tree's root and its furthest leaf.

For example, the following binary tree is of height :

Function Description

Complete the getHeight or height function in the editor. It must return the height of a binary tree

as an integer.

getHeight or height has the following parameter(s):

 root: a reference to the root of a binary tree.

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

The longest root-to-leaf path is shown below:

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";
}
}

void dict::display(dict *tree)


{
if(tree->left==NULL&&tree-
>right==NULL)
{
cout<<tree->s1<<" = "<<tree-
>s2<<"\n\n";
}
else
{
if(tree->left!=NULL)
{
display(tree->left);
}
cout<<tree->s1<<" = "<<tree-

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

cout<<"\nEnter the keyword to be searched:\n";


cin>>s1;
find(root,s1);
if(flag2==0)
{
cout<<"Number of comparisons needed:
"<<cmp<<"\n";
cmp=0;
}
}
else
{
cout<<"\nThere are no words in the
dictionary.\n";
}
}
dict* dict::find(dict *tree,string s3)
{
if(tree==NULL)
{
cout<<"\nWord not found.\n";
flag2=1;
flag3=1;
cmp=0;
}
else
{
if(tree->s1==s3)
{
cmp++;
cout<<"\nWord
found.\n";
cout<<tree->s1<<":
"<<tree->s2<<"\n";
tree1=tree;
return tree;
}
else if(tree->s1>s3)
{
cmp++;
find(tree->left,s3);
}
else if(tree->s1<s3)

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.

Why array based representation for Binary Heap?


Since a Binary Heap is a Complete Binary Tree, it can be easily represented as array and array
based representation is space efficient. If the parent node is stored at index I, the left child can be
calculated by 2 * I + 1 and right child by 2 * I + 2 (assuming the indexing starts at 0).

Heap Sort Algorithm for sorting in increasing order:


1. Build a max heap from the input data.
2. At this point, the largest item is stored at the root of the heap. Replace it with the last item of
the heap followed by reducing the size of heap by 1. Finally, heapify the root of tree. 3. Repeat
above steps until size of heap is greater than 1.

How to build the heap?


Heapify procedure can be applied to a node only if its children nodes are heapified. So the
heapification must be performed in the bottom up order.
Lets understand with the help of an example:
Input data: 4, 10, 3, 5, 1

Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur

The numbers in bracket represent the indices in the array


representation of data.
Applying heapify procedure to index 1:

Applying heapify procedure to index 0:

The heapify procedure calls itself recursively to build heap


in top down manner.

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:-

public class HeapSort {

public void sort(int arr[])

int n = arr.length;

// Build heap (rearrange array)

for (int i = n / 2 - 1; i >= 0; i--)

heapify(arr, n, i);

// One by one extract an element from heap

for (int i = n - 1; i > 0; i--) {

// Move current root to end

int temp = arr[0];

arr[0] = arr[i];

arr[i] = temp;

// call max heapify on the reduced heap

heapify(arr, i, 0);

Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur

// To heapify a subtree rooted with node i which is

// an index in arr[]. n is size of heap

void heapify(int arr[], int n, int i)

int largest = i; // Initialize largest as root

int l = 2 * i + 1; // left = 2*i + 1

int r = 2 * i + 2; // right = 2*i + 2

// If left child is larger than root

if (l < n && arr[l] > arr[largest])

largest = l;

// If right child is larger than largest so far

if (r < n && arr[r] > arr[largest])

largest = r;

// If largest is not root

if (largest != i) {

int swap = arr[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;

// Recursively heapify the affected sub-tree

heapify(arr, n, largest);

/* A utility function to print array of size n */

static void printArray(int arr[])

int n = arr.length;

for (int i = 0; i < n; ++i)

System.out.print(arr[i] + " ");

System.out.println();

// Driver code

public static void main(String args[])

int arr[] = { 12, 11, 13, 5, 6, 7 };

int n = arr.length;

Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur

HeapSort ob = new HeapSort();

ob.sort(arr);

System.out.println("Sorted array is");

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

Objective: To understand the use index sequential file to

Input: A text file

Theory: Indexed sequential access method (ISAM)

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>

using namespace std;

#define max 10

// Structure of Employee

struct employee {

string name;

long int employee_id;

string designation;

int salary;

Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur

};

int num = -1;

// Array of Employees to store the

// data in the form of the Structure

// of the Array

employee emp[max];

// Function to insert the data into

// given data type

void insert()

if (num < max) {

num++;

cout << "Enter the information of the Employee\n";

cout << "Employee ID: ";

cin >> emp[num].employee_id

cout << "Name: ";

cin >> emp[num].name;

cout << "Designation: ";

cin >> emp[num].designation;

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 {

cout << "Employee Table Full\n";

// Function to delete record at index i

void deleteIndex(int i)

for (int j = i; j < num; j++) {

emp[j].name = emp[j + 1].name;

emp[j].employee_id = emp[j + 1].employee_id;

emp[j].designation = emp[j + 1].designation;

emp[j].salary = emp[j +1].salary;

return;

void displayAllRecords(){

if(num == -1){

cout<<"No records present!\n";

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";

for(int i=0; i<num+1; i++){

cout<<setw(5)<<emp[i].employee_id<<setw(10)<<emp[i].name<<setw(18)<<emp[i].designatio
n<<setw(10)<<emp[i].salary<<endl;

} }}

// Function to delete record

void deleteRecord()

int employee_id;

cout << "Enter the Employee ID to Delete Record: ";

cin >> employee_id;

for (int i = 0; i < num+1; i++) {

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;

cout << "Enter the Employee ID to Search Record: ";

cin >> employee_id;

for (int i = 0; i < num+1; i++) {

// If the data is found

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;

cout<<"Employee record not found.\n";

// Driver Code

int main()

int option = 0;

while(option != 5){

cout << "\n----- Employee Management System -----\n";

Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur

//cout << "Available Options:\n";

cout << "1. Insert New Record\n";

cout << "2. Display all Records\n";

cout << "3. Delete Record\n";

cout << "4. Search Record by Employee ID\n";

cout << "5. Exit\n";

cout<<"Enter your choice: ";

cin >> option;

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:

cout<<"\n***** You have exited *****\n";

break;

default:

cout<<"Enter valid option!\n";

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++

Objective: To understand the files and its operation

Input: File

Theory :

Attributes of a File

Following are some of the attributes of a file :

 Name . It is the only information which is in human-readable form.

 Identifier. The file is identified by a unique tag(number) within file system.

 Type. It is needed for systems that support different types of files.

 Location. Pointer to file location on device.

 Size. The current size of the 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.

File Access Methods

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

 Data is accessed one record right after another is an order.

 Read command cause a pointer to be moved ahead by one.

 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

 Such a method is reasonable for tape.

2. Direct Access

 This method is useful for disks.

 The file is viewed as a numbered sequence of blocks or records.

 There are no restrictions on which blocks are read/written, it can be dobe in any order.

 User now says "read n" rather than "read next".

 "n" is a number relative to the beginning of file, not relative to an absolute physical disk
location.

3. Indexed Sequential Access

 It is built on top of Sequential access.

 It uses an Index to control the pointer while accessing files.

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.

Following is the information maintained in a directory :

 Name : The name visible to user.

 Type : Type of the directory.

 Location : Device and location on the device where the file header is located.

 Size : Number of bytes/words/blocks in the file.

 Position : Current next-read/next-write pointers.

 Protection : Access control on read/write/execute/delete.

 Usage : Time of creation, access, modification etc.

A file is a collection of related information that is recorded on secondary storage. Or file is a


collection of logically related entities. From user’s perspective a file is the smallest allotment
of logical secondary storage.
Attributes Types Operations
Name Doc Create

Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur

Type Exe Open


Size Jpg Read
Creation Data Xis Write
Author C Append
Last Modified Java Truncate
protection class Delete
Close
Usual
File type extension Function
Read to run
exe, com, machine language
Executable bin program
Compiled,
machine language
Object obj, o not linked
Source C, java, Source code in
Code pas, asm, a various languages
Commands to the
command
Batch bat, sh interpreter
Textual data,
Text txt, doc documents
Word wp, tex, Various word
Processor rrf, doc processor formats
Related files
arc, zip, grouped into one
Archive tar compressed file
For containing
mpeg, audio/video
Multimedia mov, rm information

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.

Information contained in a device directory are:


 Name
 Type
 Address
 Current length
 Maximum length
 Date last accessed
 Date last updated
 Owner id
 Protection information
Operation performed on directory are:
 Search for a file
 Create a file
 Delete a file
 List a directory
 Rename a file
 Traverse the file system
Advantages of maintaining directories are:
 Efficiency: A file can be located more quickly.
 Naming: It becomes convenient for users as two users can have same name for different
files or may have different name for same file.
 Grouping: Logical grouping of files can be done by properties e.g. all java programs, all
games etc.
SINGLE-LEVEL DIRECTORY
In this a single directory is maintained for all the users.

 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.

FILE ALLOCATION METHODS

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

 There is an overhead of maintaining the pointer in every disk block.


 If the pointer of any disk block is lost, the file will be truncated.
 It supports only the sequencial access of files.
3. Indexed Allocation:
It addresses many of the problems of contiguous and chained allocation. In this case, the file
allocation table contains a separate one-level index for each file: The index has one entry for
each block allocated to the file. Allocation may be on the basis of fixed-size blocks or variable-
sized blocks. Allocation by blocks eliminates external fragmentation, whereas allocation by
variable-size blocks improves locality. This allocation technique supports both sequential and
direct access to the file and thus is the most popular form of file allocation.

Disk Free Space Management


Just as the space that is allocated to files must be managed ,so the space that is not currently
allocated to any file must be managed. To perform any of the file allocation techniques,it is
necessary to know what blocks on the disk are available. Thus we need a disk allocation table
in addition to a file allocation table.The following are the approaches used for free space
management.
1. Bit Tables : This method uses a vector containing one bit for each block on the disk. Each
entry for a 0 corresponds to a free block and each 1 corresponds to a block in use.
For example: 00011010111100110001
In this vector every bit correspond to a particular block and 0 implies that, that particular
block is free and 1 implies that the block is already occupied. A bit table has the advantage
that it is relatively easy to find one or a contiguous group of free blocks. Thus, a bit table
works well with any of the file allocation methods. Another advantage is that it is as small
as possible.
2. Free Block List : In this method, each block is assigned a number sequentially and the list
of the numbers of all free blocks is maintained in a reserved block of the disk.

Program
#include<iostream>

#include<fstream>

#include<string.h>

using namespace std;

class student

typedef struct stud

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

cout<<"\n\tEnter Roll No of Student : ";

cin>>rec.roll;

cout<<"\n\tEnter a Name of Student : ";

cin>>rec.name;

cout<<"\n\tEnter a Division of Student : ";

cin>>rec.div;

cout<<"\n\tEnter a Address of Student : ";

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;

cout<<"\n\tDo You Want to Add More Records: ";

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\tThe Content of File are:\n";

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);

cout<<"\n\tEnter a Roll No: ";

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)

cout<<"\n\tRecord Not Found";

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

cout<<"\n\t***** Student Information *****";

Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur

cout<<"\n\t1. Create\n\t2. Display\n\t3. Delete\n\t4. Search\n\t5. Exit";

cout<<"\n\t..... Enter Your Choice: ";

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)

cout<<"\n\tRecord Not Found...\n";

break;

case 5:

break;

cout<<"\n\t..... Do You Want to Continue in Main Menu: ";

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

Objective: To understand the use Python

Input: Snake and Ladders and create box

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

Steps to Design Snake and Ladder game :

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.

Step 3: Define Snake and Ladder by extending the moving entity.

Step 4: Defining board class:


1. The board contains a moving entity that can be set at a specific position using a
function(set_moving_entity), for e.g. to add a snake at position 10, we can just do
set_moving_entity(10, snake)

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:

"""

Encapsulates a player properties

"""

def __init__(self, _id):

self._id = _id

# initial dummy rank -1

self.rank = -1

# starting position for every player is 1

self.position = 1

def set_position(self, pos):

self.position = pos

def set_rank(self, rank):

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:

"""

You can create any moving entity , like snake or ladder or

wormhole by extending this

"""

def __init__(self, end_pos=None):

# end pos where player would be send on board

self.end_pos = end_pos

# description of moving entity

self.desc = None

def set_description(self, desc):

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

def __init__(self, end_pos=None):

super(Snake, self).__init__(end_pos)

self.desc = "Bit by Snake"

class Ladder(MovingEntity):

"""Ladder entity"""

def __init__(self, end_pos=None):

super(Ladder, self).__init__(end_pos)

self.desc = "Climbed Ladder"

class Board:

"""

define board with size and moving entities

"""

def __init__(self, size):

self.size = size

# instead of using list, we can use map of

# {pos:moving_entity} to save space

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

def set_moving_entity(self, pos, moving_entity):

# set moving entity to pos

self.board[pos] = moving_entity

def get_next_pos(self, player_pos):

# get next pos given a specific position player is on

if player_pos > self.size:

return player_pos

if player_pos not in self.board:

return player_pos

print(f'{self.board[player_pos].desc} at {player_pos}')

return self.board[player_pos].get_end_pos()

def at_last_pos(self, pos):

if pos == self.size:

return True

return False

class Dice:

def __init__(self, sides):

# no of sides in the 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):

# return random number between 1 to sides

import random

ans = random.randrange(1, self.sides + 1)

return ans

class Game:

def __init__(self):

# game board object

self.board = None

# game dice object

self.dice = None

# list of game player objects

self.players = []

# curr turn

self.turn = 0

self.winner = None

# last rank achieved

self.last_rank = 0

# no of consecutive six in one turn, resets every turn

self.consecutive_six = 0

def initialize_game(self, board: Board, dice_sides, players):

"""

Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur

Initialize game using board, dice and players

"""

self.board = board

self.dice = Dice(dice_sides)

self.players = [GamePlayer(i) for i in range(players)]

def can_play(self):

if self.last_rank != len(self.players):

return True

return False

def get_next_player(self):

"""

Return curr_turn player but if it has already won/completed game , return

next player which is still active

"""

while True:

# if rank is -1 , player is still active so return

if self.players[self.turn].get_rank() == -1:

return self.players[self.turn]

# check next player

self.turn = (self.turn + 1) % len(self.players)

def move_player(self, curr_player, next_pos):

# Move player to next_pos

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()):

# if at last position set rank

curr_player.set_rank(self.last_rank + 1)

self.last_rank += 1

def can_move(self, curr_player, to_move_pos):

# check if player can move or not ie. between board bound

if to_move_pos <= self.board.get_size() and curr_player.get_rank() == -1:

return True

return False

def change_turn(self, dice_result):

# change player turn basis dice result.

# if it's six, do not change .

# if it's three consecutive sixes or not a six, change

self.consecutive_six = 0 if dice_result != 6 else self.consecutive_six + 1

if dice_result != 6 or self.consecutive_six == 3:

if self.consecutive_six == 3:

print("Changing turn due to 3 consecutive sixes")

self.turn = (self.turn + 1) % len(self.players)

else:

print(f"One more turn for player {self.turn+1} after rolling 6")

def play(self):

"""

starting point of game

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

# get curr player to play

# roll dice

# get next pos of player

# see if pos is valid to move

# move player to next pos

# change turn

Note: Currently everything is automated, ie. dice roll input is not taken from user.

if required , we can change that to give some control to user.

"""

while self.can_play():

curr_player = self.get_next_player()

player_input = input(

f"Player {self.turn+1}, Press enter to roll the dice")

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):

# Print state of game after every turn

Data structures And Algorithm Lab 2021 Prepared By:- Prof.Khatal S.S
Sharadchandra Pawar College Of Engineering Otur

print('-------------game state-------------')

for ix, _p in enumerate(self.players):

print(f'Player: {ix+1} is at pos {_p.get_pos()}')

print('-------------game state-------------\n\n')

def print_game_result(self):

# Print final game result with ranks of each player

print('-------------final result-------------')

for _p in sorted(self.players, key=lambda x: x.get_rank()):

print(f'Player: {_p._id+1} , Rank: {_p.get_rank()}')

def sample_run():

# a simple flow of the game

# here we create a board of size 10 and dice of side 6

# set snake at 5 with end at 2

# set ladder at 4 with end at 6

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy