0% found this document useful (0 votes)
4 views

DSA code pdf

The document contains multiple assignments focusing on data structures in C++ and Python, including hash tables, binary search trees, and tree structures. Each assignment includes code snippets for creating, searching, updating, and deleting records in these data structures, along with sample outputs demonstrating their functionality. The assignments aim to provide practical understanding and implementation of these data structures through coding exercises.

Uploaded by

Ayush Deshmukh
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)
4 views

DSA code pdf

The document contains multiple assignments focusing on data structures in C++ and Python, including hash tables, binary search trees, and tree structures. Each assignment includes code snippets for creating, searching, updating, and deleting records in these data structures, along with sample outputs demonstrating their functionality. The assignments aim to provide practical understanding and implementation of these data structures through coding exercises.

Uploaded by

Ayush Deshmukh
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/ 51

Assignment 1

#include <iostream>
#include <string>
using namespace std;

// Class to store contact details


class Node {
public:
string name;
long int tel;
int id;

Node() : name(""), tel(0), id(0) {}


};

// Class to represent a hash table for contact information


class Hashing {
private:
static const int MAX_SIZE = 100;
Node data[MAX_SIZE];
string n;
long int t;
int i, index;

public:
Hashing() : i(0), t(0), index(0) {}

// This method creates a new record in the hash table


void createRecord(int size) {
if (size > MAX_SIZE) {
cout << "Size exceeds the maximum limit." << endl;
return;
}

// Sample data for demonstration purposes


i = 4;
n = "Akshath Singh";
t = 23451234;

cout << "\nCreating a new record:" << endl;


cout << "ID: " << i << endl;
cout << "Name: " << n << endl;
cout << "Telephone: " << t << endl;

index = i % size;
// Inserting record using linear probing in case of collision
for (int j = 0; j < size; j++) {
if (data[index].id == 0) {
data[index].id = i;
data[index].name = n;
data[index].tel = t;
break;
} else {
index = (index + 1) % size;
}
}
}

// This method searches for a record by its ID


void searchRecord(int size) {
int key = 4; // Sample key for demonstration
int index1 = key % size;

cout << "\nSearching for record with ID: " << key << endl;

bool found = false;


for (int a = 0; a < size; a++) {
if (data[index1].id == key) {
found = true;
cout << "\nRecord found:" << endl;
cout << "ID: " << data[index1].id << endl;
cout << "Name: " << data[index1].name << endl;
cout << "Telephone: " << data[index1].tel << endl;
break;
} else {
index1 = (index1 + 1) % size;
}
}

if (!found) {
cout << "Record not found." << endl;
}
}

// This method deletes a record by its ID


void deleteRecord(int size) {
int key = 4; // Sample key for demonstration
int index1 = key % size;

cout << "\nDeleting record with ID: " << key << endl;

bool found = false;


for (int a = 0; a < size; a++) {
if (data[index1].id == key) {
found = true;
data[index1].id = 0;
data[index1].name = "";
data[index1].tel = 0;
cout << "Record deleted successfully." << endl;
break;
} else {
index1 = (index1 + 1) % size;
}
}

if (!found) {
cout << "Record not found." << endl;
}
}

// This method updates a record by its ID


void updateRecord(int size) {
int key = 4; // Sample key for demonstration
int index1 = key % size;

cout << "\nUpdating record with ID: " << key << endl;

bool found = false;


for (int a = 0; a < size; a++) {
if (data[index1].id == key) {
found = true;
break;
} else {
index1 = (index1 + 1) % size;
}
}

if (found) {
n = " Raj Shah";
t = 23413421;
data[index1].name = n;
data[index1].tel = t;

cout << "Updated record:" << endl;


cout << "ID: " << data[index1].id << endl;
cout << "Name: " << data[index1].name << endl;
cout << "Telephone: " << data[index1].tel << endl;
} else {
cout << "Record not found." << endl;
}
}
// This method displays all records in the hash table
void displayRecords(int size) {
cout << "\nDisplaying all records:" << endl;
cout << "ID\tName\t\tTelephone" << endl;

for (int a = 0; a < size; a++) {


if (data[a].id != 0) {
cout << data[a].id << "\t" << data[a].name << "\t\t" << data[a].tel << endl;
}
}
}
};

// Driver code
int main() {
Hashing s;

int size = 20; // Set the size of the hash table

cout << "\n1. CREATE record" << endl;


s.createRecord(size);

cout << "\n2. DISPLAY record" << endl;


s.displayRecords(size);

cout << "\n3. SEARCH record" << endl;


s.searchRecord(size);

cout << "\n4. UPDATE record" << endl;


s.updateRecord(size);

cout << "\n5. DELETE record" << endl;


s.deleteRecord(size);
return 0;
}

Output :-

1. CREATE record

Creating a new record:


ID: 4
Name: Akshath Singh
Telephone: 23451234

2. DISPLAY record
Displaying all records:
ID Name Telephone
4 Akshath Singh 23451234

3. SEARCH record

Searching for record with ID: 4

Record found:
ID: 4
Name: Akshath Singh
Telephone: 23451234

4. UPDATE record

Updating record with ID: 4


Updated record:
ID: 4
Name: Raj Shah
Telephone: 23413421

5. DELETE record

Deleting record with ID: 4


Record deleted successfully.
Assignment 2

class HashTable:
def __init__(self):
self.size = 10
self.slots = [None] * self.size
self.data = [None] * self.size
self.indices = [-1] * self.size

def insert(self, key, data):


flag = 0
hashvalue = self.hashfunction(key, len(self.slots))
same = hashvalue
if self.slots[hashvalue] == None:
self.slots[hashvalue] = key
self.data[hashvalue] = data
else:
if self.slots[hashvalue] == key:
self.data[hashvalue] = data # replace
else:
nextslot = self.nextloc(hashvalue, len(self.slots))
while self.slots[nextslot] != None and self.slots[nextslot] != key:
nextslot = self.nextloc(nextslot, len(self.slots))
if self.slots[nextslot] == None:
self.slots[nextslot] = key
self.data[nextslot] = data
self.indices[hashvalue] = nextslot
else:
self.data[nextslot] = data # replace

