0% found this document useful (0 votes)
10 views60 pages

Soham Ghodke DSAL

The document contains multiple implementations of data structures and algorithms in C++, including hash tables with linear probing and chaining, a generic tree, a binary search tree (BST), and a threaded binary tree. It also features a graph representation with functionalities for adding edges and checking connectivity. The main functions demonstrate the usage of these data structures through user input and various operations.

Uploaded by

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

Soham Ghodke DSAL

The document contains multiple implementations of data structures and algorithms in C++, including hash tables with linear probing and chaining, a generic tree, a binary search tree (BST), and a threaded binary tree. It also features a graph representation with functionalities for adding edges and checking connectivity. The main functions demonstrate the usage of these data structures through user input and various operations.

Uploaded by

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

#include <iostream>

#include <list>
#include <vector>
using namespace std;

const int TABLE_SIZE = 10;

int hashFunc on(const string &key) {

int hash = 0; for (char


ch : key) hash += ch;
return hash %
TABLE_SIZE;
}

// ----------- LINEAR PROBING IMPLEMENTATION


----------- class LinearProbingHashTable { pair<string,
string> table[TABLE_SIZE]; // {name, phone} bool
occupied[TABLE_SIZE] = {false};

public:

void insert(const string &name, const string &phone) {


int index = hashFunc on(name);
int originalIndex = index; while
(occupied[index] && table[index].first != name)
{ index = (index + 1) % TABLE_SIZE; if
(index == originalIndex) { cout << "Hash table
is full!\n"; return;
}

table[index] = {name, phone};


occupied[index] = true;

int search(const string &name) {


int index = hashFunc on(name);
int comparisons = 1; int
originalIndex = index; while
(occupied[index]) { if
(table[index].first == name)
return comparisons; index =
(index + 1) % TABLE_SIZE;
comparisons++; if (index ==
originalIndex) break;
}

return comparisons;

};

// ----------- CHAINING IMPLEMENTATION


----------- class ChainingHashTable
{ list<pair<string, string>>
table[TABLE_SIZE];

public:

void insert(const string &name, const string &phone) {


int index = hashFunc on(name);
for (auto &entry : table[index])
{ if (entry.first == name) {
entry.second = phone;
return;

}
}

table[index].emplace_back(name, phone);

int search(const string &name) {


int index = hashFunc on(name);
int comparisons = 0; for (auto
&entry : table[index])
{ comparisons++; if
(entry.first == name)
return comparisons;
}

return comparisons;

};

// ----------- MAIN FUNCTION


----------- int main() {
LinearProbingHashTable linearTable;

ChainingHashTable chainingTable;

int n;

cout << "Enter number of clients: ";


cin >> n;

vector<pair<string, string>> clients(n); cout << "Enter


name and phone number of each client:\n";
for (int i = 0; i < n; ++i) { cout << "Client " <<
i + 1 << ": "; cin >> clients[i].first >>
clients[i].second;
linearTable.insert(clients[i].first, clients[i].second);

chainingTable.insert(clients[i].first, clients[i].second);

int m; cout << "\nEnter number of names to


search: ";
cin >> m;

cout << "Enter names to search:\n";

for (int i = 0; i < m; ++i) { string name; cout


<< "Search " << i + 1 << ": "; cin >> name; int
linComp = linearTable.search(name); int chainComp
= chainingTable.search(name); cout << "Comparisons
for \"" << name << "\": Linear = "
<< linComp << ", Chaining = " << chainComp << endl;

return 0;

}
#include <iostream>

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

const int TABLE_SIZE = 10;

int hashFunc on(const string& key) {

int hash = 0; for (char ch :


key) hash += ch; return hash
% TABLE_SIZE;
}

// Dic onary ADT using Hashing with


Chaining class HashTable
{ list<pair<string, string>>
table[TABLE_SIZE]; bool
withReplacement;

public:

HashTable(bool useReplacement = false)


{ withReplacement = useReplacement;
}
void insert(string key, string value) {
int index = hashFunc on(key);

// Check for duplicate key for (auto& pair :


table[index]) { if (pair.first == key)
{ cout << "Key already exists. Upda ng
value.\n"; pair.second = value;

return;

// Insert normally (without replacement)


if (!withReplacement)
{ table[index].emplace_back(key,
value);
}

// With replacement logic

else {

if (!table[index].empty()) { auto&
firstPair = table[index].front(); int exis
ngIndex = hashFunc on(firstPair.first); if
(exis ngIndex != index) {
// Displace the current one and rehash it
pair<string, string> displaced = firstPair;
table[index].pop_front(); table[index].emplace_front(key,
value); insert(displaced.first, displaced.second); // reinsert
displaced
} else {

table[index].emplace_back(key, value);
}
} else {
table[index].emplace_back(key, value);

void find(string key) { int


index = hashFunc on(key);
for (auto& pair : table[index]) {
if (pair.first == key)
{ cout << "Found: " <<
key << " -> " << pair.second <<
endl;
return;

cout << "Key '" << key << "' not found.\n";

void remove(string key) { int index = hashFunc on(key);


for (auto it = table[index].begin(); it != table[index].end(); ++it) {
if (it->first == key) { table[index].erase(it);
cout << "Key '" << key << "' deleted.\n";
return;

cout << "Key '" << key << "' not found for dele on.\n";

}
void display() { cout << "\n--- Hash Table ---\n";
for (int i = 0; i < TABLE_SIZE; ++i) { cout << i << " -
> "; for (auto& pair : table[i]) { cout << "["
<< pair.first << ": " << pair.second << "] -> ";
}

cout << "NULL\n";

};

// ---------- Driver Code ---------- int main() { bool


useReplacement; cout << "Use chaining with replacement?
(1 = Yes, 0 = No): "; cin >> useReplacement;

HashTable dict(useReplacement);

int choice;
string key, value;

do { cout << "\n1. Insert\n2. Find\n3. Delete\n4. Display\n5.


Exit\n"; cout << "Enter choice: "; cin >> choice;

switch (choice) {
case 1:
cout << "Enter key: ";
cin >> key; cout <<
"Enter value: "; cin
>> value;
dict.insert(key, value);
break; case 2:
cout << "Enter key to find:
"; cin >> key;
dict.find(key); break;
case 3:

cout << "Enter key to delete: ";

cin >> key;


dict.remove(key);
break; case 4:
dict.display();
break; case 5:
cout << "Exi ng...\
n"; break;
default:
cout << "Invalid op on!\n";

} while (choice != 5);

return 0;

}
#include <iostream>

#include <vector>

#include <string>

using namespace std;

// Generic Tree Node class


TreeNode { public: string
name; vector<TreeNode*>
children;

TreeNode(string n) : name(n) {}

void addChild(TreeNode* child)


{ children.push_back(child);
}

};

// Recursive func on to print the tree void


printTree(TreeNode* node, int depth = 0)
{ if (!node) return;

for (int i = 0; i < depth; ++i) cout << " ";


cout << "- " << node->name << endl;

for (auto child : node->children)


{ printTree(child, depth + 1);
}

}
// Func on to free memory (avoids memory leaks)
void deleteTree(TreeNode* node) {
if (!node) return; for (auto
child : node->children)
deleteTree(child); delete node;
}

int main() {

// Construct the tree manually

TreeNode* book = new TreeNode("Book");

TreeNode* chapter1 = new TreeNode("Chapter


1"); TreeNode* chapter2 = new
TreeNode("Chapter 2");

TreeNode* sec on1 = new TreeNode("Sec on 1.1");


TreeNode* sec on2 = new TreeNode("Sec on 1.2");

TreeNode* subsec on1 = new TreeNode("Subsec on 1.1.1");


TreeNode* subsec on2 = new TreeNode("Subsec on 1.2.1");

// Build the hierarchy

sec on1->addChild(subsec on1);


sec on2->addChild(subsec on2);

chapter1->addChild(sec on1); chapter1-


>addChild(sec on2);
book->addChild(chapter1); book-
>addChild(chapter2);

// Print the tree


printTree(book);

// Clean up memory
deleteTree(book);

return 0;

#include <iostream>

#include <algorithm>
using namespace std;

// Define the Node structure


class Node { public: int
data;
Node* le ;

Node* right;

Node(int value) {
data = value; le =
right = nullptr;
}

};

// Insert a node into BST Node*


insert(Node* root, int value) { if
(root == nullptr) return new
Node(value); if (value < root->data)
root->le = insert(root->le , value);
else

root->right = insert(root->right, value);


return root;
}

// Inorder Traversal

void inorder(Node* root) {


if (root == nullptr) return;
inorder(root->le ); cout
<< root->data << " ";
inorder(root->right);
}

// Find the height of the longest path (recursive depth)


int longestPath(Node* root) { if (root == nullptr)
return 0;
return 1 + max(longestPath(root->le ), longestPath(root->right));

// Find the minimum value in BST (le most node)


int findMin(Node* root) {
if (root == nullptr) { cout <<
"Tree is empty!" << endl;
return -1;
}

Node* current = root;


while (current->le != nullptr)
current = current->le ; return
current->data;
}

// Mirror the tree (swap le and right)


void mirrorTree(Node* root) { if
(root == nullptr) return; swap(root-
>le , root->right); mirrorTree(root-
>le ); mirrorTree(root->right);

// Search for a value bool


search(Node* root, int key) { if
(root == nullptr) return
false; if (key == root->data)
return true; else if (key < root-
>data) return search(root->le
, key);
else return search(root-
>right, key);
}

// Free memory void


deleteTree(Node* root) {
if (!root) return;
deleteTree(root->le );
deleteTree(root->right);
delete root;
}

int main() { Node* root = nullptr; int ini


alValues[] = {50, 30, 70, 20, 40, 60, 80}; int n =
sizeof(ini alValues) / sizeof(ini alValues[0]);

// Build the tree for (int i = 0; i <


n; ++i) { root = insert(root, ini
alValues[i]); }

cout << "Inorder traversal of BST:


"; inorder(root); cout << endl;

// i. Insert new node int newVal = 25; cout


<< "Inser ng new node: " << newVal << endl;
insert(root, newVal); cout << "Inorder a er inser
on: "; inorder(root); cout << endl;
// ii. Find number of nodes in longest path cout <<
"Longest path (height): " << longestPath(root) << endl;

// iii. Minimum data value in tree cout << "Minimum


value in BST: " << findMin(root) << endl;

// iv. Mirror the tree


mirrorTree(root); cout <<
"Inorder a er mirroring: ";
inorder(root); cout << endl;

// v. Search a value int searchVal = 60;


cout << "Searching for " << searchVal << ":
"; if (search(root, searchVal)) cout <<
"Found" << endl;

else

cout << "Not Found" << endl;

// Clean up memory
deleteTree(root); return
0;
}
#include <iostream>
using namespace std;

class Node
{ public:
int data;
Node* le ;
Node* right;
bool isThreaded;

Node(int val)
{ data = val;
le = right = nullptr;
isThreaded = false;
}

};

// Normal BST insert

Node* insert(Node* root, int val) {

if (!root) return new


Node(val); if (val < root->data)
root->le = insert(root->le , val);
else root->right = insert(root-
>right, val); return root;
}

// Converts binary tree to threaded binary tree using reverse inorder traversal

Node* createThreaded(Node* root, Node*& prev) {


if (!root)
return nullptr;

// Right subtree createThreaded(root-


>right, prev);

// Thread this node if right is


NULL if (!root->right)
{ root->right = prev; root-
>isThreaded = true;
}

// Update previous node


prev = root;

// Le subtree createThreaded(root-
>le , prev);

return root;

// Le most node in a tree


Node* le most(Node* node) {
while (node && node->le )
node = node->le ; return
node;
}

// Inorder traversal using threads (no recursion or stack)


void inorderThreaded(Node* root) { Node* curr = le
most(root);
while (curr) {
cout << curr->data << " ";

// If node is threaded, follow the thread


if (curr->isThreaded) curr = curr-
>right;
else curr = le
most(curr->right);
}

int main() {

Node* root = nullptr;

int values[] = {50, 30, 70, 20, 40, 60,


80}; for (int val : values) root =
insert(root, val); Node* prev = nullptr;
createThreaded(root, prev);

cout << "Inorder traversal using threaded tree:


"; inorderThreaded(root); cout << endl;

return 0;}
#include <iostream>

#include <unordered_map>

#include <vector>
#include <queue>
#include <set> using
namespace std;

// Each edge: des na on city and weight ( me or fuel)


struct Edge { string dest; int cost;
};

class Graph { unordered_map<string,


vector<Edge>> adjList;

public:

// Add a directed edge (for undirected: add both ways)


void addFlight(string from, string to, int cost)
{ adjList[from].push_back({to, cost});
adjList[to].push_back({from, cost}); // assuming undirected
}

// Print the graph void printGraph() { for (auto& pair :


adjList) { cout << pair.first << " -> "; for (auto&
edge : pair.second) { cout << "(" << edge.dest << ",
cost: " << edge.cost << ") ";
}

cout << endl;


}

// Check if graph is connected using


BFS bool isConnected() { if
(adjList.empty()) return true;

set<string> visited;
queue<string> q;

// Start from any node auto


start = adjList.begin()->first;
q.push(start);
visited.insert(start);

while (!q.empty()) { string current =


q.front(); q.pop(); for (auto& neighbor :
adjList[current]) { if
(visited.find(neighbor.dest) == visited.end()) {
visited.insert(neighbor.dest);
q.push(neighbor.dest);

// If all ci es were visited, the graph is connected


return visited.size() == adjList.size();
}

};
int main() {

Graph flightMap;

flightMap.addFlight("New York", "London", 7);


flightMap.addFlight("London", "Paris", 1);
flightMap.addFlight("Paris", "Berlin", 2);
flightMap.addFlight("Berlin", "Rome", 2);
flightMap.addFlight("Rome", "New York", 9);

flightMap.printGraph();

if (flightMap.isConnected()) cout << "The


flight graph is connected." << endl;
else cout << "The flight graph is NOT
connected." << endl;

return 0;

}
#include <iostream>

#include <vector>
#include <algorithm>
using namespace std;

// Edge representa on struct


Edge {
int u, v, cost;

};

// Sort edges by increasing cost bool


compareEdge(const Edge &a, const Edge &b) {
return a.cost < b.cost;
}

// Disjoint Set Union (Union-Find) for cycle detec


on class DSU { vector<int> parent, rank; public:
DSU(int n) { parent.resize(n);
rank.resize(n, 0); for (int i = 0; i < n; ++i)
parent[i] = i;
}
int find(int x) { if (parent[x] != x)
parent[x] = find(parent[x]); // path compression
return parent[x];
}

bool unite(int x, int y) { int


rootX = find(x), rootY = find(y);
if (rootX == rootY) return false;
if (rank[rootX] < rank[rootY])
parent[rootX] = rootY; else if
(rank[rootX] > rank[rootY])
parent[rootY] = rootX;
else
{ parent[rootY] =
rootX; rank[rootX]+
+;
}

return true;

};

// Kruskal's MST int kruskalMST(int V, vector<Edge>& edges,


vector<Edge>& mst) { sort(edges.begin(), edges.end(),
compareEdge); DSU dsu(V); int totalCost = 0;

for (auto& edge : edges)


{ if (dsu.unite(edge.u,
edge.v))
{ mst.push_back(edge);
totalCost += edge.cost;
}

}
return totalCost;

int main() { int V = 5; // Number of


offices (nodes) vector<Edge> edges
={
{0, 1, 10},

{0, 2, 6},

{0, 3, 5},

{1, 3, 15},

{2, 3, 4}

};

vector<Edge> mst; int totalCost =


kruskalMST(V, edges, mst);

cout << "Minimum cost to connect all offices: " << totalCost << endl; cout <<
"Connec ons used:\n"; for (auto& edge : mst) cout << "Office " << edge.u << " -
Office " << edge.v << " : Cost = " << edge.cost << endl;

return 0;

}
#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

// AVL Tree Node


struct Node {
string key; // Keyword (e.g., dictionary word)
string value; // Meaning of the keyword
int height; // Height of the node
Node* left; // Left child
Node* right; // Right child

Node(string k, string v) : key(k), value(v), height(1),


left(nullptr), right(nullptr) {}
};

// AVL Tree Class


class AVLTree {
private:
Node* root;

// Helper function to get the height of a node


int height(Node* node) {
return node ? node->height : 0;
}

// Helper function to get the balance factor of a node


int balanceFactor(Node* node) {
return node ? height(node->left) - height(node-
>right) : 0;
}

// Right rotation
Node* rightRotate(Node* y) {
Node* x = y->left;
Node* T2 = x->right;

x->right = y;
y->left = T2;

y->height = max(height(y->left), height(y->right)) +


1;
x->height = max(height(x->left), height(x->right)) +
1;

return x;
}

// Left rotation
Node* leftRotate(Node* x) {
Node* y = x->right;
Node* T2 = y->left;
y->left = x;
x->right = T2;

x->height = max(height(x->left), height(x->right)) +


1;
y->height = max(height(y->left), height(y->right)) +
1;

return y;
}

// Insert a node into the AVL tree


Node* insert(Node* node, const string& key, const
string& value) {
if (!node) return new Node(key, value);

if (key < node->key) {


node->left = insert(node->left, key, value);
} else if (key > node->key) {
node->right = insert(node->right, key, value);
} else { // Duplicate keys are not allowed, so
update the value
node->value = value;
return node;
}

// Update height of this ancestor node


node->height = 1 + max(height(node->left),
height(node->right));

// Balance the node


int balance = balanceFactor(node);

// Left heavy case


if (balance > 1 && key < node->left->key)
return rightRotate(node);

// Right heavy case


if (balance < -1 && key > node->right->key)
return leftRotate(node);

// Left-right case
if (balance > 1 && key > node->left->key) {
node->left = leftRotate(node->left);
return rightRotate(node);
}

// Right-left case
if (balance < -1 && key < node->right->key) {
node->right = rightRotate(node->right);
return leftRotate(node);
}

return node;
}

// Delete a node from the AVL tree


Node* deleteNode(Node* root, const string& key) {
if (!root) return root;

if (key < root->key) {


root->left = deleteNode(root->left, key);
} else if (key > root->key) {
root->right = deleteNode(root->right, key);
} else {
if (!root->left || !root->right) {
Node* temp = root->left ? root->left : root-
>right;
if (!temp) {
temp = root;
root = nullptr;
} else {
*root = *temp;
}
delete temp;
} else {
Node* temp = minValueNode(root->right);
root->key = temp->key;
root->value = temp->value;
root->right = deleteNode(root->right, temp-
>key);
}
}

if (!root) return root;

// Update height of the current node


root->height = max(height(root->left), height(root-
>right)) + 1;

// Balance the node


int balance = balanceFactor(root);

if (balance > 1 && balanceFactor(root->left) >= 0)


return rightRotate(root);

if (balance < -1 && balanceFactor(root->right) <= 0)


return leftRotate(root);

if (balance > 1 && balanceFactor(root->left) < 0) {


root->left = leftRotate(root->left);
return rightRotate(root);
}
if (balance < -1 && balanceFactor(root->right) > 0)
{
root->right = rightRotate(root->right);
return leftRotate(root);
}

return root;
}

// Find the node with minimum value


Node* minValueNode(Node* node) {
Node* current = node;
while (current->left) current = current->left;
return current;
}

// In-order traversal to display the dictionary in


ascending order
void inorder(Node* root) {
if (root) {
inorder(root->left);
cout << root->key << " -> " << root->value <<
endl;
inorder(root->right);
}
}

// Reverse in-order traversal to display the dictionary


in descending order
void reverseInorder(Node* root) {
if (root) {
reverseInorder(root->right);
cout << root->key << " -> " << root->value <<
endl;
reverseInorder(root->left);
}
}

public:
AVLTree() : root(nullptr) {}

// Insert a keyword and its meaning


void insert(const string& key, const string& value) {
root = insert(root, key, value);
}

// Delete a keyword
void deleteKeyword(const string& key) {
root = deleteNode(root, key);
}

// Update the meaning of a keyword


void updateValue(const string& key, const string&
newValue) {
Node* node = search(root, key);
if (node) {
node->value = newValue;
} else {
cout << "Keyword not found!" << endl;
}
}

// Search for a keyword


Node* search(Node* root, const string& key) {
if (!root || root->key == key) return root;
if (key < root->key) return search(root->left, key);
return search(root->right, key);
}

// Display dictionary sorted in ascending order


void displayAscending() {
inorder(root);
}

// Display dictionary sorted in descending order


void displayDescending() {
reverseInorder(root);
}

// Find maximum comparisons for finding any keyword


int maxComparisons() {
return height(root); // Maximum comparisons equals
the height of the tree
}
};

int main() {
AVLTree dictionary;

// Adding some entries to the dictionary


dictionary.insert("apple", "A fruit");
dictionary.insert("banana", "Another fruit");
dictionary.insert("cherry", "A red fruit");

cout << "Dictionary (ascending order):" << endl;


dictionary.displayAscending();

cout << "\nDictionary (descending order):" << endl;


dictionary.displayDescending();

cout << "\nUpdating 'banana' meaning..." << endl;


dictionary.updateValue("banana", "A yellow fruit");
dictionary.displayAscending();

cout << "\nDeleting 'cherry'..." << endl;


dictionary.deleteKeyword("cherry");
dictionary.displayAscending();

cout << "\nMaximum comparisons required: " <<


dictionary.maxComparisons() << endl;

return 0;
}
#include <iostream>
#include <vector>
using namespace std;

class HeapSort
{ public:
void sort(vector<int>& arr) {

int n = arr.size();

// Build max heap

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


heapify(arr, n, i);

// Extract elements from heap one by one

for (int i = n - 1; i > 0; i--) { swap(arr[0],


arr[i]); // Move current root to end heapify(arr,
i, 0); // Heapify the reduced heap
}

}
void display(const vector<int>& arr) {

for (int val : arr)


cout << val << " ";
cout << endl;
}

private:

void heapify(vector<int>& arr, int n, int


i) { int largest = i; int le = 2 * i +
1; int right = 2 * i + 2;

// Check if le child is larger if


(le < n && arr[le ] > arr[largest])
largest = le ;

// Check if right child is larger if


(right < n && arr[right] > arr[largest])
largest = right;

if (largest != i)
{ swap(arr[i],
arr[largest]);
heapify(arr, n, largest);
}

};

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

class ShellSort
{ public:
void sort(vector<int>& arr) {

int n = arr.size();

// Start with a big gap, reduce the gap


for (int gap = n / 2; gap > 0; gap /= 2) {
for (int i = gap; i < n; i++) {
int temp = arr[i];
int j;

// Shi earlier gap-sorted elements up


for (j = i; j >= gap && arr[j - gap] > temp; j -=
gap) arr[j] = arr[j - gap];

arr[j] = temp;

void display(const vector<int>& arr) {

for (int val : arr)


cout << val << " ";
cout << endl;
}

};

int main() { vector<int> heapArr = {12, 11,


13, 5, 6, 7}; vector<int> shellArr = {23, 12, 1,
8, 34, 54, 2, 3};
cout << "Original Array for Heap Sort:\
n"; HeapSort hs; hs.display(heapArr);
hs.sort(heapArr); cout << "Sorted using
Heap Sort:\n"; hs.display(heapArr);

cout << "\nOriginal Array for Shell Sort:\


n"; ShellSort ss; ss.display(shellArr);
ss.sort(shellArr); cout << "Sorted using
Shell Sort:\n"; ss.display(shellArr);

return 0;

}
#include <iostream>

#include <vector>
#include <queue>
using namespace std;

class MarksAnalyzer
{ private:
priority_queue<int> maxHeap; // For maximum marks priority_queue<int,
vector<int>, greater<int>> minHeap; // For minimum marks

public:

void readMarks(const vector<int>& marks) {


for (int mark : marks)
{ maxHeap.push(mark);
minHeap.push(mark);
}
}

int getMaxMarks()
{ if (!
maxHeap.empty())
return maxHeap.top();
return -1;

int getMinMarks()
{ if (!
minHeap.empty())
return minHeap.top();
return -1;
}

void displayMarks(const vector<int>& marks)


{ cout << "Marks entered: "; for (int
mark : marks) cout << mark << " ";
cout << endl;
}

};

int main() { MarksAnalyzer analyzer; vector<int> marks =


{88, 67, 95, 74, 55, 91, 60}; analyzer.displayMarks(marks);
analyzer.readMarks(marks); cout << "Maximum Marks: " <<
analyzer.getMaxMarks() << endl; cout << "Minimum Marks: "
<< analyzer.getMinMarks() << endl;

return 0;

}
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>

using namespace std;

// Define the structure for a student


struct Student {
int roll_no;
string name;
string division;
string address;
};
// Function to add a student record to the file
void addStudent() {
Student student;
ofstream file;

file.open("students.txt", ios::app); // Open the file


in append mode
if (!file) {
cout << "File could not be opened." << endl;
return;
}

// Take student information as input


cout << "Enter Roll Number: ";
cin >> student.roll_no;
cin.ignore(); // To ignore the newline left by previous
input
cout << "Enter Name: ";
getline(cin, student.name);
cout << "Enter Division: ";
getline(cin, student.division);
cout << "Enter Address: ";
getline(cin, student.address);

// Write the student data to the file


file << student.roll_no << "," << student.name << ","
<< student.division << "," << student.address <<
endl;

file.close();
cout << "Student added successfully." << endl;
}

// Function to delete a student record from the file


void deleteStudent() {
int roll_no;
cout << "Enter Roll Number to delete: ";
cin >> roll_no;

ifstream file("students.txt");
if (!file) {
cout << "File could not be opened." << endl;
return;
}

ofstream temp("temp.txt"); // Temporary file to store


updated records
if (!temp) {
cout << "Temporary file could not be opened." <<
endl;
return;
}

string line;
bool found = false;

while (getline(file, line)) {


stringstream ss(line);
int file_roll_no;
string name, division, address;
char comma;

ss >> file_roll_no >> comma;


getline(ss, name, ',');
getline(ss, division, ',');
getline(ss, address);

if (file_roll_no == roll_no) {
found = true; // Found the student to delete
continue;
}

temp << file_roll_no << "," << name << "," <<
division << "," << address << endl;
}

file.close();
temp.close();

if (found) {
remove("students.txt"); // Delete the original file
rename("temp.txt", "students.txt"); // Rename the
temp file to the original file name
cout << "Student record deleted successfully." <<
endl;
} else {
cout << "Student with Roll Number " << roll_no << "
not found." << endl;
}
}

// Function to display a student's information


void displayStudent() {
int roll_no;
cout << "Enter Roll Number to display: ";
cin >> roll_no;

ifstream file("students.txt");
if (!file) {
cout << "File could not be opened." << endl;
return;
}

string line;
bool found = false;
while (getline(file, line)) {
stringstream ss(line);
int file_roll_no;
string name, division, address;
char comma;

ss >> file_roll_no >> comma;


getline(ss, name, ',');
getline(ss, division, ',');
getline(ss, address);

if (file_roll_no == roll_no) {
found = true;
cout << "Roll Number: " << file_roll_no << endl;
cout << "Name: " << name << endl;
cout << "Division: " << division << endl;
cout << "Address: " << address << endl;
break;
}
}

file.close();

if (!found) {
cout << "Student with Roll Number " << roll_no << "
not found." << endl;
}
}

// Main function for interacting with the menu


int main() {
int choice;

while (true) {
cout << "\nStudent Information System\n";
cout << "1. Add Student\n";
cout << "2. Delete Student\n";
cout << "3. Display Student\n";
cout << "4. Exit\n";
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 1:
addStudent();
break;
case 2:
deleteStudent();
break;
case 3:
displayStudent();
break;
case 4:
cout << "Exiting the program." << endl;
return 0;
default:
cout << "Invalid choice. Please try again."
<< endl;
}
}

return 0;
}
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>

using namespace std;

// Define the structure for an employee


struct Employee {
int id;
string name;
string designation;
double salary;
};

// Define the structure for an index entry


struct IndexEntry {
int id; // Employee ID
long position; // Position of the record in the main
data file
};

// Function to add a new employee to the data file and


update the index file
void addEmployee() {
Employee emp;
fstream dataFile, indexFile;

// Open the data file and index file in read/write mode


dataFile.open("employee.dat", ios::in | ios::out |
ios::app | ios::binary);
indexFile.open("index.dat", ios::in | ios::out |
ios::app | ios::binary);
if (!dataFile || !indexFile) {
cout << "File could not be opened." << endl;
return;
}

// Take employee information as input


cout << "Enter Employee ID: ";
cin >> emp.id;
cin.ignore();
cout << "Enter Employee Name: ";
getline(cin, emp.name);
cout << "Enter Designation: ";
getline(cin, emp.designation);
cout << "Enter Salary: ";
cin >> emp.salary;

// Write the employee data to the data file


dataFile.seekp(0, ios::end); // Move to the end of the
data file
long position = dataFile.tellp();
dataFile.write(reinterpret_cast<char*>(&emp),
sizeof(emp));

// Write the index entry to the index file


IndexEntry indexEntry = {emp.id, position};
indexFile.write(reinterpret_cast<char*>(&indexEntry),
sizeof(indexEntry));

dataFile.close();
indexFile.close();
cout << "Employee added successfully." << endl;
}

// Function to delete an employee record by ID


void deleteEmployee() {
int empID;
cout << "Enter Employee ID to delete: ";
cin >> empID;

fstream dataFile, indexFile, tempDataFile,


tempIndexFile;

// Open data files for reading and writing


dataFile.open("employee.dat", ios::in | ios::out |
ios::binary);
indexFile.open("index.dat", ios::in | ios::out |
ios::binary);
tempDataFile.open("temp_employee.dat", ios::out |
ios::binary);
tempIndexFile.open("temp_index.dat", ios::out |
ios::binary);

if (!dataFile || !indexFile || !tempDataFile || !


tempIndexFile) {
cout << "File could not be opened." << endl;
return;
}

bool found = false;


IndexEntry indexEntry;
Employee emp;

// Read index entries and data file, removing the


specified employee
while
(indexFile.read(reinterpret_cast<char*>(&indexEntry),
sizeof(indexEntry))) {
// If employee ID matches, skip writing to temp
files
if (indexEntry.id == empID) {
found = true;
continue;
}

// Write the index entry to the temporary index file

tempIndexFile.write(reinterpret_cast<char*>(&indexEntry),
sizeof(indexEntry));

// Read and write the corresponding employee record


to the temporary data file
dataFile.seekg(indexEntry.position, ios::beg);
dataFile.read(reinterpret_cast<char*>(&emp),
sizeof(emp));
tempDataFile.write(reinterpret_cast<char*>(&emp),
sizeof(emp));
}

if (found) {
// Delete the original files and rename the
temporary files
dataFile.close();
indexFile.close();
tempDataFile.close();
tempIndexFile.close();

remove("employee.dat");
remove("index.dat");

rename("temp_employee.dat", "employee.dat");
rename("temp_index.dat", "index.dat");

cout << "Employee record deleted successfully." <<


endl;
} else {
cout << "Employee not found." << endl;
}
}

// Function to display employee information by ID


void displayEmployee() {
int empID;
cout << "Enter Employee ID to display: ";
cin >> empID;

fstream dataFile, indexFile;

// Open the data file and index file in read mode


dataFile.open("employee.dat", ios::in | ios::binary);
indexFile.open("index.dat", ios::in | ios::binary);

if (!dataFile || !indexFile) {
cout << "File could not be opened." << endl;
return;
}

bool found = false;


IndexEntry indexEntry;
Employee emp;

// Search for the employee ID in the index file


while
(indexFile.read(reinterpret_cast<char*>(&indexEntry),
sizeof(indexEntry))) {
if (indexEntry.id == empID) {
found = true;
// Read the corresponding employee data from the
data file
dataFile.seekg(indexEntry.position, ios::beg);
dataFile.read(reinterpret_cast<char*>(&emp),
sizeof(emp));

cout << "Employee ID: " << emp.id << endl;


cout << "Name: " << emp.name << endl;
cout << "Designation: " << emp.designation <<
endl;
cout << "Salary: " << emp.salary << endl;
break;
}
}

if (!found) {
cout << "Employee with ID " << empID << " not
found." << endl;
}

dataFile.close();
indexFile.close();
}

// Main menu to interact with the system


int main() {
int choice;

while (true) {
cout << "\nEmployee Information System\n";
cout << "1. Add Employee\n";
cout << "2. Delete Employee\n";
cout << "3. Display Employee\n";
cout << "4. Exit\n";
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 1:
addEmployee();
break;
case 2:
deleteEmployee();
break;
case 3:
displayEmployee();
break;
case 4:
cout << "Exiting the program." << endl;
return 0;
default:
cout << "Invalid choice. Please try again."
<< endl;
}
}

return 0;
}
import random

# Class to represent the Snake and Ladder game


class SnakeAndLadder:
def __init__(self):
# Create a dictionary for snakes and ladders
# Key is the start position, value is the end
position
self.snakes = {16: 6, 47: 26, 49: 11, 56: 53, 62:
19, 64: 60, 87: 24, 93: 73, 95: 75, 98: 78}
self.ladders = {1: 38, 4: 14, 9: 31, 21: 42, 28: 84,
36: 44, 51: 67, 71: 91, 80: 100}

self.player1_position = 0
self.player2_position = 0
self.turn = 1 # Player 1 starts
# Function to roll the dice (returns a value between 1
and 6)
def roll_dice(self):
return random.randint(1, 6)

# Function to handle player movement


def move_player(self, player, roll):
if player == 1:
new_position = self.player1_position + roll
if new_position > 100:
new_position = self.player1_position #
Player can't go beyond 100
self.player1_position =
self.check_snakes_and_ladders(new_position)
print(f"Player 1 rolls a {roll} and moves to
{self.player1_position}")
else:
new_position = self.player2_position + roll
if new_position > 100:
new_position = self.player2_position #
Player can't go beyond 100
self.player2_position =
self.check_snakes_and_ladders(new_position)
print(f"Player 2 rolls a {roll} and moves to
{self.player2_position}")

# Function to check if player has landed on a snake or


ladder
def check_snakes_and_ladders(self, position):
if position in self.snakes:
print(f"Oops! Landed on a snake! Moving back to
{self.snakes[position]}")
return self.snakes[position]
elif position in self.ladders:
print(f"Yay! Landed on a ladder! Moving up to
{self.ladders[position]}")
return self.ladders[position]
return position

# Function to check for the winner


def check_winner(self):
if self.player1_position == 100:
return "Player 1 wins!"
elif self.player2_position == 100:
return "Player 2 wins!"
return None

# Function to display the current status of the game


def display_status(self):
print(f"Player 1 is at position
{self.player1_position}")
print(f"Player 2 is at position
{self.player2_position}")

# Main function to start the game


def start_game(self):
while True:
self.display_status()
if self.turn == 1:
print("Player 1's turn")
roll = self.roll_dice()
self.move_player(1, roll)
self.turn = 2 # Switch turn to Player 2
else:
print("Player 2's turn")
roll = self.roll_dice()
self.move_player(2, roll)
self.turn = 1 # Switch turn to Player 1

winner = self.check_winner()
if winner:
print(winner)
break

# Main function to play the game


if __name__ == "__main__":
game = SnakeAndLadder()
game.start_game()

You might also like

pFad - Phonifier reborn

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

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


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy