0% found this document useful (0 votes)
4 views14 pages

Data Structures & Algorithms: BSCS-402

The document contains assignments for a Data Structures and Algorithms course, detailing various C++ programming tasks. These include generating subsets using bitmasking, organizing a closet with file input and sorting, implementing N-dimensional dynamic arrays, and creating a dynamic linked list with essential operations. Each assignment includes a description and code implementation, showcasing different programming techniques and data structures.

Uploaded by

fizzanna9210
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)
4 views14 pages

Data Structures & Algorithms: BSCS-402

The document contains assignments for a Data Structures and Algorithms course, detailing various C++ programming tasks. These include generating subsets using bitmasking, organizing a closet with file input and sorting, implementing N-dimensional dynamic arrays, and creating a dynamic linked list with essential operations. Each assignment includes a description and code implementation, showcasing different programming techniques and data structures.

Uploaded by

fizzanna9210
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/ 14

dkfjkdfjkf

Data Structures
& Algorithms
BSCS-402
ASSIGNMENTS

Name: Ain Ul Wara


Seat no: B22110006013
Section: A
2nd year, 4th Semester

Course Incharge:
Sir Muhammed Saeed
Assignment No# 1:
Permutations & Combinations
This C++ program generates all non-empty subsets of a given set using
bitmasking. It iterates through all bitmask values from `1` to `2^n - 1`, where each
bit represents whether an element is included in the subset. The subsets are
displayed in the format `{ element1 element2 ... }`, excluding the empty subset.
The approach efficiently generates all possible subsets without calculating
permutations or combinations. For example, with the set `{1, 2, 3}`, the output will
include `{ 1 }`, `{ 2 }`, `{ 3 }`, `{ 1 2 }`, `{ 1 3 }`, `{ 2 3 }`, and `{ 1 2 3 }`. This
method offers a simple and efficient solution for generating subsets.

Code Implementation:
#include <iostream>
#include <vector>
using namespace std;

void generateSubsets(vector<int>& set) {


int n = set.size();
int totalSubsets = 1 << n; // 2^n subsets

for (int subsetMask = 1; subsetMask < totalSubsets; ++subsetMask) {


vector<int> subset;
for (int i = 0; i < n; ++i) {
// Check if the i-th element is in the subset
if (subsetMask & (1 << i)) {
subset.push_back(set[i]);
}
}

// Print the current subset


cout << "{ ";
for (size_t j = 0; j < subset.size(); ++j) {
cout << subset[j] << " ";
}
cout << "}\n";
}
}

int main() {
int arr[] = {1, 2, 3}; // C++98-compatible array
vector<int> set(arr, arr + sizeof(arr) / sizeof(arr[0])); // Initialize vector from array
generateSubsets(set);
return 0;
}
Output:

Assignment No# 2:
Sorting a messy closet
In this assignment, we created a C++ program to organize a messy closet by
reading clothing items from a text file, sorting them alphabetically, and
implementing a search functionality to locate a specific item. The
`readClosetItems` function opens a text file (`closet.txt`) and reads each clothing
item, represented by a character, into a vector. The `sortCloset` function sorts these
items alphabetically using the `sort` algorithm, and the `searchCloset` function
implements binary search to check if a specific item exists in the sorted closet. The
program first displays the unorganized closet, then shows the organized closet, and
allows the user to search for a clothing item. For example, if the closet items are `P
S H T J`, the program first prints them as `P S H T J`, then after sorting, it displays
`H J P S T`. The user can search for any item, and the program will confirm its
presence or absence. This assignment demonstrates efficient closet management
using file input, sorting, and searching techniques.

Code Implementation:
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;

vector<char> readClosetItems(const string& filename) {


vector<char> closet;
ifstream file("closet.txt");

if (file.is_open()) {
char item;
while (file >> item) {
closet.push_back(item);
}
file.close();
} else {
cout << "Unable to open file.\n";
}

return closet;
}

void sortCloset(vector<char>& closet) {


sort(closet.begin(), closet.end());
}

bool searchCloset(const vector<char>& closet, char item) {


return binary_search(closet.begin(), closet.end(), item);
}