def hashfunction(self, key, size):


return key % size

def nextloc(self, oldhash, size):


return (oldhash + 1) % size

def delete(self, key):


hashvalue = self.hashfunction(key, len(self.slots))
flag = False
check = 0
while check != 1:
if self.slots[hashvalue] == key:
self.slots[hashvalue] = None
self.data[hashvalue] = None
self.indices[hashvalue] = -1
check = 1
flag = True
break
else:
if self.indices[hashvalue] != -1:
oldhash = hashvalue
hashvalue = self.indices[hashvalue]
self.indices[oldhash] = -1
else:
check = 1
break

def get(self, key):


startslot = self.hashfunction(key, len(self.slots))
data = None
stop = False
found = False
position = startslot
while self.slots[position] != None and not found and not stop:
if self.slots[position] == key:
found = True
data = self.data[position]
else:
position = self.nextloc(position, len(self.slots))
if position == startslot:
stop = True
return data

def __getitem__(self, key):


return self.get(key)

def __setitem__(self, key, data):


self.insert(key, data)

H = HashTable()
H[54] = "Rohit"
H[26] = "Anaya"
H[93] = "Nikita"
H[17] = "Amar"
H[77] = "Manali"
H[31] = "Shilpa"
H[44] = "Aniket"
H[99] = "Prasad"
H[20] = "Pawan"

print("Keys:")
print(H.slots)
print("Data at their respective Keys:")
print(H.data)
print(H.indices)
print(H[77])
H.delete(77)

print("After deletion of data in H[77]")


print("Keys:")
print(H.slots)
print("Data at their respective Keys:")
print(H.data)
print(H.indices)

Output:-

Keys:
[20, 31, None, 93, 54, 44, 26, 17, 77, 99]
Data at their respective Keys:
['Pawan', 'Shilpa', None, 'Nikita', 'Rohit', 'Aniket', 'Anaya', 'Amar', 'Manali', 'Prasad']
[-1, -1, -1, -1, 5, -1, -1, 8, -1, -1]
Manali
After deletion of data in H[77]
Keys:
[20, 31, None, 93, 54, 44, 26, 17, None, 99]
Data at their respective Keys:
['Pawan', 'Shilpa', None, 'Nikita', 'Rohit', 'Aniket', 'Anaya', 'Amar', None, 'Prasad']
[-1, -1, -1, -1, 5, -1, -1, -1, -1, -1]

=== Code Execution Successful ===


Assignment 3

#include<iostream>
#include <iostream>
#include <string.h>
using namespace std;
struct node // Node Declaration
{
string label;
//char label[10];
int ch_count;
struct node *child[10];
} * root;
class GT // Class Declaration
{
public:
void create_tree();
void display(node *r1);
GT()
{
root = NULL;
}
};
void GT::create_tree()
{
int tbooks, tchapters, i, j, k;
root = new node;
cout << "Enter name of book : ";
cin.get();
getline(cin, root->label);
cout << "Enter number of chapters in book : ";
cin >> tchapters;
root->ch_count = tchapters;
for (i = 0; i < tchapters; i++)
{
root->child[i] = new node;
cout << "Enter the name of Chapter " << i + 1 << " : ";
cin.get();
getline(cin, root->child[i]->label);
cout << "Enter number of sections in Chapter : " << root->child[i]->label << " : ";
cin >> root->child[i]->ch_count;
for (j = 0; j < root->child[i]->ch_count; j++)
{
root->child[i]->child[j] = new node;
cout << "Enter Name of Section " << j + 1 << " : ";
cin.get();
getline(cin, root->child[i]->child[j]->label);
//cout<<"Enter no. of subsections in "<<r1->child[i]->child[j]->label;
//cin>>r1->child[i]->ch_count;
}
}
}
void GT::display(node *r1)
{
int i, j, k, tchapters;
if (r1 != NULL)
{
cout << "\n-----Book Hierarchy---";
cout << "\n Book title : " << r1->label;
tchapters = r1->ch_count;
for (i = 0; i < tchapters; i++)
{
cout << "\nChapter " << i + 1;
cout << " : " << r1->child[i]->label;
cout << "\nSections : ";
for (j = 0; j < r1->child[i]->ch_count; j++)
{
cout << "\n"<< r1->child[i]->child[j]->label;
}
}
}
cout << endl;
}
int main()
{
int choice;
GT gt;
while (1)
{
cout << "-----------------" << endl;
cout << "Book Tree Creation" << endl;
cout << "-----------------" << endl;
cout << "1.Create" << endl;
cout << "2.Display" << endl;
cout << "3.Quit" << endl;
cout << "Enter your choice : ";
cin >> choice;
switch (choice)
{
case 1:
gt.create_tree();
case 2:
gt.display(root);
break;
case 3:
exit(1);
default:
cout << "Wrong choice!!!" << endl;
}
}
return 0;
}

Output:-

-----------------
Book Tree Creation
-----------------
1.Create
2.Display
3.Quit
Enter your choice : 1
Enter name of book : Dsa
Enter number of chapters in book : 2
Enter the name of Chapter 1 : Graph
Enter number of sections in Chapter : Graph : 1
Enter Name of Section 1 : introduction to graph
Enter the name of Chapter 2 : Tree
Enter number of sections in Chapter : tree : 2
Enter Name of Section 1 : Introduction to tree
Enter Name of Section 2 : tree treversal

-----Book Hierarchy---
Book title : Dsa
Chapter 1 : Graph
Sections :
introduction to graph
Chapter 2 : tree
Sections :
Introduction to tree
tree treversal
-----------------
Book Tree Creation
-----------------
1.Create
2.Display
3.Quit
Enter your choice :
Assignment 4

#include <iostream>
#include <algorithm>

using namespace std;

// Binary Search Tree Node


