Added all the codes.
This commit is contained in:
parent
2825553bb6
commit
a8290daf1e
204
Codes/Practical-A1 (Hashing).py
Normal file
204
Codes/Practical-A1 (Hashing).py
Normal file
@ -0,0 +1,204 @@
|
||||
"""
|
||||
THIS CODE HAS BEEN TESTED AND IS FULLY OPERATIONAL.
|
||||
|
||||
Problem Statement: 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.
|
||||
|
||||
Code from DataStructuresAndAlgorithms (SPPU - Second Year - Computer Engineering - Content) repository on KSKA Git: https://git.kska.io/sppu-se-comp-content/DataStructuresAndAlgorithms/
|
||||
"""
|
||||
|
||||
# BEGINNING OF CODE
|
||||
class HashTable1:
|
||||
"""linear Probing without replacement"""
|
||||
|
||||
def __init__(self, size: int) -> None:
|
||||
self.record = []
|
||||
self.m = size
|
||||
|
||||
for _ in range(size):
|
||||
self.record.append([0, ""])
|
||||
|
||||
def display_table(self) -> None:
|
||||
print("Hash table using linear probing (without replacement):\t")
|
||||
for i in range(len(self.record)):
|
||||
print(i, self.record[i])
|
||||
|
||||
def hash_function(self, tel: int) -> int:
|
||||
key = (tel % self.m)
|
||||
return key
|
||||
|
||||
def generate_table(self, recs: list[list]) -> None:
|
||||
for rec in recs:
|
||||
self.insert_rec(rec)
|
||||
|
||||
def insert_rec(self, rec: list) -> None:
|
||||
key = self.hash_function(rec[0])
|
||||
if (self.record[key][0] == 0):
|
||||
|
||||
self.record[key][0] = rec[0]
|
||||
self.record[key][1] = rec[1]
|
||||
else:
|
||||
while (self.record[key][0] != 0):
|
||||
key = ((key+1) % self.m)
|
||||
|
||||
self.record[key][0] = rec[0]
|
||||
self.record[key][1] = rec[1]
|
||||
|
||||
|
||||
class HashTable2:
|
||||
"""linear Probing with replacement"""
|
||||
|
||||
def __init__(self, size: int) -> None:
|
||||
self.record = []
|
||||
self.m = size
|
||||
|
||||
for _ in range(size):
|
||||
self.record.append([0, "", -1])
|
||||
|
||||
def display_table(self) -> None:
|
||||
print("Hash table using linear probing (with replacement):\t")
|
||||
for i in range(len(self.record)):
|
||||
print(i, self.record[i])
|
||||
|
||||
def hash_function(self, tel: int) -> int:
|
||||
key = (tel % self.m)
|
||||
return key
|
||||
|
||||
def generate_table(self, recs: list[list]) -> None:
|
||||
for rec in recs:
|
||||
self.insert_rec(rec)
|
||||
|
||||
def insert_rec(self, rec: list) -> None:
|
||||
key = self.hash_function(rec[0])
|
||||
if (self.record[key][0] == 0):
|
||||
|
||||
self.record[key][0] = rec[0]
|
||||
self.record[key][1] = rec[1]
|
||||
self.record[key][2] = -1
|
||||
else:
|
||||
if (self.hash_function(self.record[key][0]) == key):
|
||||
|
||||
last_elmt = key
|
||||
while (self.record[last_elmt][2] != -1):
|
||||
last_elmt = self.record[last_elmt][2]
|
||||
k = last_elmt
|
||||
while (self.record[k][0] != 0):
|
||||
k = ((k+1) % self.m)
|
||||
self.record[last_elmt][2] = k
|
||||
self.record[k][0] = rec[0]
|
||||
self.record[k][1] = rec[1]
|
||||
self.record[k][2] = -1
|
||||
else:
|
||||
for i in range(self.m):
|
||||
if (self.record[i][2] == key):
|
||||
prev_link_key = i
|
||||
|
||||
old_rec_tel = self.record[key][0]
|
||||
old_rec_name = self.record[key][1]
|
||||
old_rec_link = self.record[key][2]
|
||||
|
||||
self.record[key][0] = rec[0]
|
||||
self.record[key][1] = rec[1]
|
||||
self.record[key][2] = -1
|
||||
|
||||
k = key
|
||||
while (self.record[k][0] != 0):
|
||||
k = ((k+1) % self.m)
|
||||
|
||||
self.record[prev_link_key][2] = k
|
||||
self.record[k][0] = old_rec_tel
|
||||
self.record[k][1] = old_rec_name
|
||||
self.record[k][2] = old_rec_link
|
||||
|
||||
|
||||
class HashTable3:
|
||||
"""Double hashing"""
|
||||
|
||||
def __init__(self, size: int) -> None:
|
||||
self.record = []
|
||||
self.m = size
|
||||
|
||||
for _ in range(size):
|
||||
self.record.append([0, ""])
|
||||
|
||||
if (size <= 3):
|
||||
self.prime = size
|
||||
else:
|
||||
prime = [2, 3]
|
||||
for i in range(size):
|
||||
for j in prime:
|
||||
if (i % j == 0):
|
||||
p = False
|
||||
break
|
||||
if (p):
|
||||
prime.append(i)
|
||||
self.prime = prime[-1]
|
||||
|
||||
def hash1(self, key: int) -> int:
|
||||
return (key % self.m)
|
||||
|
||||
def hash2(self, key: int) -> int:
|
||||
return (self.prime - (key % self.prime))
|
||||
|
||||
def display_table(self) -> None:
|
||||
print("Hash table using double hashing:\t")
|
||||
for i in range(len(self.record)):
|
||||
print(i, self.record[i])
|
||||
|
||||
def generate_table(self, recs: list[list]) -> None:
|
||||
for rec in recs:
|
||||
self.insert_rec(rec)
|
||||
|
||||
def insert_rec(self, rec: list) -> None:
|
||||
i = 0
|
||||
key = self.hash1(rec[0])
|
||||
k2 = (key + i*self.hash2(rec[0])) % self.m
|
||||
while (self.record[k2][0] != 0):
|
||||
k2 = (key + i*self.hash2(rec[0])) % self.m
|
||||
i += 1
|
||||
self.record[k2][0] = rec[0]
|
||||
self.record[k2][1] = rec[1]
|
||||
|
||||
|
||||
def input_records(n: int) -> list[list]:
|
||||
records = []
|
||||
for i in range(n):
|
||||
print(f"--- PERSON {i+1} ---")
|
||||
name = input("Name of the person:\t")
|
||||
tel = int(input("Telephone number:\t"))
|
||||
records.append([tel, name])
|
||||
print("--- DETAILS SAVED ---")
|
||||
return records
|
||||
|
||||
n = int(input("Total number of records are:\t"))
|
||||
records = input_records(n)
|
||||
ch = 1
|
||||
while(ch != 5):
|
||||
print("--- MAIN MENU")
|
||||
print("1 -> Enter records")
|
||||
print("2 -> Use linear Probing (without replacement)")
|
||||
print("3 -> Use linear Probing (with replacement)")
|
||||
print("4 -> Use double hashing")
|
||||
print("5 -> Exit")
|
||||
|
||||
ch = int(input("Choose an option (1-5):\t"))
|
||||
match (ch):
|
||||
case 1:
|
||||
n = int(input("Total number of records:\t"))
|
||||
records = input_records(n)
|
||||
case 2:
|
||||
t1 = HashTable1(n)
|
||||
t1.generate_table(records)
|
||||
t1.display_table()
|
||||
case 3:
|
||||
t2 = HashTable2(n)
|
||||
t2.generate_table(records)
|
||||
t2.display_table()
|
||||
case 4:
|
||||
t3 = HashTable3(n)
|
||||
t3.generate_table(records)
|
||||
t3.display_table()
|
||||
case 5:
|
||||
print("\n## END OF CODE\n")
|
||||
case default:
|
||||
print("Please choose a valid option (1-5).")
|
||||
# END OF CODE
|
177
Codes/Practical-A4 (Set Operations).py
Normal file
177
Codes/Practical-A4 (Set Operations).py
Normal file
@ -0,0 +1,177 @@
|
||||
"""
|
||||
THIS CODE HAS BEEN TESTED AND IS FULLY OPERATIONAL.
|
||||
|
||||
Problem Statement: To create ADT that implement the "set" concept.
|
||||
a. Add (newElement) -> Place a value into the set
|
||||
b. Remove (element) -> Remove the value
|
||||
c. Contains (element) -> Return true if element is in collection
|
||||
d. Size () -> Return number of values in collection
|
||||
Iterator () -> Return an iterator used to loop over collection
|
||||
e. Intersection of two sets
|
||||
f. Union of two sets
|
||||
g. Difference between two sets
|
||||
h. Subset
|
||||
|
||||
Code from DataStructuresAndAlgorithms (SPPU - Second Year - Computer Engineering - Content) repository on KSKA Git: https://git.kska.io/sppu-se-comp-content/DataStructuresAndAlgorithms/
|
||||
"""
|
||||
|
||||
# BEGINNING OF CODE
|
||||
SetA = []
|
||||
SetB = []
|
||||
|
||||
def insert():
|
||||
n1 = int(input("Number of elements in SET A:\t"))
|
||||
for i in range(n1):
|
||||
nm = int(input(f"Element {i+1} in SET A:\t"))
|
||||
SetA.append(nm)
|
||||
|
||||
n1 = int(input("Number of elements in SET B:\t"))
|
||||
for i in range(n1):
|
||||
nm = int(input(f"Element {i+1} in SET B:\t"))
|
||||
SetB.append(nm)
|
||||
|
||||
def display():
|
||||
print("SET A:\t",SetA)
|
||||
print("SET B:\t",SetB)
|
||||
|
||||
|
||||
def union():
|
||||
res=[]
|
||||
for i in SetA:
|
||||
res.append(i)
|
||||
for i in SetB:
|
||||
if i not in res:
|
||||
res.append(i)
|
||||
|
||||
print("Union:\t",res)
|
||||
|
||||
def intersection():
|
||||
res =[]
|
||||
for i in SetA:
|
||||
if i in SetB:
|
||||
res.append(i)
|
||||
|
||||
print("Intersection:\t",res)
|
||||
|
||||
def difference():
|
||||
res =[]
|
||||
|
||||
for i in SetA:
|
||||
if i not in SetB:
|
||||
res.append(i)
|
||||
|
||||
for i in SetB:
|
||||
if i not in SetA:
|
||||
res.append(i)
|
||||
print("Difference:\t",res)
|
||||
|
||||
|
||||
def find():
|
||||
t = int(input("1. SET A\n2. SET B\nChoose an option (1/2):\t"))
|
||||
s=False
|
||||
s = int(input("Element to search:\t"))
|
||||
if t==1:
|
||||
for i in range(len(SetA)):
|
||||
if s == SetA[i]:
|
||||
s = True
|
||||
if s == True:
|
||||
print("Element exists.")
|
||||
else:
|
||||
print("Element does not exist.")
|
||||
elif t==2:
|
||||
for i in range(len(SetB)):
|
||||
if s == SetB[i]:
|
||||
s = True
|
||||
if s == True:
|
||||
print("Element exists.")
|
||||
else:
|
||||
print("Element does not exist.")
|
||||
|
||||
def remove():
|
||||
t = int(input("1. SET A\n2. SET B\nChoose an option (1/2):\t"))
|
||||
s=False
|
||||
s1 = int(input("Element to be deleted:\t"))
|
||||
if t==1:
|
||||
for i in range(len(SetA)):
|
||||
if s1 == SetA[i]:
|
||||
s = True
|
||||
if s == True:
|
||||
print("Element exists.")
|
||||
SetA.remove(s1)
|
||||
print("After deletion:\t",SetA)
|
||||
else:
|
||||
print("Element does not exist in SET A.")
|
||||
elif t==2:
|
||||
for i in range(len(SetB)):
|
||||
if s1 == SetB[i]:
|
||||
s = True
|
||||
if s == True:
|
||||
print("Element exists.")
|
||||
SetB.remove(s1)
|
||||
print("After deletion:\t",SetB)
|
||||
else:
|
||||
print("Element does not exist in SET B.")
|
||||
|
||||
def size():
|
||||
ct=0
|
||||
for i in SetA:
|
||||
ct+=1
|
||||
print("Size of SET A:\t",ct)
|
||||
ct=0
|
||||
for i in SetB:
|
||||
ct+=1
|
||||
print("Size of SET B:\t",ct)
|
||||
|
||||
def subset():
|
||||
set5 = []
|
||||
flag=False
|
||||
for i in SetA:
|
||||
if i in SetB:
|
||||
set5.append(i)
|
||||
flag=True
|
||||
|
||||
if flag==True:
|
||||
print("Subset",set5)
|
||||
print("SET B is a subset of SET A.")
|
||||
else:
|
||||
print("SET B is NOT Subset of SET A.")
|
||||
|
||||
while True:
|
||||
print("--- SET OPERATIONS ---")
|
||||
print("1 -> Insert")
|
||||
print("2 -> Display")
|
||||
print("3 -> Union ")
|
||||
print("4 -> Intersection")
|
||||
print("5 -> Difference")
|
||||
print("6 -> Size of Sets")
|
||||
print("7 -> Find")
|
||||
print("8 -> Delete an Element")
|
||||
print("9 -> Subset")
|
||||
print("0 -> Exit")
|
||||
|
||||
ch = int(input("Choose an option (0-9):\t"))
|
||||
|
||||
if ch==1:
|
||||
insert()
|
||||
elif ch==2:
|
||||
display()
|
||||
elif ch==3:
|
||||
union()
|
||||
elif ch==4:
|
||||
intersection()
|
||||
elif ch==5:
|
||||
difference()
|
||||
elif ch==6:
|
||||
size()
|
||||
elif ch==7:
|
||||
find()
|
||||
elif ch==8:
|
||||
remove()
|
||||
elif ch==9:
|
||||
subset()
|
||||
elif ch==0:
|
||||
print("\n## END OF CODE\n")
|
||||
break
|
||||
else:
|
||||
print("Please choose a valid option (0-9).")
|
||||
# END OF CODE
|
247
Codes/Practical-B11 (Binary Search Tree).cpp
Normal file
247
Codes/Practical-B11 (Binary Search Tree).cpp
Normal file
@ -0,0 +1,247 @@
|
||||
/*
|
||||
THIS CODE HAS BEEN TESTED AND IS FULLY OPERATIONAL.
|
||||
|
||||
Problem Statement: A Dictionary stores keywords & 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 Binary Search Tree for implementation.
|
||||
|
||||
Code from DataStructuresAndAlgorithms (SPPU - Second Year - Computer Engineering - Content) repository on KSKA Git: https://git.kska.io/sppu-se-comp-content/DataStructuresAndAlgorithms/
|
||||
*/
|
||||
|
||||
// BEGINNING OF CODE
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
using namespace std;
|
||||
|
||||
class node {
|
||||
public:
|
||||
string key, value;
|
||||
node *left, *right;
|
||||
node() {
|
||||
key = "";
|
||||
value = "";
|
||||
left = NULL;
|
||||
right = NULL;
|
||||
}
|
||||
node(string key, string value) {
|
||||
this->key = key;
|
||||
this->value = value;
|
||||
left = NULL;
|
||||
right = NULL;
|
||||
}
|
||||
};
|
||||
|
||||
class bst {
|
||||
public:
|
||||
node *root;
|
||||
bst(){
|
||||
root = NULL;
|
||||
}
|
||||
bst(string key, string value) {
|
||||
root = new node(key, value);
|
||||
}
|
||||
|
||||
bool insert(string, string);
|
||||
string search(string);
|
||||
bool update(string, string);
|
||||
bool delete_key(string);
|
||||
void display(node *cur);
|
||||
|
||||
};
|
||||
bool bst::insert(string key, string value) {
|
||||
if (root == NULL) {
|
||||
root = new node(key, value);
|
||||
return 1;
|
||||
}
|
||||
|
||||
node *temp, *prev;
|
||||
prev = root;
|
||||
temp = root;
|
||||
while (temp != NULL) {
|
||||
prev = temp;
|
||||
if (temp->key == key) {
|
||||
return 0;
|
||||
} else if (temp->key < key) {
|
||||
temp = temp->right;
|
||||
} else {
|
||||
temp = temp->left;
|
||||
}
|
||||
}
|
||||
if (prev->key < key) {
|
||||
prev->right = new node(key, value);
|
||||
} else {
|
||||
prev->left = new node(key, value);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
string bst::search(string key) {
|
||||
node *temp = root;
|
||||
while (temp != NULL) {
|
||||
if (temp->key == key) {
|
||||
return temp->value;
|
||||
} else if (temp->key < key) {
|
||||
temp = temp->right;
|
||||
} else {
|
||||
temp = temp->left;
|
||||
}
|
||||
}
|
||||
return "\0";
|
||||
}
|
||||
|
||||
bool bst::update(string key, string value) {
|
||||
node *temp;
|
||||
temp = root;
|
||||
while (temp != NULL) {
|
||||
if (temp->key == key) {
|
||||
temp->value = value;
|
||||
return 1;
|
||||
} else if (temp->key < key) {
|
||||
temp = temp->right;
|
||||
} else {
|
||||
temp = temp->left;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool bst::delete_key(string key) {
|
||||
node **cur = &root;
|
||||
while (*cur != nullptr) {
|
||||
if ((*cur)->key == key) {
|
||||
node *temp = *cur;
|
||||
if (temp->left == nullptr)
|
||||
*cur = temp->right;
|
||||
else if (temp->right == nullptr)
|
||||
*cur = temp->left;
|
||||
else {
|
||||
node *successor = temp->right;
|
||||
while (successor->left != nullptr)
|
||||
successor = successor->left;
|
||||
temp->key = successor->key;
|
||||
temp->value = successor->value;
|
||||
cur = &temp->right;
|
||||
key = successor->key;
|
||||
continue;
|
||||
}
|
||||
delete temp;
|
||||
return true;
|
||||
} else if ((*cur)->key < key)
|
||||
cur = &((*cur)->right);
|
||||
else
|
||||
cur = &((*cur)->left);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void bst::display(node *cur) {
|
||||
if (cur == NULL) {
|
||||
return;
|
||||
}
|
||||
display(cur->left);
|
||||
cout << cur->key << " : " << cur->value << endl;
|
||||
display(cur->right);
|
||||
}
|
||||
|
||||
int main() {
|
||||
bst tree;
|
||||
int ch;
|
||||
string k, v, ans;
|
||||
do {
|
||||
cout << "--- MAIN MENU ---" << endl;
|
||||
cout << "1 -> Insert" << endl;
|
||||
cout << "2 -> Search" << endl;
|
||||
cout << "3 -> Update" << endl;
|
||||
cout << "4 -> Delete" << endl;
|
||||
cout << "5 -> Display Ascending" << endl;
|
||||
cout << "0 -> Exit" << endl;
|
||||
cout << "Choose an option (0-5):\t";
|
||||
cin >> ch;
|
||||
switch (ch) {
|
||||
case 1:
|
||||
cout << "Key (word) to insert:\t";
|
||||
cin >> k;
|
||||
cout << "Value (meaning):\t";
|
||||
cin >> v;
|
||||
if (tree.insert(k, v)) {
|
||||
cout << "Element insertion successful." << endl;
|
||||
} else {
|
||||
cout << "Element already exists." << endl;
|
||||
}
|
||||
break;
|
||||
case 2:
|
||||
cout << "Key (word) to search:\t";
|
||||
cin >> k;
|
||||
ans = tree.search(k);
|
||||
if (ans == "\0") {
|
||||
cout << "Element does not exist." << endl;
|
||||
} else {
|
||||
cout << "Value (meaning) is:\t" << ans << endl;
|
||||
}
|
||||
break;
|
||||
case 3:
|
||||
cout << "Key (word) to update:\t";
|
||||
cin >> k;
|
||||
cout << "New value (meaning):\t";
|
||||
cin >> v;
|
||||
if (tree.update(k, v)) {
|
||||
cout << "Element updated." << endl;
|
||||
} else {
|
||||
cout << "Element does not exist." << endl;
|
||||
}
|
||||
break;
|
||||
case 4:
|
||||
cout << "Key (word) to delete:\t";
|
||||
cin >> k;
|
||||
if (tree.delete_key(k)) {
|
||||
cout << "Element deletion successful." << endl;
|
||||
} else {
|
||||
cout << "Element does not exist." << endl;
|
||||
}
|
||||
break;
|
||||
case 5:
|
||||
cout << "Data in ascending order:\t" << endl;
|
||||
tree.display(tree.root);
|
||||
break;
|
||||
case 0:
|
||||
cout << "\n// END OF CODE\n";
|
||||
break;
|
||||
default:
|
||||
cout << "Please choose a valid option (0-5)." << endl;
|
||||
break;
|
||||
}
|
||||
} while (ch != 0);
|
||||
return 0;
|
||||
}
|
||||
// END OF CODE
|
||||
|
||||
/*
|
||||
SAMPLE OUTPUT:
|
||||
|
||||
Choose an option (0-5): 1
|
||||
Key (word) to insert: testWord
|
||||
Value (meaning): life
|
||||
Element insertion successful.
|
||||
|
||||
Choose an option (0-5): 1
|
||||
Key (word) to insert: test2
|
||||
Value (meaning): sdfj
|
||||
Element insertion successful.
|
||||
|
||||
Choose an option (0-5): 2
|
||||
Key (word) to search: test2
|
||||
Value (meaning) is: sdfj
|
||||
|
||||
Choose an option (0-5): 3
|
||||
Key (word) to update: test2
|
||||
New value (meaning): val
|
||||
Element updated.
|
||||
|
||||
Choose an option (0-5): 5
|
||||
Data in ascending order:
|
||||
test2 : val
|
||||
testWord : life
|
||||
|
||||
Choose an option (0-5): 0
|
||||
|
||||
// END OF CODE
|
||||
|
||||
*/
|
123
Codes/Practical-B5 (Tree).cpp
Normal file
123
Codes/Practical-B5 (Tree).cpp
Normal file
@ -0,0 +1,123 @@
|
||||
/*
|
||||
THIS CODE HAS BEEN TESTED AND IS FULLY OPERATIONAL.
|
||||
|
||||
Problem Statement: 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.
|
||||
|
||||
Code from DataStructuresAndAlgorithms (SPPU - Second Year - Computer Engineering - Content) repository on KSKA Git: https://git.kska.io/sppu-se-comp-content/DataStructuresAndAlgorithms/
|
||||
*/
|
||||
|
||||
// BEGINNING OF CODE
|
||||
#include<iostream>
|
||||
#include<string.h>
|
||||
|
||||
using namespace std;
|
||||
|
||||
struct node{
|
||||
string label;
|
||||
int ch_count;
|
||||
|
||||
struct node* child[10];
|
||||
|
||||
}*root;
|
||||
|
||||
class GT{
|
||||
|
||||
public:
|
||||
GT(){
|
||||
root = NULL;
|
||||
}
|
||||
|
||||
string lbel;
|
||||
int count;
|
||||
|
||||
void create(){
|
||||
root = new node;
|
||||
|
||||
cout<<"Name of the book:\t";
|
||||
cin>>root->label;
|
||||
cout<<"Number of chapters:\t";
|
||||
cin>>root->ch_count;
|
||||
|
||||
for(int i=0;i<root->ch_count;i++){
|
||||
|
||||
root->child[i] = new node;
|
||||
cout<<"Name of chapter "<< i+1 <<":\t";
|
||||
cin>>root->child[i]->label;
|
||||
cout<<"Number of sections:\t";
|
||||
cin>>root->child[i]->ch_count;
|
||||
|
||||
for(int j=0;j<root->child[i]->ch_count;j++){
|
||||
root->child[i]->child[j] = new node;
|
||||
cout<<"Name of section "<< i+1 <<" - "<< j+1<< ":\t";
|
||||
cin>>root->child[i]->child[j]->label;
|
||||
cout<<"Number of sub-sections:\t";
|
||||
cin>>root->child[i]->child[j]->ch_count;
|
||||
|
||||
for(int k=0;k<root->child[i]->child[j]->ch_count;k++){
|
||||
root->child[i]->child[j]->child[k] = new node;
|
||||
cout<<"Name of sub-section "<< i+1 <<" - "<< j+1<< " - "<< k+1<< ":\t";
|
||||
cin>>root->child[i]->child[j]->label;
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void display(node * r){
|
||||
cout<<endl<<"Name of book:\t";
|
||||
cout<<root->label<<endl;
|
||||
cout<<endl<<"Number of chapters:\t";
|
||||
cout<<root->ch_count<<endl;
|
||||
|
||||
for(int i=0;i<root->ch_count;i++){
|
||||
cout<<endl<<"Name of chapter:\t";
|
||||
cout<<root->child[i]->label<<endl;
|
||||
cout<<endl<<"Number of sections:\t";
|
||||
cout<<root->child[i]->ch_count<<endl;
|
||||
|
||||
for(int j=0;j<root->child[i]->ch_count;j++){
|
||||
cout<<"\t\t"<< i+1 <<" - "<< j+1<< " Name of sections: ";
|
||||
cout<<root->child[i]->child[j]->label<<endl;
|
||||
cout<<"\t\tNumber of sub-section: ";
|
||||
cout<<root->child[i]->child[j]->ch_count<<endl;
|
||||
|
||||
for(int k=0;k<root->child[i]->child[j]->ch_count;k++){
|
||||
cout<<"\t\t\t"<< i+1 <<" - "<< j+1<< " - "<< k+1<< " Name of sub-section: ";
|
||||
cout<<root->child[i]->child[j]->label<<endl;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
int main(){
|
||||
GT g;
|
||||
|
||||
while(1){
|
||||
cout<<"--- MAIN MENU ---"<<endl;
|
||||
cout<<"1 -> Add book info"<<endl;
|
||||
cout<<"2 -> Display info"<<endl;
|
||||
cout<<"3 ->Exit"<<endl;
|
||||
cout<<"Choose an option (1-3):\t";
|
||||
int ch;
|
||||
cin>>ch;
|
||||
|
||||
switch(ch){
|
||||
case 1:
|
||||
g.create();
|
||||
break;
|
||||
case 2:
|
||||
g.display(root);
|
||||
break;
|
||||
case 3:
|
||||
cout<<endl<<"// END OF CODE\n\n";
|
||||
exit(0);
|
||||
break;
|
||||
default:
|
||||
cout<<"Please choose a valid option (1-3).";
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// END OF CODE
|
150
Codes/Practical-B7 (Expression Tree).cpp
Normal file
150
Codes/Practical-B7 (Expression Tree).cpp
Normal file
@ -0,0 +1,150 @@
|
||||
/*
|
||||
THIS CODE HAS BEEN TESTED AND IS FULLY OPERATIONAL.
|
||||
|
||||
Problem Statement: Construct an expression tree from the given prefix expression eg. +--a*bc/def and traverse it using postordertraversal(non recursive) and then delete the entire tree.
|
||||
|
||||
Code from DataStructuresAndAlgorithms (SPPU - Second Year - Computer Engineering - Content) repository on KSKA Git: https://git.kska.io/sppu-se-comp-content/DataStructuresAndAlgorithms/
|
||||
*/
|
||||
|
||||
// BEGINNING OF CODE
|
||||
#include<iostream>
|
||||
#include<string.h>
|
||||
using namespace std;
|
||||
|
||||
struct node{
|
||||
char data;
|
||||
node *left;
|
||||
node *right;
|
||||
};
|
||||
|
||||
class tree{
|
||||
char prefix[50];
|
||||
public:
|
||||
node *top;
|
||||
void expression(char []);
|
||||
void display(node *);
|
||||
void deletion(node *node);
|
||||
};
|
||||
|
||||
class stack1{
|
||||
public:
|
||||
node *data[30];
|
||||
int top;
|
||||
stack1(){
|
||||
top=-1;
|
||||
}
|
||||
int empty(){
|
||||
if(top==-1){
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
void push(node *p){
|
||||
data[++top]=p;
|
||||
}
|
||||
|
||||
node *pop(){
|
||||
|
||||
return(data[top--]);
|
||||
}
|
||||
};
|
||||
|
||||
void tree::expression(char prefix[]){
|
||||
char c;
|
||||
stack1 s;
|
||||
node *t1,*t2;
|
||||
int len,i;
|
||||
len=strlen(prefix);
|
||||
for(i=len-1;i>=0;i--){
|
||||
top = new node;
|
||||
top->left=NULL;
|
||||
top->right=NULL;
|
||||
|
||||
if(isalpha(prefix[i])){
|
||||
top->data=prefix[i];
|
||||
s.push(top);
|
||||
}else if(prefix[i]=='+'||prefix[i]=='-'||prefix[i]=='*'||prefix[i]=='/'){
|
||||
t2 = s.pop();
|
||||
t1=s.pop();
|
||||
top->data=prefix[i];
|
||||
top->left = t2;
|
||||
top->right=t1;
|
||||
s.push(top);
|
||||
}
|
||||
}
|
||||
top = s.pop();
|
||||
}
|
||||
|
||||
void tree::display(node *top){
|
||||
stack1 s1,s2;
|
||||
|
||||
node *T = top;
|
||||
s1.push(T);
|
||||
while(!s1.empty()){
|
||||
T = s1.pop();
|
||||
s2.push(T);
|
||||
|
||||
if(T->left!=NULL){
|
||||
s1.push(T->left);
|
||||
}
|
||||
|
||||
if(T->right!=NULL){
|
||||
s1.push(T->right);
|
||||
}
|
||||
}
|
||||
|
||||
while(!s2.empty()){
|
||||
|
||||
top = s2.pop();
|
||||
cout<<top->data;
|
||||
|
||||
}
|
||||
cout<<endl;
|
||||
}
|
||||
|
||||
void tree::deletion(node *node){
|
||||
if(node==NULL){
|
||||
return;
|
||||
}
|
||||
deletion(node->left);
|
||||
deletion(node->right);
|
||||
cout<<"Deleting node: "<<node->data<<endl;
|
||||
free(node);
|
||||
}
|
||||
|
||||
int main(){
|
||||
tree t;
|
||||
char exp1[20];
|
||||
|
||||
int ch;
|
||||
do{
|
||||
cout<<"1 -> Enter prefix expression"<<endl;
|
||||
cout<<"2 -> Display postfix Expression"<<endl;
|
||||
cout<<"3 -> Deletion"<<endl;
|
||||
cout<<"4 -> Exit"<<endl;
|
||||
cout<<"Choose an option (1-4):\t";
|
||||
cin>>ch;
|
||||
|
||||
switch(ch){
|
||||
|
||||
case 1:
|
||||
cout<<"Enter the expression (eg.: +--a*bc/def):\t";
|
||||
cin>>exp1;
|
||||
t.expression(exp1);
|
||||
break;
|
||||
case 2:
|
||||
t.display(t.top);
|
||||
break;
|
||||
case 3:
|
||||
t.deletion(t.top);
|
||||
break;
|
||||
case 4:
|
||||
cout<<"\n// END OF CODE\n"<<endl;
|
||||
break;
|
||||
default:
|
||||
cout<<"Choose a valid option (1-4).";
|
||||
break;
|
||||
}
|
||||
}while(ch!=4);
|
||||
}
|
||||
// END OF CODE
|
251
Codes/Practical-C13 (Adjacent List and Matrix of Graph).cpp
Normal file
251
Codes/Practical-C13 (Adjacent List and Matrix of Graph).cpp
Normal file
@ -0,0 +1,251 @@
|
||||
/*
|
||||
THIS CODE HAS BEEN TESTED AND IS FULLY OPERATIONAL.
|
||||
|
||||
Problem Statement: 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.
|
||||
|
||||
Code from DataStructuresAndAlgorithms (SPPU - Second Year - Computer Engineering - Content) repository on KSKA Git: https://git.kska.io/sppu-se-comp-content/DataStructuresAndAlgorithms/
|
||||
*/
|
||||
|
||||
// BEGINNING OF CODE
|
||||
#include<iostream>
|
||||
using namespace std;
|
||||
|
||||
class DFS {
|
||||
public:
|
||||
int top, f, r, x;
|
||||
int** adjList;
|
||||
int data[30], data1[30];
|
||||
int visit[20];
|
||||
int g[10][10];
|
||||
void create();
|
||||
void display();
|
||||
void createList();
|
||||
void displayList();
|
||||
void dfs();
|
||||
void bfs();
|
||||
|
||||
DFS() {
|
||||
top = -1;
|
||||
f = r = -1;
|
||||
adjList = NULL;
|
||||
}
|
||||
|
||||
int pop() {
|
||||
if(top != -1)
|
||||
{
|
||||
int y = data[top];
|
||||
top--;
|
||||
return y;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
void push(int t) {
|
||||
top++;
|
||||
data[top] = t;
|
||||
}
|
||||
|
||||
void enqueue(int t) {
|
||||
if(f == -1 && r == -1)
|
||||
{
|
||||
f++;
|
||||
r++;
|
||||
data1[r] = t;
|
||||
}
|
||||
else
|
||||
{
|
||||
r++;
|
||||
data1[r] = t;
|
||||
}
|
||||
}
|
||||
|
||||
int dequeue() {
|
||||
if(f == -1 && r == -1)
|
||||
return -1;
|
||||
else
|
||||
{
|
||||
int y = data1[f];
|
||||
if(f == r)
|
||||
f = r = -1;
|
||||
else
|
||||
f++;
|
||||
return y;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
void DFS::create() {
|
||||
cout<<"Number of nodes:\t";
|
||||
cin>>x;
|
||||
for(int i = 0; i < x; i++)
|
||||
{
|
||||
for(int j = 0; j < x; j++)
|
||||
{
|
||||
cout<<endl<<"Enter link status of graph from node:\t";
|
||||
cin>>g[i][j];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void DFS::createList() {
|
||||
cout << "Number of nodes:\t";
|
||||
cin >> x;
|
||||
adjList = new int*[x];
|
||||
for (int i = 0; i < x; ++i)
|
||||
{
|
||||
adjList[i] = new int[x];
|
||||
for (int j = 0; j < x; ++j)
|
||||
{
|
||||
adjList[i][j] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
int connected, node;
|
||||
for (int i = 0; i < x; i++)
|
||||
{
|
||||
cout << "\nEnter number of nodes connected to node " << i << ": ";
|
||||
cin >> connected;
|
||||
cout << "\nEnter the nodes connected to node " << i << ": ";
|
||||
for (int j = 0; j < connected; j++)
|
||||
{
|
||||
cin >> node;
|
||||
adjList[i][node] = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void DFS::displayList()
|
||||
{
|
||||
for (int i = 0; i < x; i++)
|
||||
{
|
||||
cout << "\nNode " << i << " is connected to: ";
|
||||
for (int j = 0; j < x; j++)
|
||||
{
|
||||
if (adjList[i][j] == 1)
|
||||
{
|
||||
cout << j << " ";
|
||||
}
|
||||
}
|
||||
}
|
||||
cout<<"\n";
|
||||
}
|
||||
|
||||
void DFS::display()
|
||||
{
|
||||
cout<< " ";
|
||||
for (int i = 0; i < x; i++)
|
||||
{
|
||||
cout<<" "<<i;
|
||||
}
|
||||
cout<<"\n";
|
||||
for (int i = 0; i < x; i++)
|
||||
{
|
||||
cout<<i<<" |";
|
||||
for (int j = 0; j < x; j++)
|
||||
{
|
||||
cout<<" "<< g[i][j];
|
||||
}
|
||||
cout<<"\n";
|
||||
}
|
||||
}
|
||||
|
||||
void DFS::dfs()
|
||||
{
|
||||
for(int i = 0; i < x; i++)
|
||||
visit[i] = 0;
|
||||
DFS s;
|
||||
int v1;
|
||||
cout<<"\nEnter starting node: ";
|
||||
cin>>v1;
|
||||
s.push(v1);
|
||||
cout<<"DFS traversal is: ";
|
||||
while(s.top != -1)
|
||||
{
|
||||
int v = s.pop();
|
||||
if(visit[v] == 0)
|
||||
{
|
||||
cout<<" "<<v;
|
||||
visit[v] = 1;
|
||||
for(int i = x-1; i > -1; i--)
|
||||
{
|
||||
if(g[v][i] == 1 && visit[i] == 0)
|
||||
{
|
||||
s.push(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void DFS::bfs()
|
||||
{
|
||||
for(int i = 0; i < x; i++)
|
||||
visit[i] = 0;
|
||||
DFS s;
|
||||
int v1;
|
||||
cout<<"\nEnter starting node: ";
|
||||
cin>>v1;
|
||||
s.enqueue(v1);
|
||||
cout<<"\nBFS traversal is: ";
|
||||
while(s.f != -1 && s.r != -1)
|
||||
{
|
||||
int v = s.dequeue();
|
||||
if(visit[v] == 0)
|
||||
{
|
||||
cout<<" "<<v;
|
||||
visit[v] = 1;
|
||||
for(int i = 0; i < x; i++)
|
||||
{
|
||||
if(adjList[v][i] == 1 && visit[i] == 0)
|
||||
{
|
||||
s.enqueue(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
cout<<"\n";
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
DFS obj;
|
||||
bool flag = true;
|
||||
int choice;
|
||||
while(flag)
|
||||
{
|
||||
cout<<"\n***YOUR CHOICES ARE****\n";
|
||||
cout<<"\n1. Create Graph (Matrix) \n2. DFS Traversal (Using Matrix) \n3. Create Graph (List) \n4. BFS Traversal (Using List) \n5. Exit";
|
||||
cout<<"\nEnter choice: ";
|
||||
cin>>choice;
|
||||
switch(choice)
|
||||
{
|
||||
case 1:
|
||||
obj.create();
|
||||
obj.display();
|
||||
break;
|
||||
|
||||
case 2:
|
||||
obj.dfs();
|
||||
break;
|
||||
|
||||
case 3:
|
||||
obj.createList();
|
||||
obj.displayList();
|
||||
break;
|
||||
|
||||
case 4:
|
||||
obj.bfs();
|
||||
break;
|
||||
|
||||
case 5:
|
||||
flag = false;
|
||||
break;
|
||||
|
||||
default:
|
||||
cout<<"\nEnter Valid Choice!";
|
||||
break;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
// END OF CODE
|
171
Codes/Practical-C15 (Prims).cpp
Executable file
171
Codes/Practical-C15 (Prims).cpp
Executable file
@ -0,0 +1,171 @@
|
||||
/*
|
||||
THIS CODE HAS BEEN TESTED AND IS FULLY OPERATIONAL.
|
||||
|
||||
Problem Statement: You have a business with several offices; you want to lease phone lines to connect them up with each other; and the phone company charges different amounts of money to connect different pairs of cities. You want a set of lines that connects all your offices with a minimum total cost. Solve the problem by suggesting appropriate data structures.
|
||||
|
||||
Code from DataStructuresAndAlgorithms (SPPU - Second Year - Computer Engineering - Content) repository on KSKA Git: https://git.kska.io/sppu-se-comp-content/DataStructuresAndAlgorithms/
|
||||
*/
|
||||
|
||||
// BEGINNING OF CODE
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
#include <cstdint>
|
||||
#define MAX_NUM_CITIES 10
|
||||
|
||||
using namespace std;
|
||||
|
||||
struct edge {
|
||||
int start;
|
||||
int end;
|
||||
int wt;
|
||||
};
|
||||
|
||||
class graph {
|
||||
int adj_mat[MAX_NUM_CITIES][MAX_NUM_CITIES] = {0};
|
||||
string city_names[MAX_NUM_CITIES];
|
||||
int city_count;
|
||||
edge mst[MAX_NUM_CITIES - 1];
|
||||
void add_to_list(vector<edge> &, edge);
|
||||
int cost;
|
||||
|
||||
public:
|
||||
graph();
|
||||
|
||||
void prims_algo(int);
|
||||
void display_mst();
|
||||
};
|
||||
|
||||
void graph::add_to_list(vector<edge> &list, edge e) {
|
||||
list.push_back(e);
|
||||
for (int i = list.size() - 1; i > 0; i--) {
|
||||
if (list[i].wt < list[i - 1].wt) {
|
||||
swap(list[i], list[i - 1]);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
graph::graph() {
|
||||
cost = 0;
|
||||
cout << "Number of cities are (1-" << MAX_NUM_CITIES << "):\t";
|
||||
cin >> city_count;
|
||||
city_count = (city_count > MAX_NUM_CITIES) ? MAX_NUM_CITIES : city_count;
|
||||
|
||||
for (int i = 0; i < city_count; i++) {
|
||||
cout << "Enter city:\n" << i + 1 << ":\t";
|
||||
cin >> city_names[i];
|
||||
}
|
||||
|
||||
// initialize all matrix with max value
|
||||
for (int i = 0; i < city_count; i++)
|
||||
for (int j = 0; j < city_count; j++) adj_mat[i][j] = INT32_MAX;
|
||||
|
||||
int num_pairs;
|
||||
cout << "Number of city pairs are:\t";
|
||||
cin >> num_pairs;
|
||||
cout << "City codes are:\t" << endl;
|
||||
for (int i = 0; i < city_count; i++) {
|
||||
cout << i << " - " << city_names[i] << endl;
|
||||
}
|
||||
int x, y, wt;
|
||||
for (int i = 0; i < num_pairs; i++) {
|
||||
cout << "Enter pair:\n" << i + 1 << ":\t";
|
||||
cin >> x >> y;
|
||||
cout << "Enter cost between city " << city_names[x] << " & city "
|
||||
<< city_names[y] << ":\t";
|
||||
cin >> wt;
|
||||
adj_mat[x][y] = wt;
|
||||
adj_mat[y][x] = wt;
|
||||
}
|
||||
}
|
||||
|
||||
void graph::prims_algo(int start) {
|
||||
bool visited[MAX_NUM_CITIES] = {0};
|
||||
int visited_count = 1;
|
||||
visited[start] = 1;
|
||||
vector<edge> adj;
|
||||
for (int i = 0; i < city_count; i++) {
|
||||
if (adj_mat[start][i] != INT32_MAX) {
|
||||
edge e;
|
||||
e.start = start;
|
||||
e.end = i;
|
||||
e.wt = adj_mat[start][i];
|
||||
add_to_list(adj, e);
|
||||
}
|
||||
}
|
||||
|
||||
while (visited_count != city_count) {
|
||||
edge m = adj.front();
|
||||
adj.erase(adj.begin());
|
||||
if (!visited[m.end]) {
|
||||
mst[visited_count - 1] = m;
|
||||
cost += m.wt;
|
||||
for (int i = 0; i < city_count; i++) {
|
||||
if (adj_mat[m.end][i] != INT32_MAX) {
|
||||
edge e;
|
||||
e.start = m.end;
|
||||
e.end = i;
|
||||
e.wt = adj_mat[e.start][i];
|
||||
add_to_list(adj, e);
|
||||
}
|
||||
}
|
||||
visited[m.end] = 1;
|
||||
visited_count++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void graph::display_mst() {
|
||||
cout << "Most efficient network is:\t" << endl;
|
||||
|
||||
for (int i = 0; i < city_count - 1; i++) {
|
||||
cout << city_names[mst[i].start] << " to " << city_names[mst[i].end]
|
||||
<< " of weight " << mst[i].wt << endl;
|
||||
}
|
||||
cout << endl << "The cost of network is:\t" << cost << endl;
|
||||
}
|
||||
|
||||
int main() {
|
||||
// prims algo
|
||||
graph g;
|
||||
int start;
|
||||
cout << "Enter beginning city:\t";
|
||||
cin >> start;
|
||||
start = (start > MAX_NUM_CITIES - 1) ? 0 : start;
|
||||
g.prims_algo(start);
|
||||
g.display_mst();
|
||||
return 0;
|
||||
}
|
||||
// END OF CODE
|
||||
|
||||
/*
|
||||
SAMPLE OUTPUT:
|
||||
|
||||
Number of cities are (1-10): 3
|
||||
Enter city:
|
||||
1: Paris
|
||||
Enter city:
|
||||
2: Pune
|
||||
Enter city:
|
||||
3: Nagar
|
||||
Number of city pairs are: 2
|
||||
City codes are:
|
||||
0 - Paris
|
||||
1 - Pune
|
||||
2 - Nagar
|
||||
Enter pair:
|
||||
1: 1
|
||||
2
|
||||
Enter cost between city Pune & city Nagar: 5
|
||||
Enter pair:
|
||||
2: 0
|
||||
1
|
||||
Enter cost between city Paris & city Pune: 10
|
||||
Enter beginning city: Pune
|
||||
Most efficient network is:
|
||||
Paris to Pune of weight 10
|
||||
Pune to Nagar of weight 5
|
||||
|
||||
The cost of network is: 15
|
||||
*/
|
85
Codes/Practical-D18 (OBST).cpp
Normal file
85
Codes/Practical-D18 (OBST).cpp
Normal file
@ -0,0 +1,85 @@
|
||||
/*
|
||||
THIS CODE HAS BEEN TESTED AND IS FULLY OPERATIONAL.
|
||||
|
||||
Problem Statement: 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?
|
||||
|
||||
Code from DataStructuresAndAlgorithms (SPPU - Second Year - Computer Engineering - Content) repository on KSKA Git: https://git.kska.io/sppu-se-comp-content/DataStructuresAndAlgorithms/
|
||||
*/
|
||||
|
||||
// BEGINNING OF CODE
|
||||
#include<iostream>
|
||||
using namespace std;
|
||||
|
||||
int find(int, int);
|
||||
void print(int, int);
|
||||
int c[20][20], w[20][20], r[20][20], p[20], q[20], k, m, i, j, n;
|
||||
char idtr[10][7];
|
||||
|
||||
int main()
|
||||
{
|
||||
cout<<"\nEnter number of identifiers: ";
|
||||
cin>>n;
|
||||
for(i = 1; i <= n; i++)
|
||||
{
|
||||
cout<<"Enter Identifier "<<i<<": ";
|
||||
cin>>idtr[i];
|
||||
}
|
||||
for(i = 1; i <= n; i++)
|
||||
{
|
||||
cout<<"Enter successful probability of "<<i<<": ";
|
||||
cin>>p[i];
|
||||
}
|
||||
for(i = 0; i <= n; i++)
|
||||
{
|
||||
cout<<"Enter unsuccessful probability of "<<i<<": ";
|
||||
cin>>q[i];
|
||||
}
|
||||
for(i = 0; i <= n; i++)
|
||||
{
|
||||
w[i][i] = q[i];
|
||||
c[i][i] = r[i][i] = 0;
|
||||
cout<<"\nW: "<<w[i][i]<<" | c: "<<c[i][i]<<" | r: "<<r[i][i];
|
||||
}
|
||||
for(i = 0; i < n; i++)
|
||||
{
|
||||
j = i + 1;
|
||||
w[i][j] = p[j] + q[j] + q[i];
|
||||
c[i][j] = w[i][j];
|
||||
r[i][j] = j;
|
||||
cout<<"\nW: "<<w[i][j]<<" | c: "<<c[i][j]<<" | r: "<<r[i][j];
|
||||
}
|
||||
for(m = 2; m <= n; m++)
|
||||
{
|
||||
for(i = 0; i <= n-m; i++)
|
||||
{
|
||||
j = i + m;
|
||||
w[i][j] = p[j] + q[j] + w[i][j-1];
|
||||
c[i][j] = 1000;
|
||||
for(k = i + 1; k <= j; k++)
|
||||
{
|
||||
int cost = c[i][k-1] + c[k][j];
|
||||
if(cost < c[i][j])
|
||||
{
|
||||
c[i][j] = cost;
|
||||
r[i][j] = k;
|
||||
}
|
||||
}
|
||||
c[i][j] += w[i][j];
|
||||
cout<<"\nW: "<<w[i][j]<<" | c: "<<c[i][j]<<" | r: "<<r[i][j];
|
||||
}
|
||||
}
|
||||
cout<<"\nFinal OBST is: ";
|
||||
print(0, n);
|
||||
return 0;
|
||||
}
|
||||
|
||||
void print(int i, int j)
|
||||
{
|
||||
if(i < j)
|
||||
cout<<"\n"<<idtr[r[i][j]];
|
||||
else
|
||||
return;
|
||||
print(i, r[i][j] - 1);
|
||||
print(r[i][j], j);
|
||||
}
|
||||
// END OF CODE
|
306
Codes/Practical-D19 (AVL Tree).cpp
Normal file
306
Codes/Practical-D19 (AVL Tree).cpp
Normal file
@ -0,0 +1,306 @@
|
||||
/*
|
||||
THIS CODE HAS BEEN TESTED AND IS FULLY OPERATIONAL.
|
||||
|
||||
Problem Statement: A Dictionary stores keywords & 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.
|
||||
|
||||
Code from DataStructuresAndAlgorithms (SPPU - Second Year - Computer Engineering - Content) repository on KSKA Git: https://git.kska.io/sppu-se-comp-content/DataStructuresAndAlgorithms/
|
||||
*/
|
||||
|
||||
// BEGINNING OF CODE
|
||||
#include<iostream>
|
||||
using namespace std;
|
||||
|
||||
class node
|
||||
{
|
||||
public:
|
||||
string key;
|
||||
string meaning;
|
||||
node *left;
|
||||
node *right;
|
||||
};
|
||||
|
||||
class AVL
|
||||
{
|
||||
node *root;
|
||||
public:
|
||||
AVL()
|
||||
{
|
||||
root=NULL;
|
||||
}
|
||||
|
||||
void create();
|
||||
node* insert(node *cur,node *temp);
|
||||
node* balance(node *temp);
|
||||
int dif(node *temp);
|
||||
int height(node *temp);
|
||||
int maximum(int a,int b);
|
||||
|
||||
node* LL(node *par);
|
||||
node* RR(node *par);
|
||||
node* LR(node *par);
|
||||
node* RL(node *par);
|
||||
|
||||
void ascending(node *temp);
|
||||
node* delete_n(node *root,string key1);
|
||||
void deleten();
|
||||
|
||||
node* extractmin(node *t);
|
||||
void descending(node *temp);
|
||||
void display();
|
||||
bool search(node *cur,string key1);
|
||||
void search_value();
|
||||
};
|
||||
|
||||
void AVL::create()
|
||||
{
|
||||
char answer;
|
||||
node *temp;
|
||||
do
|
||||
{
|
||||
temp=new node();
|
||||
cout<<endl<<"Enter keyword:\t";
|
||||
cin>>temp->key;
|
||||
cout<<"Enter meaning:\t";
|
||||
cin>>temp->meaning;
|
||||
temp->left=temp->right=NULL;
|
||||
|
||||
root=insert(root,temp);
|
||||
|
||||
cout<<endl<<"Add another word? (y/n):\t";
|
||||
cin>>answer;
|
||||
}
|
||||
while(answer=='y'||answer=='Y');
|
||||
}
|
||||
|
||||
|
||||
node* AVL::insert(node *cur,node *temp)
|
||||
{
|
||||
if(cur==NULL)
|
||||
{
|
||||
return temp;
|
||||
}
|
||||
if(temp->key<cur->key)
|
||||
{
|
||||
cur->left=insert(cur->left,temp);
|
||||
cur=balance(cur);
|
||||
}
|
||||
else if(temp->key>cur->key)
|
||||
{
|
||||
cur->right=insert(cur->right,temp);
|
||||
cur=balance(cur);
|
||||
}
|
||||
return cur;
|
||||
}
|
||||
|
||||
node* AVL::balance(node *temp)
|
||||
{
|
||||
int bal;
|
||||
bal=dif(temp);
|
||||
|
||||
if(bal>=2)
|
||||
{
|
||||
if(dif(temp->left)<0)
|
||||
temp=LR(temp);
|
||||
else
|
||||
temp=LL(temp);
|
||||
}
|
||||
else if(bal<=-2)
|
||||
{
|
||||
if(dif(temp->right)<0)
|
||||
temp=RR(temp);
|
||||
else
|
||||
temp=RL(temp);
|
||||
}
|
||||
return temp;
|
||||
}
|
||||
|
||||
|
||||
int AVL::dif(node *temp)
|
||||
{
|
||||
int l,r;
|
||||
l=height(temp->left);
|
||||
r=height(temp->right);
|
||||
return(l-r);
|
||||
}
|
||||
|
||||
int AVL::height(node *temp)
|
||||
{
|
||||
if(temp==NULL)
|
||||
return(-1);
|
||||
else
|
||||
return(max(height(temp->left),height(temp->right))+1);
|
||||
}
|
||||
|
||||
int AVL::maximum(int a,int b)
|
||||
{
|
||||
if(a>b)
|
||||
return a;
|
||||
else
|
||||
return b;
|
||||
}
|
||||
|
||||
node* AVL::LL(node *par)
|
||||
{
|
||||
node *temp,*temp1;
|
||||
temp=par->left;
|
||||
temp1=temp->right;
|
||||
temp->right=par;
|
||||
par->left=temp1;
|
||||
return temp;
|
||||
}
|
||||
|
||||
node* AVL::RR(node *par)
|
||||
{
|
||||
node *temp,*temp1;
|
||||
temp=par->right;
|
||||
temp1=temp->left;
|
||||
temp->left=par;
|
||||
par->right=temp1;
|
||||
return temp;
|
||||
}
|
||||
|
||||
node* AVL::LR(node *par)
|
||||
{
|
||||
par->left=RR(par->left);
|
||||
return(LL(par));
|
||||
}
|
||||
|
||||
node* AVL::RL(node *par)
|
||||
{
|
||||
par->right=LL(par->right);
|
||||
return(RR(par));
|
||||
}
|
||||
|
||||
void AVL::ascending(node *temp)
|
||||
{
|
||||
if(temp!=NULL)
|
||||
{
|
||||
ascending(temp->left);
|
||||
cout<<"\n\t"<<temp->key<<" : "<<temp->meaning;
|
||||
ascending(temp->right);
|
||||
}
|
||||
}
|
||||
|
||||
void AVL::descending(node *temp)
|
||||
{
|
||||
if(temp!=NULL)
|
||||
{
|
||||
descending(temp->right);
|
||||
cout<<"\n\t"<<temp->key<<" : "<<temp->meaning;
|
||||
descending(temp->left);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void AVL::display()
|
||||
{
|
||||
cout<<endl<<"Keywords in ascending order:\t";
|
||||
ascending(root);
|
||||
cout<<endl<<"Keywords in descending order:\t";
|
||||
descending(root);
|
||||
}
|
||||
|
||||
bool AVL::search(node *cur,string key1)
|
||||
{
|
||||
if(cur)
|
||||
{
|
||||
if(cur->key==key1)
|
||||
return true;
|
||||
if(cur->key>key1)
|
||||
return search(cur->left,key1);
|
||||
else
|
||||
return search(cur->right,key1);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void AVL::search_value()
|
||||
{
|
||||
string key2;
|
||||
cout<<endl<<"Keyword to search:\t";
|
||||
cin>>key2;
|
||||
if(search(root,key2))
|
||||
cout<<endl<<"Keyword exists in AVL tree.";
|
||||
else
|
||||
cout<<endl<<"Keyword does not exist in AVL tree.";
|
||||
}
|
||||
|
||||
|
||||
node* AVL::delete_n(node* cur,string key1)
|
||||
{
|
||||
if ( !cur)
|
||||
return cur;
|
||||
if ( key1 < cur->key )
|
||||
cur->left = delete_n(cur->left, key1);
|
||||
|
||||
else if( key1 > cur->key )
|
||||
cur->right = delete_n(cur->right, key1);
|
||||
|
||||
else
|
||||
{
|
||||
node *l = cur->left;
|
||||
node *r = cur->right;
|
||||
delete cur;
|
||||
if ( !r )
|
||||
return l;
|
||||
node *m=r;
|
||||
|
||||
while(m->left)
|
||||
m=m->left;
|
||||
m->right = extractmin(r);
|
||||
m->left = l;
|
||||
return balance(m);
|
||||
}
|
||||
return balance(cur);
|
||||
}
|
||||
|
||||
node* AVL::extractmin(node *t)
|
||||
{
|
||||
if ( !t->left )
|
||||
return t->right;
|
||||
t->left = extractmin(t->left);
|
||||
return balance(t);
|
||||
}
|
||||
|
||||
void AVL::deleten()
|
||||
{
|
||||
string key;
|
||||
cout<<endl<<"Keyword to delete:\t";
|
||||
cin>>key;
|
||||
root=delete_n(root,key);
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
char c;
|
||||
int ch;
|
||||
AVL a;
|
||||
do
|
||||
{
|
||||
cout<<endl<<"--- MAIN MENU ---";
|
||||
cout<<endl<<"1 -> Insert keyword";
|
||||
cout<<endl<<"2 -> Display AVL tree";
|
||||
cout<<endl<<"3 -> Search a keyword";
|
||||
cout<<endl<<"4 -> Delete a keyword";
|
||||
cout<<endl<<"Choose an option (1-4):\t";
|
||||
cin>>ch;
|
||||
switch(ch)
|
||||
{
|
||||
case 1 : a.create();
|
||||
break;
|
||||
case 2 : a.display();
|
||||
break;
|
||||
case 3 : a.search_value();
|
||||
break;
|
||||
case 4 : a.deleten();
|
||||
break;
|
||||
default : cout<<endl<<"Please choose a valid option (1-4).";
|
||||
}
|
||||
cout<<endl<<"Would you like to continue? (y/n):\t";
|
||||
cin>>c;
|
||||
}
|
||||
while(c=='y'||c=='Y');
|
||||
cout<<"\n\n// END OF CODE\n\n";
|
||||
return 0;
|
||||
}
|
||||
// END OF CODE
|
140
Codes/Practical-E20 (Priority Queue).cpp
Normal file
140
Codes/Practical-E20 (Priority Queue).cpp
Normal file
@ -0,0 +1,140 @@
|
||||
/*
|
||||
THIS CODE HAS BEEN TESTED AND IS FULLY OPERATIONAL.
|
||||
|
||||
Problem Statement: Consider a scenario for Hospital to cater services to different kinds of patients as Serious (top priority), b) non-serious (medium priority), c) General Checkup (Least priority). Implement the priority queue to cater services to the patients.
|
||||
|
||||
Code from DataStructuresAndAlgorithms (SPPU - Second Year - Computer Engineering - Content) repository on KSKA Git: https://git.kska.io/sppu-se-comp-content/DataStructuresAndAlgorithms/
|
||||
*/
|
||||
|
||||
// BEGINNING OF CODE
|
||||
#include<iostream>
|
||||
#include<string>
|
||||
#include <list>
|
||||
using namespace std;
|
||||
|
||||
// creating LinkList
|
||||
class Node
|
||||
{
|
||||
public :
|
||||
Node *next;
|
||||
int priority;
|
||||
string data;
|
||||
Node(string d,int prior){
|
||||
priority = prior;
|
||||
data = d;
|
||||
next = NULL;
|
||||
}
|
||||
};
|
||||
|
||||
class PriorityQueue{
|
||||
public:
|
||||
Node *front=NULL;
|
||||
|
||||
//d is patient name , prior is priority
|
||||
void insert(string d,int prior){
|
||||
Node *temp,*rear;
|
||||
temp = new Node(d,prior);
|
||||
if(front == NULL){
|
||||
front = temp;
|
||||
}
|
||||
else
|
||||
{
|
||||
//compare until position is found
|
||||
rear = front;
|
||||
while(
|
||||
rear->next!=NULL &&
|
||||
rear->next->priority >= prior
|
||||
){
|
||||
rear=rear->next;
|
||||
}
|
||||
temp->next = rear->next;
|
||||
rear->next = temp;
|
||||
}
|
||||
|
||||
}
|
||||
//to get name of first patient
|
||||
void peek(){
|
||||
cout<<"First patient is:\t"<<front->data;
|
||||
}
|
||||
void pop(){
|
||||
//to remove first patient
|
||||
if(front==NULL)
|
||||
return;
|
||||
front=front->next;
|
||||
}
|
||||
|
||||
//display all the queue
|
||||
void dis()
|
||||
{
|
||||
string currPrior="";
|
||||
if(front== NULL){
|
||||
cout<<endl<<"Empty queue."<<endl;
|
||||
return;
|
||||
}
|
||||
cout<<endl;
|
||||
Node *curr= front;
|
||||
while(curr!=NULL){
|
||||
//hardCode the category
|
||||
if(curr->priority!=0){
|
||||
if(curr->priority==3)
|
||||
currPrior="Serious patient";
|
||||
else if(curr->priority==2)
|
||||
currPrior="Not serious patient";
|
||||
else
|
||||
currPrior="General checkup";
|
||||
}
|
||||
cout<<curr->data<<" with priority:\t"<<currPrior<<endl;
|
||||
curr=curr->next;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
int main(){
|
||||
|
||||
string name;
|
||||
int priority,ch;
|
||||
|
||||
cout<<endl;
|
||||
PriorityQueue q;
|
||||
do{
|
||||
cout<<endl<<"--- MAIN MENU ---";
|
||||
cout<<endl<<"1 -> Add patient";
|
||||
cout<<endl<<"2 -> Remove patient";
|
||||
cout<<endl<<"3 -> Get all patients";
|
||||
cout<<endl<<"0 -> Exit";
|
||||
cout<<endl<<"Choose an option (0-3):\t";
|
||||
cin>>ch;
|
||||
|
||||
switch (ch)
|
||||
{
|
||||
case 1:
|
||||
{
|
||||
cout<<"Patient name is:\t";
|
||||
cin.ignore();
|
||||
getline(cin,name,'\n');
|
||||
cout<<endl<<"Enter priority (3-High, 2-Medium, 1-General):\t";
|
||||
cin>>priority;
|
||||
q.insert(name,priority);
|
||||
break;
|
||||
}
|
||||
case 2:
|
||||
{
|
||||
q.pop();
|
||||
break;
|
||||
}
|
||||
case 3:{
|
||||
q.dis();
|
||||
break;
|
||||
}
|
||||
case 0:
|
||||
cout<<endl<<"// END OF CODE\n\n";
|
||||
exit(1);
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
} while(ch!=0);
|
||||
}
|
||||
// END OF CODE
|
206
Codes/Practical-F23 (Student information).cpp
Normal file
206
Codes/Practical-F23 (Student information).cpp
Normal file
@ -0,0 +1,206 @@
|
||||
/*
|
||||
THIS CODE HAS BEEN TESTED AND IS FULLY OPERATIONAL.
|
||||
|
||||
Problem Statement: 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.
|
||||
|
||||
Code from DataStructuresAndAlgorithms (SPPU - Second Year - Computer Engineering - Content) repository on KSKA Git: https://git.kska.io/sppu-se-comp-content/DataStructuresAndAlgorithms/
|
||||
*/
|
||||
|
||||
// BEGINNING OF CODE
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
typedef struct student {
|
||||
int rollNo;
|
||||
char name[50];
|
||||
char div;
|
||||
char address[100];
|
||||
} student;
|
||||
|
||||
class studentDatabase {
|
||||
string fileName = "student_data.dat";
|
||||
|
||||
public:
|
||||
studentDatabase() {
|
||||
fstream fileObj(fileName);
|
||||
if (fileObj.fail()) {
|
||||
fileObj.open(fileName, ios::out);
|
||||
cout << "New file created." << endl;
|
||||
} else {
|
||||
cout << "File already exists." << endl;
|
||||
}
|
||||
fileObj.close();
|
||||
}
|
||||
|
||||
void addStudent();
|
||||
void searchStudent();
|
||||
void deleteStudent();
|
||||
void displayAll();
|
||||
};
|
||||
|
||||
void studentDatabase::searchStudent() {
|
||||
int roll;
|
||||
student s;
|
||||
bool status = false;
|
||||
|
||||
// take input of roll number to delete
|
||||
cout << "Roll number to search:\t";
|
||||
cin >> roll;
|
||||
|
||||
// opening files to delete a record
|
||||
ifstream readFile;
|
||||
readFile.open(fileName, ios::in | ios::binary);
|
||||
|
||||
// looking for record
|
||||
while (readFile.read((char*)&s, sizeof(student))) {
|
||||
if (s.rollNo == roll) {
|
||||
status = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
readFile.close();
|
||||
|
||||
if (status) {
|
||||
cout << "--- RECORD FOUND ---" << endl;
|
||||
cout << "Roll number:\t" << s.rollNo << endl;
|
||||
cout << "Name:\t" << s.name << endl;
|
||||
cout << "Division:\t" << s.div << endl;
|
||||
cout << "Address:\t" << s.address << endl;
|
||||
cout << "--- END OF RECORD ---" << endl;
|
||||
} else {
|
||||
cout << "Record not found." << endl;
|
||||
}
|
||||
}
|
||||
|
||||
void studentDatabase::deleteStudent() {
|
||||
int roll;
|
||||
student s;
|
||||
bool status = false;
|
||||
|
||||
// take input of roll number to delete
|
||||
cout << "Roll number to delete:\t";
|
||||
cin >> roll;
|
||||
|
||||
// opening files to delete a record
|
||||
ifstream readFile;
|
||||
readFile.open(fileName, ios::in | ios::binary);
|
||||
ofstream writeFile;
|
||||
writeFile.open("~" + fileName, ios::out | ios::binary);
|
||||
writeFile.clear();
|
||||
|
||||
// looking for record
|
||||
while (readFile.read((char*)&s, sizeof(student))) {
|
||||
if (s.rollNo == roll) {
|
||||
status = true;
|
||||
} else {
|
||||
writeFile.write((char*)&s, sizeof(student)) << flush;
|
||||
}
|
||||
}
|
||||
readFile.close();
|
||||
writeFile.close();
|
||||
|
||||
// moving temp file back to original file
|
||||
if (status) {
|
||||
readFile.open("~" + fileName, ios::in | ios::binary);
|
||||
writeFile.open(fileName, ios::out | ios::binary);
|
||||
writeFile.clear();
|
||||
|
||||
writeFile << readFile.rdbuf();
|
||||
readFile.close();
|
||||
writeFile.close();
|
||||
|
||||
// remove("~"+fileName);
|
||||
cout << "Record deleted." << endl;
|
||||
} else {
|
||||
cout << "Record not found." << endl;
|
||||
}
|
||||
}
|
||||
|
||||
void studentDatabase::addStudent() {
|
||||
student s;
|
||||
cout << "Roll number:\t";
|
||||
cin >> s.rollNo;
|
||||
cout << "Name:\t";
|
||||
cin.ignore();
|
||||
cin.getline(s.name, 50);
|
||||
cout << "Division:\t";
|
||||
// cin.ignore();
|
||||
cin >> s.div;
|
||||
cout << "Address:\t";
|
||||
cin.ignore();
|
||||
cin.getline(s.address, 100);
|
||||
// cin.ignore();
|
||||
ofstream file(fileName, ios::out | ios::binary | ios::app);
|
||||
// file.seekp(ios::end);
|
||||
file.write((char*)&s, sizeof(student)) << flush;
|
||||
if (file.fail()) {
|
||||
cout << "Failed to add student record." << endl;
|
||||
} else {
|
||||
cout << "Student added successfully." << endl;
|
||||
}
|
||||
file.close();
|
||||
}
|
||||
|
||||
void studentDatabase::displayAll() {
|
||||
ifstream file;
|
||||
student s;
|
||||
int count = 0;
|
||||
file.open(fileName, ios::in | ios::binary);
|
||||
while (file.read((char*)&s, sizeof(student))) {
|
||||
count++;
|
||||
cout << count << ") ";
|
||||
cout << s.rollNo << "|";
|
||||
cout << s.name << "|";
|
||||
cout << s.div << "|";
|
||||
cout << s.address << endl;
|
||||
}
|
||||
if (count == 0) {
|
||||
cout << "No records found." << endl;
|
||||
}
|
||||
file.close();
|
||||
}
|
||||
int main() {
|
||||
int ch;
|
||||
studentDatabase db;
|
||||
|
||||
// loop
|
||||
do {
|
||||
cout << endl;
|
||||
cout << "--- MAIN MENU ---" << endl;
|
||||
cout << "1 -> Add record" << endl;
|
||||
cout << "2 -> Delete record" << endl;
|
||||
cout << "3 -> Search record" << endl;
|
||||
cout << "4 -> Display all records" << endl;
|
||||
cout << "0 -> Exit" << endl << endl;
|
||||
cout << "Choose an option (0-4):\t";
|
||||
cin >> ch;
|
||||
switch (ch) {
|
||||
case 0:
|
||||
cout << "\n\n// END OF CODE\n\n" << endl;
|
||||
break;
|
||||
case 1:
|
||||
db.addStudent();
|
||||
break;
|
||||
case 2:
|
||||
db.deleteStudent();
|
||||
break;
|
||||
case 3:
|
||||
db.searchStudent();
|
||||
break;
|
||||
case 4:
|
||||
cout << "All records are:\t" << endl;
|
||||
db.displayAll();
|
||||
break;
|
||||
|
||||
default:
|
||||
cout << "Please choose a valid option (0-4):\t" << endl;
|
||||
break;
|
||||
}
|
||||
} while (ch != 0);
|
||||
|
||||
return 0;
|
||||
}
|
||||
// END OF CODE
|
298
Codes/Practical-F24 (Employee information).cpp
Normal file
298
Codes/Practical-F24 (Employee information).cpp
Normal file
@ -0,0 +1,298 @@
|
||||
/*
|
||||
THIS CODE HAS BEEN TESTED AND IS FULLY OPERATIONAL.
|
||||
|
||||
Problem Statement: 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.
|
||||
|
||||
Code from DataStructuresAndAlgorithms (SPPU - Second Year - Computer Engineering - Content) repository on KSKA Git: https://git.kska.io/sppu-se-comp-content/DataStructuresAndAlgorithms/
|
||||
*/
|
||||
|
||||
// BEGINNING OF CODE
|
||||
#include <string.h>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
using namespace std;
|
||||
|
||||
typedef struct employee {
|
||||
int empId;
|
||||
char name[50];
|
||||
char designation[50];
|
||||
int salary;
|
||||
} employee;
|
||||
|
||||
typedef struct index_pair {
|
||||
int key;
|
||||
int position;
|
||||
} index_pair;
|
||||
|
||||
class employeeDatabase {
|
||||
string data_file_name = "ind_employee_data.dat";
|
||||
string index_file_name = "ind_employee_index.dat";
|
||||
public:
|
||||
employeeDatabase();
|
||||
void addEmployee(int eid, char name[50], char dest[50], int sal);
|
||||
void searchEmployee(int);
|
||||
void deleteEmployee(int);
|
||||
bool isPresent(int);
|
||||
void display_all();
|
||||
employee readEmp(int pos);
|
||||
};
|
||||
|
||||
employee employeeDatabase::readEmp(int pos) {
|
||||
fstream data_file(data_file_name, ios::binary | ios::in | ios::ate);
|
||||
employee emp;
|
||||
if (pos >= data_file.tellg() || pos == -1) {
|
||||
emp.empId = -1;
|
||||
return emp;
|
||||
}
|
||||
data_file.seekg(pos, ios::beg);
|
||||
data_file.read((char *)&emp, sizeof(emp));
|
||||
data_file.close();
|
||||
return emp;
|
||||
}
|
||||
|
||||
employeeDatabase::employeeDatabase() {
|
||||
fstream data_file(data_file_name);
|
||||
fstream index_file(index_file_name);
|
||||
if (data_file.fail() | index_file.fail()) {
|
||||
cout << "Created a new file." << endl;
|
||||
data_file.open(data_file_name, ios::binary | ios::out | ios::app);
|
||||
index_file.open(index_file_name, ios::binary | ios::out | ios::app);
|
||||
} else {
|
||||
cout << "File already exists." << endl;
|
||||
}
|
||||
data_file.close();
|
||||
index_file.close();
|
||||
}
|
||||
|
||||
void employeeDatabase::addEmployee(int eid, char name[50], char dest[50], int sal) {
|
||||
fstream data_file(data_file_name, ios::binary | ios::out | ios::app);
|
||||
fstream index_file(index_file_name, ios::binary | ios::in);
|
||||
index_pair current, temp;
|
||||
char *all_data;
|
||||
employee emp;
|
||||
int pos, ipos;
|
||||
bool update = false;
|
||||
|
||||
while (index_file.read((char *)¤t, sizeof(index_pair))) {
|
||||
|
||||
if (current.key == eid) {
|
||||
if (current.position == -1) {
|
||||
ipos = (int)index_file.tellg() - sizeof(current);
|
||||
update = true;
|
||||
break;
|
||||
} else {
|
||||
cout << "Cannot add employee, already exists."
|
||||
<< endl;
|
||||
goto exit_addEmployee;
|
||||
}
|
||||
}
|
||||
}
|
||||
index_file.close();
|
||||
|
||||
emp.empId = eid;
|
||||
strcpy(emp.name, name);
|
||||
strcpy(emp.designation, dest);
|
||||
emp.salary = sal;
|
||||
|
||||
data_file.seekp(0, ios::end);
|
||||
pos = data_file.tellp();
|
||||
data_file.write((char *)&emp, sizeof(emp));
|
||||
current.key = eid;
|
||||
current.position = pos;
|
||||
// cout << pos << endl;
|
||||
if (update) {
|
||||
index_file.open(index_file_name, ios::binary | ios::out);
|
||||
index_file.seekp(ipos, ios::beg);
|
||||
index_file.write((char *)¤t, sizeof(current));
|
||||
} else {
|
||||
bool written = false;
|
||||
// inserting record in sorted order
|
||||
vector<index_pair> index_pairs;
|
||||
index_file.open(index_file_name, ios::binary | ios::in);
|
||||
while (index_file.read((char *)&temp, sizeof(index_pair))) {
|
||||
if (!written and temp.key > eid) {
|
||||
written = true;
|
||||
index_pairs.push_back(current);
|
||||
}
|
||||
index_pairs.push_back(temp);
|
||||
}
|
||||
if (!written) {
|
||||
index_pairs.push_back(current);
|
||||
}
|
||||
|
||||
index_file.clear();
|
||||
index_file.close();
|
||||
|
||||
// write records
|
||||
index_file.open(index_file_name, ios::binary | ios::out);
|
||||
|
||||
for (int i = 0; i < index_pairs.size(); i++) {
|
||||
current = index_pairs[i];
|
||||
if (current.position != -1) {
|
||||
index_file.write((char *)¤t, sizeof(index_pair));
|
||||
}
|
||||
}
|
||||
}
|
||||
cout << "Employee added successfully." << endl;
|
||||
// close and exit
|
||||
exit_addEmployee:
|
||||
data_file.close();
|
||||
index_file.close();
|
||||
}
|
||||
|
||||
void display_emp(employee emp) {
|
||||
cout << "ID:\t" << emp.empId << endl;
|
||||
cout << "Name:\t" << emp.name << endl;
|
||||
cout << "Designation:\t" << emp.designation << endl;
|
||||
cout << "Salary:\tRs. " << emp.salary << endl;
|
||||
}
|
||||
|
||||
void employeeDatabase::searchEmployee(int eid) {
|
||||
fstream index_file(index_file_name, ios::binary | ios::in);
|
||||
index_pair current;
|
||||
int pos = -1;
|
||||
|
||||
while (index_file.read((char *)¤t, sizeof(index_pair))) {
|
||||
if (current.key == eid) {
|
||||
pos = current.position;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
employee emp = readEmp(pos);
|
||||
if (emp.empId == -1) {
|
||||
cout << "Employee does not exist." << endl;
|
||||
} else {
|
||||
cout << "--- EMPLOYEE FOUND ---" << endl;
|
||||
display_emp(emp);
|
||||
cout << "--- END OF RECORD ---" << endl;
|
||||
}
|
||||
|
||||
index_file.close();
|
||||
}
|
||||
|
||||
bool employeeDatabase::isPresent(int eid) {
|
||||
fstream index_file(index_file_name, ios::binary | ios::in);
|
||||
index_pair current;
|
||||
|
||||
while (index_file.read((char *)¤t, sizeof(index_pair))) {
|
||||
if (current.key == eid) {
|
||||
if (current.position == -1) {
|
||||
index_file.close();
|
||||
return false;
|
||||
} else {
|
||||
index_file.close();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
index_file.close();
|
||||
return false;
|
||||
}
|
||||
|
||||
void employeeDatabase::deleteEmployee(int eid) {
|
||||
fstream index_file(index_file_name, ios::binary | ios::in);
|
||||
index_pair current;
|
||||
bool deleted = false;
|
||||
vector<index_pair> pairs;
|
||||
|
||||
while (index_file.read((char *)¤t, sizeof(index_pair))) {
|
||||
if (current.key == eid) {
|
||||
deleted = true;
|
||||
} else {
|
||||
pairs.push_back(current);
|
||||
}
|
||||
}
|
||||
index_file.close();
|
||||
if (deleted) {
|
||||
index_file.open(index_file_name, ios::binary | ios::out);
|
||||
index_file.clear();
|
||||
index_file.seekp(0, ios::beg);
|
||||
|
||||
for (int i = 0; i < pairs.size(); i++) {
|
||||
current = pairs[i];
|
||||
index_file.write((char *)¤t, sizeof(index_pair));
|
||||
}
|
||||
index_file.close();
|
||||
cout << "Employee removed from record." << endl;
|
||||
} else {
|
||||
cout << "Employee does not exist in the record." << endl;
|
||||
}
|
||||
}
|
||||
|
||||
void employeeDatabase::display_all() {
|
||||
fstream index_file(index_file_name, ios::binary | ios::in);
|
||||
fstream data_file(data_file_name, ios::binary | ios::in);
|
||||
index_pair current;
|
||||
employee emp;
|
||||
while (index_file.read((char *)¤t, sizeof(index_pair))) {
|
||||
if (current.position != -1) {
|
||||
data_file.seekg(current.position, ios::beg);
|
||||
data_file.read((char *)&emp, sizeof(emp));
|
||||
cout << emp.empId << " | " << emp.name << " | " << emp.designation
|
||||
<< " | " << emp.salary << endl;
|
||||
}
|
||||
}
|
||||
index_file.close();
|
||||
data_file.close();
|
||||
}
|
||||
|
||||
int main() {
|
||||
employeeDatabase db;
|
||||
int eid, sal;
|
||||
char name[50], dest[50];
|
||||
int ch;
|
||||
do {
|
||||
cout << endl << "--- MAIN MENU ---" << endl;
|
||||
cout << "1 -> Add employee" << endl;
|
||||
cout << "2 -> Search employee" << endl;
|
||||
cout << "3 -> Delete employee" << endl;
|
||||
cout << "4 -> Display all" << endl;
|
||||
cout << "5 -> Exit" << endl;
|
||||
cout << "Choose an option (1-5):\t";
|
||||
cin >> ch;
|
||||
switch (ch) {
|
||||
case 1:
|
||||
reenter_eid:
|
||||
cout << "Employee ID:\t";
|
||||
cin >> eid;
|
||||
if (db.isPresent(eid)) {
|
||||
cout << "Employee already exists in record. Please try again."
|
||||
<< endl;
|
||||
goto reenter_eid;
|
||||
}
|
||||
cout << "Name:\t";
|
||||
cin >> name;
|
||||
cout << "Designation:\t";
|
||||
cin >> dest;
|
||||
cout << "Salary:\tRs. ";
|
||||
cin >> sal;
|
||||
|
||||
db.addEmployee(eid, name, dest, sal);
|
||||
break;
|
||||
case 2:
|
||||
cout << "Employee ID:\t";
|
||||
cin >> eid;
|
||||
db.searchEmployee(eid);
|
||||
break;
|
||||
case 3:
|
||||
cout << "Employee ID:\t";
|
||||
cin >> eid;
|
||||
db.deleteEmployee(eid);
|
||||
break;
|
||||
case 4:
|
||||
db.display_all();
|
||||
break;
|
||||
case 5:
|
||||
cout << "\n\n// END OF CODE\n\n" << endl;
|
||||
break;
|
||||
default:
|
||||
cout << "Please choose a valid option (1-5)." << endl;
|
||||
break;
|
||||
}
|
||||
} while (ch != 5);
|
||||
|
||||
return 0;
|
||||
}
|
||||
// END OF CODE
|
7
Codes/README.md
Normal file
7
Codes/README.md
Normal file
@ -0,0 +1,7 @@
|
||||
## Choose your poison:
|
||||
|
||||
- [main branch (all the codes are tested and relatively small in size)](https://git.kska.io/sppu-se-comp-content/DataStructuresAndAlgorithms/src/branch/main/Codes) **CURRENT BRANCH**
|
||||
- [longCodes (long codes with minimal description)](https://git.kska.io/sppu-se-comp-content/DataStructuresAndAlgorithms/src/branch/longCodes)
|
||||
- [testing (untested codes)](https://git.kska.io/sppu-se-comp-content/DataStructuresAndAlgorithms/src/branch/testing/)
|
||||
|
||||
---
|
17
README.md
17
README.md
@ -16,6 +16,23 @@ Delve into the realm of Data Structures and Algorithms (DSA) with our Git reposi
|
||||
5. [Unit 5 - Indexing and Multiway Trees](https://git.kska.io/sppu-se-comp-content/DataStructuresAndAlgorithms/src/branch/main/Notes/Unit%205%20-%20Indexing%20and%20Multiway%20Trees)
|
||||
6. Unit 6 - File Organization - NEVER RECEIVED THEM FROM MA'AM.
|
||||
|
||||
### Codes
|
||||
|
||||
1. [Practical A1 - Hashing](https://git.kska.io/sppu-se-comp-content/DataStructuresAndAlgorithms/src/branch/main/Codes/Practical-A1%20%28Hashing%29.py)
|
||||
2. [Practical A4 - Set Operations](https://git.kska.io/sppu-se-comp-content/DataStructuresAndAlgorithms/src/branch/main/Codes/Practical-A4%20%28Set%20Operations%29.py)
|
||||
3. [Practical B5 - Tree](https://git.kska.io/sppu-se-comp-content/DataStructuresAndAlgorithms/src/branch/main/Codes/Practical-B5%20%28Tree%29.cpp)
|
||||
4. [Practical B7 - Binary tree functions](https://git.kska.io/sppu-se-comp-content/DataStructuresAndAlgorithms/src/branch/main/Codes/Practical-B7%20%28Expression%20Tree%29.cpp)
|
||||
5. [Practical B11 - Dictionary using BST](https://git.kska.io/sppu-se-comp-content/DataStructuresAndAlgorithms/src/branch/main/Codes/Practical-B11%20%28Binary%20Search%20Tree%29.cpp)
|
||||
6. [Practical C13 - Adjacent List and Matrix of Graph](https://git.kska.io/sppu-se-comp-content/DataStructuresAndAlgorithms/src/branch/main/Codes/Practical-C13%20%28Adjacent%20List%20and%20Matrix%20of%20Graph%29.cpp)
|
||||
7. [Practical C15 - Prim's Algorithm](https://git.kska.io/sppu-se-comp-content/DataStructuresAndAlgorithms/src/branch/main/Codes/Practical-C15%20%28Prims%29.cpp)
|
||||
8. [Practical D18 - Optimal Binary Search Tree](https://git.kska.io/sppu-se-comp-content/DataStructuresAndAlgorithms/src/branch/main/Codes/Practical-D18%20%28OBST%29.cpp)
|
||||
9. [Practical D19 - Adelson, Velskii, and Landi (AVL) tree](https://git.kska.io/sppu-se-comp-content/DataStructuresAndAlgorithms/src/branch/main/Codes/Practical-D19%20%28AVL%20Tree%29.cpp)
|
||||
10. [Practical E20 - Priority Queue](https://git.kska.io/sppu-se-comp-content/DataStructuresAndAlgorithms/src/branch/main/Codes/Practical-E20%20%28Priority%20Queue%29.cpp)
|
||||
11. [Practical F23 - Student information](https://git.kska.io/sppu-se-comp-content/DataStructuresAndAlgorithms/src/branch/main/Codes/Practical-F23%20%28Student%20information%29.cpp)
|
||||
12. [Practical F24 - Employee information](https://git.kska.io/sppu-se-comp-content/DataStructuresAndAlgorithms/src/branch/main/Codes/Practical-F24%20%28Employee%20information%29.cpp)
|
||||
|
||||
> Alternate versions of these codes are available in the [longCodes](https://git.kska.io/sppu-se-comp-content/DataStructuresAndAlgorithms/src/branch/longCodes) and [testing](https://git.kska.io/sppu-se-comp-content/DataStructuresAndAlgorithms/src/branch/testing) branch.
|
||||
|
||||
### ERP Assignments
|
||||
|
||||
> **THESE ASSIGNMENTS ARE TO BE UPLOADED TO ERP. DO NOT DIRECTLY DOWNLOAD THESE, CHANGE YOUR NAME AND UPLOAD THEM, ONLY USE THEM FOR REFERENCE.**
|
||||
|
Loading…
Reference in New Issue
Block a user