int main() {
string filename = "closet.txt"; // Input file containing unorganized closet items
vector<char> closet = readClosetItems(filename);

// Display the unorganized closet


cout << "Unorganized Closet: ";
for (size_t i = 0; i < closet.size(); ++i) {
cout << closet[i] << " ";
}
cout << endl;

// Sort the closet items


sortCloset(closet);

// Display the organized closet


cout << "Organized Closet: ";
for (size_t i = 0; i < closet.size(); ++i) {
cout << closet[i] << " ";
}
cout << endl;
// Search for an item in the organized closet
char searchItem;
cout << "Enter the clothing item to search for: ";
cin >> searchItem;

// Display search result


if (searchCloset(closet, searchItem)) {
cout << "Item " << searchItem << " found in the closet.\n";
} else {
cout << "Item " << searchItem << " not found in the closet.\n";
}

return 0;
}

Output:
Assignment No# # 3:
Row Major & Column Major in Arrays
This assignment presents an N-dimensional dynamic array in C++ supporting both
row-major and column-major ordering. The `NDArray` class stores dimensions
and data in vectors, with helper functions to calculate linear indices for efficient
element access. Key methods `setRowMajor` and `getRowMajor` handle row-
major operations, while `setColumnMajor` and `getColumnMajor` support
column-major access. In `main`, we create a 3x3x3 array, set elements, and
retrieve them using both orderings. Display functions print all elements in each
format, demonstrating flexible and efficient multi-dimensional storage and access.

Code Implementation:
#include <iostream>
#include <vector>

class NDArray {
private:
std::vector<int> dimensions; // Stores the size of each dimension
std::vector<int> data; // Flat vector for storing all elements
int totalSize; // Total number of elements

// Helper function to compute the linear index in row-major order


int getRowMajorIndex(const std::vector<int>& indices) const {
int index = 0;
int factor = 1;
for (int i = dimensions.size() - 1; i >= 0; --i) {
index += indices[i] * factor;
factor *= dimensions[i];
}
return index;
}

// Helper function to compute the linear index in column-major order


int getColumnMajorIndex(const std::vector<int>& indices) const {
int index = 0;
int factor = 1;
for (int i = 0; i < dimensions.size(); ++i) {
index += indices[i] * factor;
factor *= dimensions[i];
}
return index;
}

public:
// Constructor to initialize the array with given dimensions
NDArray(const std::vector<int>& dims) : dimensions(dims) {
// Check if dimensions are non-empty
if (dimensions.empty()) {
std::cerr << "Error: Dimensions vector is empty." << std::endl;
exit(1); // Exit the program if dimensions are invalid
}

totalSize = 1;
for (size_t i = 0; i < dimensions.size(); ++i) { // Replaced range-based loop
totalSize *= dimensions[i]; // Access via index
}
data.resize(totalSize, 0); // Initialize all elements to 0
}

// Set value using row-major order


void setRowMajor(const std::vector<int>& indices, int value) {
int index = getRowMajorIndex(indices);
data[index] = value;
}

// Get value using row-major order


int getRowMajor(const std::vector<int>& indices) const {
int index = getRowMajorIndex(indices);
return data[index];
}

// Set value using column-major order


void setColumnMajor(const std::vector<int>& indices, int value) {
int index = getColumnMajorIndex(indices);
data[index] = value;
}

// Get value using column-major order


int getColumnMajor(const std::vector<int>& indices) const {
int index = getColumnMajorIndex(indices);
return data[index];
}

// Display all elements in row-major order


void displayRowMajor() const {
std::cout << "Array elements (Row-Major Order): ";
for (int i = 0; i < totalSize; ++i) {
std::cout << data[i] << " ";
}
std::cout << std::endl;
}

// Display all elements in column-major order


void displayColumnMajor() const {
std::cout << "Array elements (Column-Major Order): ";
for (int i = 0; i < totalSize; ++i) {
// Reverse calculate indices for display purposes
std::vector<int> indices(dimensions.size());
int temp = i;
for (int j = 0; j < dimensions.size(); ++j) {
indices[j] = temp % dimensions[j];
temp /= dimensions[j];
}
std::cout << getColumnMajor(indices) << " ";
}
std::cout << std::endl;
}
};