struct Node {
int data;
Node* left;
Node* right;
};

// Create a new node


Node* createNode(int data) {
Node* newNode = new Node();
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}

// Insert a new node into the BST


Node* insert(Node* root, int data) {
if (root == NULL) {
return createNode(data);
}

if (data < root->data) {


root->left = insert(root->left, data);
} else {
root->right = insert(root->right, data);
}

return root;
}

// Find the minimum value in the BST


int findMin(Node* root) {
while (root->left != NULL) {
root = root->left;
}
return root->data;
}

// Find the height of the BST


int findHeight(Node* root) {
if (root == NULL) {
return 0;
}
int leftHeight = findHeight(root->left);
int rightHeight = findHeight(root->right);

return 1 + max(leftHeight, rightHeight);


}

// Swap left and right children recursively


void swapChildren(Node* root) {
if (root == NULL) {
return;
}

swap(root->left, root->right);

swapChildren(root->left);
swapChildren(root->right);
}

// Search for a value in the BST


bool search(Node* root, int data) {
if (root == NULL) {
return false;
}

if (root->data == data) {
return true;
} else if (data < root->data) {
return search(root->left, data);
} else {
return search(root->right, data);
}
}

int main() {
Node* root = NULL;
int choice, value;

while (true) {
cout << "\nMenu:";
cout << "\n1. Insert a node";
cout << "\n2. Find the number of nodes in the longest path from the root (height)";
cout << "\n3. Find the minimum data value in the BST";
cout << "\n4. Swap the roles of left and right pointers at every node";
cout << "\n5. Search for a value in the BST";
cout << "\n6. Exit";
cout << "\nEnter your choice: ";
cin >> choice;

switch (choice) {
case 1:
cout << "Enter the value to insert: ";
cin >> value;
root = insert(root, value);
cout << "Node inserted.";
break;

case 2:
cout << "Height of the tree: " << findHeight(root);
break;

case 3:
if (root == NULL) {
cout << "BST is empty.";
} else {
cout << "Minimum value in the tree: " << findMin(root);
}
break;

case 4:
swapChildren(root);
cout << "Children swapped at every node.";
break;

case 5:
cout << "Enter the value to search: ";
cin >> value;
if (search(root, value)) {
cout << "Value found in the BST.";
} else {
cout << "Value not found.";
}
break;

case 6:
cout << "Exiting...";
return 0;

default:
cout << "Invalid choice. Try again.";
break;
}
}
return 0;
}

Output :-

Menu:
1. Insert a node
2. Find the number of nodes in the longest path from the root (height)
3. Find the minimum data value in the BST
4. Swap the roles of left and right pointers at every node
5. Search for a value in the BST
6. Exit
Enter your choice: 1
Enter the value to insert: 39
Node inserted.
Menu:
1. Insert a node
2. Find the number of nodes in the longest path from the root (height)
3. Find the minimum data value in the BST
4. Swap the roles of left and right pointers at every node
5. Search for a value in the BST
6. Exit
Enter your choice: 1
Enter the value to insert: 44
Node inserted.
Menu:
1. Insert a node
2. Find the number of nodes in the longest path from the root (height)
3. Find the minimum data value in the BST
4. Swap the roles of left and right pointers at every node
5. Search for a value in the BST
6. Exit
Enter your choice: 1
Enter the value to insert: 27
Node inserted.
Menu:
1. Insert a node
2. Find the number of nodes in the longest path from the root (height)
3. Find the minimum data value in the BST
4. Swap the roles of left and right pointers at every node
5. Search for a value in the BST
6. Exit
Enter your choice: 2
Height of the tree: 2
Menu:
1. Insert a node
2. Find the number of nodes in the longest path from the root (height)
3. Find the minimum data value in the BST
4. Swap the roles of left and right pointers at every node
5. Search for a value in the BST
6. Exit
Enter your choice:
Assignment 5

#include <iostream> // For input/output operations

using namespace std;

// Structure of a node in a threaded binary tree


struct Node {
int key;
Node *left, *right;
bool isThreaded; // Indicates if the right pointer is a thread
};

// Utility function to create a new node


Node* newNode(int key) {
Node* temp = new Node;
temp->key = key;
temp->left = nullptr;
temp->right = nullptr;
temp->isThreaded = false;
return temp;
}

// Function to create a threaded binary tree


Node* createThreaded(Node* root) {
if (root == nullptr) {
return nullptr;
}

if (root->left == nullptr && root->right == nullptr) {


return root;
}

// Find predecessor if it exists


if (root->left != nullptr) {
Node* l = createThreaded(root->left);

// Link a thread from predecessor to root


l->right = root;
l->isThreaded = true;
}

// If the current node is the rightmost child


if (root->right == nullptr) {
return root;
}

// Recur for the right subtree


return createThreaded(root->right);
}

// Function to find the leftmost node


Node* leftMost(Node* root) {
while (root != nullptr && root->left != nullptr) {
root = root->left;
}
return root;
}

// Function to do inorder traversal of a threaded binary tree


void inOrder(Node* root) {
if (root == nullptr) {
return;
}

Node* cur = leftMost(root);

while (cur != nullptr) {


cout << cur->key << " ";

// If this node is a thread, go to the inorder successor


if (cur->isThreaded) {
cur = cur->right;
} else {
// Otherwise, go to the leftmost child in the right subtree
cur = leftMost(cur->right);
}
}
}
// Driver program to test the above functions
int main() {
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
createThreaded(root);
cout << "Inorder traversal of the created threaded tree is:\n";
inOrder(root);

return 0;
}
Output:-
Inorder traversal of the created threaded tree is:
4251637
Assignment 6

#include <iostream>
#include <iomanip>
using namespace std;

const int MAX = 10;

// Forward declaration
class EdgeList;

// Edge class (used in Kruskal's Algorithm)


class Edge {
public:
int u, v, w;

Edge() {} // Default constructor

Edge(int a, int b, int weight) {


u = a;
v = b;
w = weight;
}

friend class EdgeList;


friend class PhoneGraph;
};

// EdgeList class for managing edges


class EdgeList {
private:
Edge data[MAX];
int n;

public:
EdgeList() {
n = 0;
}

void sort(); // Sorts edges by weight


void print(); // Prints the edges

friend class PhoneGraph;


};

// Bubble sort for sorting edges by weight


void EdgeList::sort() {
for (int i = 1; i < n; i++) {
for (int j = 0; j < n - 1; j++) {
if (data[j].w > data[j + 1].w) {
Edge temp = data[j];
data[j] = data[j + 1];
data[j + 1] = temp;
}
}
}
}

// Print edges and calculate the minimum cost


void EdgeList::print() {
int cost = 0;
for (int i = 0; i < n; i++) {
cout << "\n" << i + 1 << " " << data[i].u << "--" << data[i].v << " = " << data[i].w;
cost += data[i].w;
}
cout << "\nMinimum cost of Flight path Graph = " << cost << endl;
}

// PhoneGraph class representing the graph and algorithms


class PhoneGraph {
private:
int data[MAX][MAX]; // Adjacency matrix
int n; // Number of vertices

public:
PhoneGraph(int num) {
n = num;
}

void readGraph(); // Read adjacency matrix


void printGraph(); // Print adjacency matrix
int minCost(int cost[], bool visited[]); // Find the vertex with the minimum cost
int prim(); // Prim's algorithm for minimum spanning tree
void kruskal(EdgeList &spanlist); // Kruskal's algorithm for minimum spanning tree
int find(int belongs[], int vertexNo); // Find the set a vertex belongs to
void unionComp(int belongs[], int c1, int c2); // Union components
};

// Read the adjacency matrix for the graph


void PhoneGraph::readGraph() {
cout << "Enter Adjacency (Cost) Matrix: \n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> data[i][j];
}
}
}

// Print the adjacency matrix


void PhoneGraph::printGraph() {
cout << "\nAdjacency (Cost) Matrix: \n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << setw(3) << data[i][j];
}
cout << endl;
}
}

// Find the vertex with the minimum cost


int PhoneGraph::minCost(int cost[], bool visited[]) {
int min = 9999; // Initialize min to a high value
int min_index = -1; // Index of vertex with the minimum cost
for (int i = 0; i < n; i++) {
if (!visited[i] && cost[i] < min) {
min = cost[i];
min_index = i;
}
}
return min_index;
}

// Prim's algorithm to find the minimum spanning tree


int PhoneGraph::prim() {
bool visited[MAX] = {0}; // Initialize visited to false
int parents[MAX]; // Track parents
int cost[MAX]; // Minimum cost to connect vertices

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


cost[i] = 9999; // Set initial cost to high
}

cost[0] = 0; // Start from the first vertex


parents[0] = -1; // Make it the root

// Prim's algorithm
for (int i = 0; i < n - 1; i++) {
int k = minCost(cost, visited); // Get the vertex with the minimum cost
visited[k] = true; // Mark as visited

for (int j = 0; j < n; j++) {


if (data[k][j] != 0 && !visited[j] && data[k][j] < cost[j]) {
parents[j] = k;
cost[j] = data[k][j];
}
}
}

// Output the minimum cost


int minCost = 0;
cout << "Minimum Cost flight path Map:\n";
for (int i = 1; i < n; i++) {
cout << parents[i] << " -- " << i << " = " << cost[i] << endl;
minCost += cost[i];
}

return minCost;
}

// Kruskal's algorithm for the minimum spanning tree


void PhoneGraph::kruskal(EdgeList &spanlist) {
EdgeList elist; // List of all edges
int belongs[MAX]; // Which component each vertex belongs to

// Build the edge list


for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (data[i][j] != 0) { // If there's a connection
elist.data[elist.n] = Edge(i, j, data[i][j]); // Add the edge
elist.n++;
}
}
}

elist.sort(); // Sort edges by weight

// Initialize component belonging


for (int i = 0; i < n; i++) {
belongs[i] = i; // Initially, each vertex is in its own component
}

// Kruskal's algorithm
for (int i = 0; i < elist.n; i++) {
int cno1 = find(belongs, elist.data[i].u); // Component of vertex u
int cno2 = find(belongs, elist.data[i].v); // Component of vertex v

if (cno1 != cno2) { // If they are in different components


spanlist.data[spanlist.n] = elist.data[i]; // Add edge to spanning list
spanlist.n++;
unionComp(belongs, cno1, cno2); // Union the components
}
}
}

// Find which component a vertex belongs to


int PhoneGraph::find(int belongs[], int vertexNo) {
return belongs[vertexNo];
}

// Union two components


void PhoneGraph::unionComp(int belongs[], int c1, int c2) {
for (int i = 0; i < n; i++) {
if (belongs[i] == c2) {
belongs[i] = c1;
}
}
}

// Main program to test the graph algorithms


int main() {
int vertices, choice;
EdgeList spantree;

cout << "Enter Number of Cities: ";


cin >> vertices; // Number of vertices in the graph

PhoneGraph p1(vertices); // Create the graph


p1.readGraph(); // Read the adjacency matrix

do {
cout << "\n1. Find Minimum Total Cost (by Prim's Algorithm)"
<< "\n2. Find Minimum Total Cost (by Kruskal's Algorithm)"
<< "\n3. Re-Read Graph (INPUT)"
<< "\n4. Print Graph"
<< "\n0. Exit"
<< "\nEnter your choice: ";
cin >> choice; // Get user input

switch (choice) {
case 1:
cout << "Minimum cost of Phone Line to Cities is: " << p1.prim() << endl;
break;

case 2:
p1.kruskal(spantree); // Use Kruskal's Algorithm
spantree.print(); // Print the spanning tree
break;

case 3:
p1.readGraph(); // Re-read the adjacency matrix
break;

case 4:
p1.printGraph(); // Print the adjacency matrix
break;

case 0:
break; // Exit loop

default:
cout << "\nWrong Choice!" << endl;
}

} while (choice != 0); // Loop until user chooses to exit

return 0;
}