int main() {
// Initialize dimensions with push_back (for C++98 compatibility)
std::vector<int> dims;
dims.push_back(3);
dims.push_back(3);
dims.push_back(3); // 3x3x3 array

NDArray array(dims); // Initialize the array with dimensions

// Setting elements in row-major order


std::vector<int> indices;
indices.push_back(0);
indices.push_back(0);
indices.push_back(0);
array.setRowMajor(indices, 1);

indices[2] = 1; // Update the indices for the next element


array.setRowMajor(indices, 2);

indices[0] = 1;
indices[1] = 2;
indices[2] = 2;
array.setRowMajor(indices, 9);
// Getting elements in row-major order
std::cout << "Row-Major Order Access:\n";
indices[0] = 0;
indices[1] = 0;
indices[2] = 0;
std::cout << "array[0][0][0] = " << array.getRowMajor(indices) << std::endl;

indices[2] = 1;
std::cout << "array[0][0][1] = " << array.getRowMajor(indices) << std::endl;

indices[0] = 1;
indices[1] = 2;
indices[2] = 2;
std::cout << "array[1][2][2] = " << array.getRowMajor(indices) << std::endl;

// Setting elements in column-major order


indices[0] = 0;
indices[1] = 0;
indices[2] = 0;
array.setColumnMajor(indices, 3);

indices[2] = 1;
array.setColumnMajor(indices, 4);

indices[0] = 2;
indices[1] = 2;
indices[2] = 2;
array.setColumnMajor(indices, 10);

// Getting elements in column-major order


std::cout << "Column-Major Order Access:\n";
indices[0] = 0;
indices[1] = 0;
indices[2] = 0;
std::cout << "array[0][0][0] = " << array.getColumnMajor(indices) << std::endl;

indices[2] = 1;
std::cout << "array[0][0][1] = " << array.getColumnMajor(indices) << std::endl;

indices[0] = 2;
indices[1] = 2;
indices[2] = 2;
std::cout << "array[2][2][2] = " << array.getColumnMajor(indices) << std::endl;

// Display elements in row-major order


array.displayRowMajor();

// Display elements in column-major order


array.displayColumnMajor();

return 0;
}

Output:

Assignment No# # 4:
Implementaions of ADT:
1. Dynamic Linked list:
In this assignment, implement a dynamic linked list in C++ with essential
operations. Create a `LinkedList` class that includes methods for appending
(`append`), inserting at a specific position (`insert`), displaying all nodes
(`display`), searching for a value (`search`), and deleting a node by value
(`deleteNode`). Use a `Node` structure to store an integer value and a pointer
to the next node. In `main()`, demonstrate the list by appending values 10,
20, and 30, inserting 15 at position 1, displaying the list, searching for values
20 and 25, deleting the node with value 20, and displaying the final list.
Implement a destructor to clean up memory, ensuring no memory leaks
occur.

Code Implementation:
#include <iostream>
using namespace std;
// Node structure for the linked list
struct Node {
int data;
Node* next;

Node(int value) : data(value), next(NULL) {}


};

// Linked List class


class LinkedList {
private:
Node* head;

public:
LinkedList() : head(NULL) {}

// Function to append a new node at the end


void append(int value) {
Node* newNode = new Node(value);
if (!head) {
head = newNode;
} else {
Node* temp = head;
while (temp->next) {
temp = temp->next;
}
temp->next = newNode;
}
}

// Function to insert a node at a specific position


void insert(int value, int position) {
Node* newNode = new Node(value);
if (position == 0) {
newNode->next = head;
head = newNode;
} else {
Node* temp = head;
for (int i = 0; i < position - 1 && temp; i++) {
temp = temp->next;
}
if (temp) {
newNode->next = temp->next;
temp->next = newNode;
} else {
cout << "Position out of bounds" << endl;
delete newNode;
}
}
}

// Function to display all nodes in the list


void display() {
Node* temp = head;
while (temp) {
cout << temp->data << " -> ";
temp = temp->next;
}
cout << "NULL" << endl;
}

// Function to search for a value in the list


bool search(int value) {
Node* temp = head;
while (temp) {
if (temp->data == value) {
return true;
}
temp = temp->next;
}
return false;
}

// Function to delete a node by value


void deleteNode(int value) {
if (!head) return;

if (head->data == value) {
Node* temp = head;
head = head->next;
delete temp;
return;
}

Node* temp = head;


while (temp->next && temp->next->data != value) {
temp = temp->next;
}

if (temp->next) {
Node* toDelete = temp->next;
temp->next = temp->next->next;
delete toDelete;
} else {
cout << "Value not found in the list" << endl;
}
}

// Destructor to free up memory


~LinkedList() {
while (head) {
Node* temp = head;
head = head->next;
delete temp;
}
}
};

int main() {
LinkedList list;
list.append(10);
list.append(20);
list.append(30);
list.insert(15, 1); // Inserts 15 at position 1
list.display();

cout << "Searching for 20: " << (list.search(20) ? "Found" : "Not Found") << endl;
cout << "Searching for 25: " << (list.search(25) ? "Found" : "Not Found") << endl;

list.deleteNode(20); // Deletes the node with value 20


list.display();

return 0;
}

Output:

Thank you so much for your time!

You might also like