Output :-

Enter Number of Cities: 2


Enter Adjacency (Cost) Matrix:
2
3
4
2

1. Find Minimum Total Cost (by Prim's Algorithm)


2. Find Minimum Total Cost (by Kruskal's Algorithm)
3. Re-Read Graph (INPUT)
4. Print Graph
0. Exit
Enter your choice: 4

Adjacency (Cost) Matrix:


2 3
4 2

1. Find Minimum Total Cost (by Prim's Algorithm)


2. Find Minimum Total Cost (by Kruskal's Algorithm)
3. Re-Read Graph (INPUT)
4. Print Graph
0. Exit
Enter your choice: 1
Minimum cost of Phone Line to Cities is: Minimum Cost flight path Map:
0 -- 1 = 3
1. Find Minimum Total Cost (by Prim's Algorithm)
2. Find Minimum Total Cost (by Kruskal's Algorithm)
3. Re-Read Graph (INPUT)
4. Print Graph
0. Exit
Enter your choice: 2

1 1--0 = 4
Minimum cost of Flight path Graph = 4

1. Find Minimum Total Cost (by Prim's Algorithm)


2. Find Minimum Total Cost (by Kruskal's Algorithm)
3. Re-Read Graph (INPUT)
4. Print Graph
0. Exit
Enter your choice:
Assignment 7

#include <iostream>
#include <iomanip>
#include <limits>

using namespace std;

const int MAX = 10;

// Forward declaration
class EdgeList;

class Edge {
public:
int u, v, w;

Edge() {} // Empty constructor

Edge(int a, int b, int weight) {


u = a;
v = b;
w = weight;
}

friend class EdgeList;


friend class PhoneGraph;
};

// EdgeList class
class EdgeList {
public:
Edge data[MAX];
int n;

EdgeList() {
n = 0;
}

void sort();
void print();

friend class PhoneGraph;


};

// Bubble sort for sorting edges in increasing weights' order


void EdgeList::sort() {
for (int i = 1; i < n; i++) {
for (int j = 0; j < n - 1; j++) {
if (data[j].w > data[j + 1].w) {
swap(data[j], data[j + 1]);
}
}
}
}

void EdgeList::print() {
int total_cost = 0;
for (int i = 0; i < n; i++) {
cout << "\n" << i + 1 << " " << data[i].u << "--" << data[i].v << " = " << data[i].w;
total_cost += data[i].w;
}
cout << "\nMinimum cost of Telephone Graph = " << total_cost;
}

// PhoneGraph class
class PhoneGraph {
int data[MAX][MAX];
int n;

public:
PhoneGraph(int num) {
n = num;
}

void readgraph();
void printGraph();
int mincost(int cost[], bool visited[]);
int prim();
void kruskal(EdgeList &spanlist);
int find(int belongs[], int vertexno);
void unionComp(int belongs[], int c1, int c2);
};

// Corrected readgraph method with input validation


void PhoneGraph::readgraph() {
cout << "Enter the Adjacency (Cost) Matrix:\n";

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


for (int j = 0; j < n; j++) {
int value;
cin >> value;

if (cin.fail() || value < 0) {


cout << "Invalid input. Please enter a non-negative integer." << endl;
cin.clear(); // Clear error state
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Ignore invalid input
j--; // Re-enter current index
continue; // Retry input
}

data[i][j] = value; // Valid input


}
}
}

void PhoneGraph::printGraph() {
cout << "\nAdjacency (COST) Matrix:\n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << setw(3) << data[i][j];
}
cout << endl;
}
}

int PhoneGraph::mincost(int cost[], bool visited[]) {


int min = 9999; // Initialize min to a high value
int min_index;

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


if (!visited[i] && cost[i] < min) {
min = cost[i];
min_index = i;
}
}
return min_index;
}

int PhoneGraph::prim() {
bool visited[MAX];
int parents[MAX];
int cost[MAX];

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


cost[i] = 9999;
visited[i] = false;
}

cost[0] = 0; // Starting vertex cost


parents[0] = -1; // Make the first vertex the root

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


int k = mincost(cost, visited);
visited[k] = true;

for (int j = 0; j < n; j++) {


if (data[k][j] && !visited[j] && data[k][j] < cost[j]) {
parents[j] = k;
cost[j] = data[k][j];
}
}
}

cout << "Minimum Cost Telephone Map:\n";


for (int i = 1; i < n; i++) {
cout << i << " -- " << parents[i] << " = " << cost[i] << endl;
}

int mincost = 0;
for (int i = 1; i < n; i++) {
mincost += cost[i];
}

return mincost;
}

void PhoneGraph::kruskal(EdgeList &spanlist) {


EdgeList elist;
int belongs[MAX]; // Component groupings

// Populate EdgeList
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (data[i][j] != 0) {
elist.data[elist.n] = Edge(i, j, data[i][j]);
elist.n++;
}
}
}

elist.sort(); // Sort in increasing weight order

// Initialize components
for (int i = 0; i < n; i++) {
belongs[i] = i;
}

// Build the spanning tree using Kruskal's algorithm


for (int i = 0; i < elist.n; i++) {
int cno1 = find(belongs, elist.data[i].u);
int cno2 = find(belongs, elist.data[i].v);
if (cno1 != cno2) { // If different components
spanlist.data[spanlist.n] = elist.data[i];
spanlist.n++;
unionComp(belongs, cno1, cno2); // Unite components
}
}
}

int PhoneGraph::find(int belongs[], int vertexno) {


return belongs[vertexno];
}

void PhoneGraph::unionComp(int belongs[], int c1, int c2) {


for (int i = 0; i < n; i++) {
if (belongs[i] == c2) {
belongs[i] = c1;
}
}
}

// Main program
int main() {
int vertices;
int choice;
EdgeList spantree;

cout << "Enter number of cities: ";


cin >> vertices;

PhoneGraph p1(vertices);

p1.readgraph();

do {
cout << "\n1. Find Minimum Total Cost (Prim's Algorithm)"
<< "\n2. Find Minimum Total Cost (Kruskal's Algorithm)"
<< "\n3. Re-read Graph"
<< "\n4. Print Graph"
<< "\n0. Exit"
<< "\nEnter your choice: ";

cin >> choice;

switch (choice) {
case 1:
cout << "Minimum cost of Phone Line to cities is: " << p1.prim() << endl;
break;
case 2:
p1.kruskal(spantree);
spantree.print();
break;
case 3:
p1.readgraph();
break;
case 4:
p1.printGraph();
break;
default:
cout << "\nInvalid choice. Please try again." << endl;
}

} while (choice != 0);

return 0;
}

Output :-

Enter number of cities: 3


Enter the Adjacency (Cost) Matrix:
4
2
3
2
1
4
5
3
2

1. Find Minimum Total Cost (Prim's Algorithm)


2. Find Minimum Total Cost (Kruskal's Algorithm)
3. Re-read Graph
4. Print Graph
0. Exit
Enter your choice: 4

Adjacency (COST) Matrix:


4 2 3
2 1 4
5 3 2

1. Find Minimum Total Cost (Prim's Algorithm)


2. Find Minimum Total Cost (Kruskal's Algorithm)
3. Re-read Graph
4. Print Graph
0. Exit
Enter your choice:
Assignment 8

#include <iostream>
#include <climits>

using namespace std;

// A utility function to get the sum of


// array elements freq[i] to freq[j]
int sum(int freq[], int i, int j) {
int s = 0;
for (int k = i; k <= j; k++) {
s += freq[k];
}
return s;
}

// A recursive function to calculate


// the cost of optimal binary search tree
int optCost(int freq[], int i, int j) {
// Base cases
if (j < i) { // no elements in this subarray
return 0;
}
if (j == i) { // one element in this subarray
return freq[i];
}

// Get sum of freq[i], freq[i+1], ... freq[j]


int fsum = sum(freq, i, j);

// Initialize minimum value


int min_cost = INT_MAX;

// One by one consider all elements


// as root and recursively find cost
// of the BST, compare the cost with
// min_cost, and update min_cost if needed
for (int r = i; r <= j; r++) {
int cost = optCost(freq, i, r - 1) +
optCost(freq, r + 1, j);

if (cost < min_cost) {


min_cost = cost;
}
}

// Return the minimum value including the sum of frequencies


return min_cost + fsum;
}

// The main function that calculates


// the minimum cost of a Binary Search Tree.
// It mainly uses optCost() to find the optimal cost.
int optimalSearchTree(int keys[], int freq[], int n) {
// Assume that the keys array is sorted in ascending order.
return optCost(freq, 0, n - 1);
}

// Driver Code
int main() {
int keys[] = {10, 12, 20};
int freq[] = {34, 8, 50};
int n = sizeof(keys) / sizeof(keys[0]);

cout << "Cost of Optimal BST is "


<< optimalSearchTree(keys, freq, n) << endl;

return 0;
}

Output :-

Cost of Optimal BST is 142


Assignment 9

#include <iostream>
#include <string>
using namespace std;

struct node {
string word;
string meaning;
node* left;
node* right;
};

void inorder_rec(node* rnode) {


if (rnode == nullptr) return;
inorder_rec(rnode->left);
cout << " " << rnode->word << " : " << rnode->meaning << endl;
inorder_rec(rnode->right);
}

void postorder_rec(node* rnode) {


if (rnode == nullptr) return;
postorder_rec(rnode->left);
postorder_rec(rnode->right);
}

bool insert(node*& root, const string& word) {


if (root == nullptr) {
root = new node{word, "", nullptr, nullptr};
return true;
}
node* cur = root;
node* par = nullptr;
while (cur != nullptr) {
par = cur;
if (word < cur->word) {
cur = cur->left;
} else if (word > cur->word) {
cur = cur->right;
} else {
// Word already exists, no insertion
return false;
}
}

if (word < par->word) {


par->left = new node{word, "", nullptr, nullptr};
} else {
par->right = new node{word, "", nullptr, nullptr};
}
return true;
}

int find(node* root, const string& key) {


node* tmp = root;
while (tmp != nullptr) {
if (key < tmp->word) {
tmp = tmp->left;
} else if (key > tmp->word) {
tmp = tmp->right;
} else {
return 0; // Key found
}
}
return -1; // Key not found
}

int main() {
node* root = nullptr;
insert(root, "hello");
insert(root, "world");
inorder_rec(root);

return 0;
}

Output :-

hello :
world :

=== Code Execution Successful ===


Assignment 10

#include <iostream>
using namespace std;

void MaxHeapify(int a[], int i, int n) {


int j, temp;
temp = a[i];
j = 2 * i;

while (j <= n) {
if (j < n && a[j + 1] > a[j])
j = j + 1;

if (temp > a[j])


break;

a[j / 2] = a[j];
j = 2 * j;
}
a[j / 2] = temp;
}

void MinHeapify(int a[], int i, int n) {


int j, temp;
temp = a[i];
j = 2 * i;

while (j <= n) {
if (j < n && a[j + 1] < a[j])
j = j + 1;

if (temp < a[j])


break;

a[j / 2] = a[j];
j = 2 * j;
}
a[j / 2] = temp;
}

void MaxHeapSort(int a[], int n) {


for (int i = n; i >= 2; i--) {
int temp = a[i];
a[i] = a[1];
a[1] = temp;
MaxHeapify(a, 1, i - 1);
}
}

void MinHeapSort(int a[], int n) {


for (int i = n; i >= 2; i--) {
int temp = a[i];
a[i] = a[1];
a[1] = temp;
MinHeapify(a, 1, i - 1);
}
}

void Build_MaxHeap(int a[], int n) {


for (int i = n / 2; i >= 1; i--)
MaxHeapify(a, i, n);
}

void Build_MinHeap(int a[], int n) {


for (int i = n / 2; i >= 1; i--)
MinHeapify(a, i, n);
}

int main() {
int n;
cout << "Enter the number of Students: ";
cin >> n;

int arr[n + 1]; // Initialize the array with size n + 1


for (int i = 1; i <= n; i++) {
cout << "Enter the marks for student " << i << ": ";
cin >> arr[i];
}

// Max heap and sort


Build_MaxHeap(arr, n);
MaxHeapSort(arr, n);

int min = arr[1]; // Set minimum value

cout << "\nSorted Data in Ascending Order: ";


for (int i = 1; i <= n; i++)
cout << arr[i] << " ";

// Min heap and sort


Build_MinHeap(arr, n);
MinHeapSort(arr, n);

int max = arr[1]; // Set maximum value


cout << "\nSorted Data in Descending Order: ";
for (int i = 1; i <= n; i++)
cout << arr[i] << " ";

cout << "\nMaximum Marks: " << max;


cout << "\nMinimum Marks: " << min << "\n";

return 0;
}

Output :-

Enter the number of Students: 2


Enter the marks for student 1: 29
Enter the marks for student 2: 27

Sorted Data in Ascending Order: 27 29


Sorted Data in Descending Order: 29 27
Maximum Marks: 29
Minimum Marks: 27
Assignment 11

#include <iostream>
#include <fstream>
#include <cstring>
#include <iomanip>

using namespace std;

const int MAX = 20;

// Define the Student class


class Student {
int rollNo;
char name[MAX], city[MAX];
char div;
int year;

public:
// Default constructor
Student() : rollNo(0), div(0), year(0) {
strcpy(name, "");
strcpy(city, "");
}

// Parameterized constructor
Student(int rollNo, const char* name, int year, char div, const char* city)
: rollNo(rollNo), div(div), year(year) {
strcpy(this->name, name);
strcpy(this->city, city);
}

int getRollNo() const {


return rollNo;
}

void displayRecord() const {


cout << setw(5) << rollNo << setw(20) << name << setw(5) << year << setw(5) << div <<
setw(10) << city << endl;
}
};

// File operations class


class FileOperations {
fstream file;

public:
// Constructor to open file
FileOperations(const char* filename) {
file.open(filename, ios::in | ios::out | ios::ate | ios::binary);
if (!file.is_open()) {
cerr << "Error: Unable to open file." << endl;
exit(1);
}
}

void insertRecord(int rollNo, const char* name, int year, char div, const char* city) {
Student s(rollNo, name, year, div, city);
file.seekp(0, ios::end);
file.write(reinterpret_cast<char*>(&s), sizeof(Student));
file.clear();
}

void displayAll() {
Student s;
file.seekg(0, ios::beg);
cout << setw(5) << "ROLL" << setw(20) << "NAME" << setw(5) << "YEAR" << setw(5) <<
"DIV" << setw(10) << "CITY" << endl;
while (file.read(reinterpret_cast<char*>(&s), sizeof(Student))) {
s.displayRecord();
}
file.clear();
}

void displayRecord(int rollNo) {


Student s;
file.seekg(0, ios::beg);
bool found = false;
while (file.read(reinterpret_cast<char*>(&s), sizeof(Student))) {
if (s.getRollNo() == rollNo) {
s.displayRecord();
found = true;
break;
}
}
if (!found) {
cout << "\nRecord of roll number " << rollNo << " is not present." << endl;
}
file.clear();
}

void deleteRecord(int rollNo) {


ofstream outFile("new.dat", ios::binary);
file.seekg(0, ios::beg);
bool found = false;
Student s;

while (file.read(reinterpret_cast<char*>(&s), sizeof(Student))) {


if (s.getRollNo() == rollNo) {
found = true;
continue;
}
outFile.write(reinterpret_cast<char*>(&s), sizeof(Student));
}

if (!found) {
cout << "\nRecord of roll number " << rollNo << " is not present." << endl;
}

file.close();
outFile.close();
remove("student.dat");
rename("new.dat", "student.dat");
file.open("student.dat", ios::in | ios::out | ios::ate | ios::binary);
}

~FileOperations() {
file.close();
cout << "\nFile Closed." << endl;
}
};

// Main function
int main() {
ofstream newFile("student.dat", ios::app | ios::binary);
newFile.close();

FileOperations file("student.dat");

int rollNo, year, choice = 0;


char div;
char name[MAX], city[MAX];

while (choice != 5) {
cout << "\n***** Student Database *****\n";
cout << "1) Add New Record\n";
cout << "2) Display All Records\n";
cout << "3) Display by RollNo\n";
cout << "4) Delete a Record\n";
cout << "5) Exit\n";
cout << "Choose your choice: ";
cin >> choice;
switch (choice) {
case 1: // Add new record
cout << "\nEnter RollNo and Name: ";
cin >> rollNo >> name;
cout << "Enter Year and Division: ";
cin >> year >> div;
cout << "Enter City: ";
cin >> city;
file.insertRecord(rollNo, name, year, div, city);
cout << "\nRecord Inserted." << endl;
break;

case 2: // Display all records


file.displayAll();
break;

case 3: // Display by RollNo


cout << "\nEnter Roll Number: ";
cin >> rollNo;
file.displayRecord(rollNo);
break;

case 4: // Delete a record


cout << "\nEnter Roll Number: ";
cin >> rollNo;
file.deleteRecord(rollNo);
break;

case 5: // Exit
cout << "\nExiting..." << endl;
break;

default:
cout << "\nInvalid choice. Please try again." << endl;
break;
}
}

return 0;
}
Output :-

***** Student Database *****


1) Add New Record
2) Display All Records
3) Display by RollNo
4) Delete a Record
5) Exit
Choose your choice:1
Enter RollNo and Name:67 and Akshath Singh
Enter Year and Division: 2nd and CS

***** Student Database *****


1) Add New Record
2) Display All Records
3) Display by RollNo
4) Delete a Record
5) Exit
Choose your choice:2
67 Akshah Singh 2nd CS

***** Student Database *****


1) Add New Record
2) Display All Records
3) Display by RollNo
4) Delete a Record
5) Exit
Choose your choice:5
Assignment 12

#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstring>

using namespace std;

// Employee class Declaration


class Employee {
private:
int code;
char name[20];
float salary;

public:
void read();
void display();
int getEmpCode() { return code; }
float getSalary() { return salary; }
void updateSalary(float s) { salary = s; }
};

// Read employee record


void Employee::read() {
cout << "Enter employee code: ";
cin >> code;
cout << "Enter name: ";
cin.ignore(); // Clear buffer for getline
cin.getline(name, sizeof(name));
cout << "Enter salary: ";
cin >> salary;
}

// Display employee record


void Employee::display() {
cout << code << " " << name << "\t" << salary << endl;
}

// File stream object


fstream file;

// Delete existing file


void deleteExistingFile() {
remove("EMPLOYEE.DAT");
}
// Append record into file
void appendToFile() {
Employee x;

x.read();

file.open("EMPLOYEE.DAT", ios::binary | ios::app);


if (!file) {
cout << "Error in creating file\n";
return;
}
file.write(reinterpret_cast<char*>(&x), sizeof(x));
file.close();
cout << "Record added successfully.\n";
}

// Display all employee records


void displayAll() {
Employee x;

file.open("EMPLOYEE.DAT", ios::binary | ios::in);


if (!file) {
cout << "Error in opening file\n";
return;
}
cout << "Employee records with salary between 10,000 and 20,000:\n";
while (file.read(reinterpret_cast<char*>(&x), sizeof(x))) {
if (x.getSalary() >= 10000 && x.getSalary() <= 20000) {
x.display();
}
}
file.close();
}

// Search for a specific employee record


void searchForRecord() {
Employee x;
int code;
bool isFound = false;

cout << "Enter employee code to search: ";


cin >> code;

file.open("EMPLOYEE.DAT", ios::binary | ios::in);


if (!file) {
cout << "Error in opening file\n";
return;
}
while (file.read(reinterpret_cast<char*>(&x), sizeof(x))) {
if (x.getEmpCode() == code) {
cout << "Record found:\n";
x.display();
isFound = true;
break;
}
}
if (!isFound) {
cout << "Record not found!!!\n";
}
file.close();
}

// Function to increase salary


void increaseSalary() {
Employee x;
int code;
bool isFound = false;
float salaryHike;

cout << "Enter employee code to increase salary: ";


cin >> code;

fstream tempFile("TEMP.DAT", ios::binary | ios::out);

file.open("EMPLOYEE.DAT", ios::binary | ios::in);


if (!file || !tempFile) {
cout << "Error in opening files\n";
return;
}

while (file.read(reinterpret_cast<char*>(&x), sizeof(x))) {


if (x.getEmpCode() == code) {
cout << "Salary increment: ";
cin >> salaryHike;
x.updateSalary(x.getSalary() + salaryHike);
isFound = true;
}
tempFile.write(reinterpret_cast<char*>(&x), sizeof(x));
}

if (!isFound) {
cout << "Record not found!!!\n";
}

file.close();
tempFile.close();
rename("TEMP.DAT", "EMPLOYEE.DAT");
cout << "Salary updated successfully." << endl;
}

// Insert record while maintaining sorted order by code


void insertRecord() {
Employee newEmp;

// Read record to insert


newEmp.read();

fstream tempFile("TEMP.DAT", ios::binary | ios::out);

file.open("EMPLOYEE.DAT", ios::binary | ios::in);


if (!file || !tempFile) {
cout << "Error in opening files\n";
return;
}

Employee existingEmp;
bool isInserted = false;
while (file.read(reinterpret_cast<char*>(&existingEmp), sizeof(existingEmp))) {
if (existingEmp.getEmpCode() > newEmp.getEmpCode() && !isInserted) {
tempFile.write(reinterpret_cast<char*>(&newEmp), sizeof(newEmp));
isInserted = true;
}
tempFile.write(reinterpret_cast<char*>(&existingEmp), sizeof(existingEmp));
}

if (!isInserted) {
tempFile.write(reinterpret_cast<char*>(&newEmp), sizeof(newEmp));
}

file.close();
tempFile.close();

rename("TEMP.DAT", "EMPLOYEE.DAT");
cout << "Record inserted successfully." << endl;
}

// Main function with a menu-driven approach


int main() {
char continueChoice;

// Delete existing file if needed


deleteExistingFile();
do {
int option;

cout << "Choose an option:\n";


cout << "1. Add an employee\n";
cout << "2. Display employees\n";
cout << "3. Search employee\n";
cout << "4. Increase salary\n";
cout << "5. Insert employee\n";
cout << "6. Exit\n";

cout << "Make a choice: ";


cin >> option;

switch (option) {
case 1:
appendToFile();
break;
case 2:
displayAll();
break;
case 3:
searchForRecord();
break;
case 4:
increaseSalary();
break;
case 5:
insertRecord();
break;
case 6:
cout << "Exiting..." << endl;
return 0; // Exit the program
default:
cout << "Invalid choice. Try again." << endl;
break;
}

cout << "Do you want to continue? (Y/N): ";


cin >> continueChoice;

} while (continueChoice == 'Y' || 'y');

return 0;
}
Output :-

Choose an option:
1. Add an employee
2. Display employees
3. Search employee
4. Increase salary
5. Insert employee
6. Exit
Make a choice: 1
Enter employee code: 002
Enter name: Akshath
Enter salary: 20000
Record added successfully.
Do you want to continue? (Y/N): y
Choose an option:
1. Add an employee
2. Display employees
3. Search employee
4. Increase salary
5. Insert employee
6. Exit
Make a choice: 2
Employee records with salary between 10,000 and 20,000:
2 Akshath 20000
Do you want to continue? (Y/N):

You might also like