cleaning up excess projects
This commit is contained in:
@@ -1,19 +0,0 @@
|
||||
# CMakeList.txt : Top-level CMake project file, do global configuration
|
||||
# and include sub-projects here.
|
||||
#
|
||||
cmake_minimum_required (VERSION 3.20)
|
||||
|
||||
# Enable Hot Reload for MSVC compilers if supported.
|
||||
if (POLICY CMP0141)
|
||||
cmake_policy(SET CMP0141 NEW)
|
||||
set(CMAKE_MSVC_DEBUG_INFORMATION_FORMAT "$<IF:$<AND:$<C_COMPILER_ID:MSVC>,$<CXX_COMPILER_ID:MSVC>>,$<$<CONFIG:Debug,RelWithDebInfo>:EditAndContinue>,$<$<CONFIG:Debug,RelWithDebInfo>:ProgramDatabase>>")
|
||||
endif()
|
||||
|
||||
project ("Exercises")
|
||||
|
||||
# Include sub-projects.
|
||||
add_subdirectory ("Submission-01")
|
||||
add_subdirectory ("Submission-02")
|
||||
add_subdirectory ("Submission-03")
|
||||
add_subdirectory ("Submission-04")
|
||||
add_subdirectory ("Submission-05")
|
||||
@@ -1,13 +0,0 @@
|
||||
# CMakeList.txt : CMake project for Submission-01, include source and define
|
||||
# project specific logic here.
|
||||
#
|
||||
|
||||
# Add source to this project's executable.
|
||||
add_executable (Submission-01 "main.cpp" "main.h")
|
||||
target_link_libraries(Submission-01 PRIVATE LibExample)
|
||||
|
||||
if (CMAKE_VERSION VERSION_GREATER 3.20)
|
||||
set_property(TARGET Submission-01 PROPERTY CXX_STANDARD 20)
|
||||
endif()
|
||||
|
||||
# TODO: Add tests and install targets if needed.
|
||||
@@ -1,309 +0,0 @@
|
||||
// Submission-01.cpp : Defines the entry point for the application.
|
||||
//
|
||||
|
||||
#include "main.h"
|
||||
#include <iostream>
|
||||
|
||||
|
||||
|
||||
// Movie class with bitwise genre flags
|
||||
enum EGenreFlags {
|
||||
Action = 0x0001,
|
||||
Comedy = 0x0002,
|
||||
Drama = 0x0004,
|
||||
Horror = 0x0008,
|
||||
SciFi = 0x0010,
|
||||
Romance = 0x0020,
|
||||
Documentary = 0x0040,
|
||||
Thriller = 0x0080,
|
||||
Crime = 0x0100,
|
||||
Fantasy = 0x0200,
|
||||
Animation = 0x0400,
|
||||
Adventure = 0x0800
|
||||
};
|
||||
|
||||
static std::string GenreFlagsToString(int genreFlags) {
|
||||
std::string result;
|
||||
if (genreFlags & EGenreFlags::Action) result += "Action ";
|
||||
if (genreFlags & EGenreFlags::Comedy) result += "Comedy ";
|
||||
if (genreFlags & EGenreFlags::Drama) result += "Drama ";
|
||||
if (genreFlags & EGenreFlags::Horror) result += "Horror ";
|
||||
if (genreFlags & EGenreFlags::SciFi) result += "SciFi ";
|
||||
if (genreFlags & EGenreFlags::Romance) result += "Romance ";
|
||||
if (genreFlags & EGenreFlags::Documentary) result += "Documentary ";
|
||||
if (genreFlags & EGenreFlags::Thriller) result += "Thriller ";
|
||||
if (genreFlags & EGenreFlags::Crime) result += "Crime ";
|
||||
if (genreFlags & EGenreFlags::Fantasy) result += "Fantasy ";
|
||||
if (genreFlags & EGenreFlags::Animation) result += "Animation ";
|
||||
if (genreFlags & EGenreFlags::Adventure) result += "Adventure ";
|
||||
return result.empty() ? "None" : result;
|
||||
}
|
||||
|
||||
// Movie class definition
|
||||
class TMovie {
|
||||
private:
|
||||
std::string title;
|
||||
std::string director;
|
||||
int year;
|
||||
int genreFlags; // Bitwise combination of EGenreFlags
|
||||
float rating; // Scale from 0.0 to 10.0
|
||||
|
||||
public:
|
||||
TMovie(std::string t, std::string d, int y, int g, float r)
|
||||
: title(t), director(d), year(y), genreFlags(g), rating(r) {}
|
||||
void PrintInfo() const {
|
||||
std::cout << "Title: " << title << "\nDirector: " << director
|
||||
<< "\nYear: " << year << "\nGenres: " << GenreFlagsToString(genreFlags)
|
||||
<< "\nRating: " << rating << "/10\n";
|
||||
}
|
||||
std::string GetTitle() const { return title; }
|
||||
std::string GetDirector() const { return director; }
|
||||
int GetYear() const { return year; }
|
||||
float GetRating() const { return rating; }
|
||||
int GetGenreFlags() const { return genreFlags; }
|
||||
bool HasGenre(EGenreFlags genre) const {
|
||||
return (genreFlags & genre) != 0;
|
||||
}
|
||||
};
|
||||
|
||||
typedef bool (*FCheckMovie)(TMovie*, void*);
|
||||
typedef void (*FMovieIndex)(TMovie*, int);
|
||||
|
||||
// Doubly Linked List TMovieNode definition
|
||||
struct TMovieNode {
|
||||
TMovie* movie;
|
||||
TMovieNode* next;
|
||||
TMovieNode* prev;
|
||||
TMovieNode(TMovie* m) : movie(m), next(nullptr), prev(nullptr) {}
|
||||
};
|
||||
|
||||
// Doubly Linked List class definition with dummy node, head, and tail O(1) operations
|
||||
class TMovieList {
|
||||
private:
|
||||
TMovieNode* head; // Always points to dummy node
|
||||
TMovieNode* tail;
|
||||
int size;
|
||||
|
||||
// Helper function to get node at index
|
||||
TMovieNode* InternalGetAtIndex(int aIndex) {
|
||||
if (aIndex < 0 || aIndex >= size) return nullptr;
|
||||
TMovieNode* current;
|
||||
// Optimize traversal direction, if index is in the first half, start from head, else from tail
|
||||
if (aIndex < size / 2) {
|
||||
current = head->next; // Start from the beginning
|
||||
for (int i = 0; i < aIndex; i++) {
|
||||
current = current->next;
|
||||
}
|
||||
}
|
||||
else {
|
||||
current = tail; // Start from the end
|
||||
for (int i = size - 1; i > aIndex; i--) {
|
||||
current = current->prev;
|
||||
}
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
public:
|
||||
TMovieList() {
|
||||
head = new TMovieNode(nullptr); // Dummy node
|
||||
tail = head; // Initially, tail is the same as head
|
||||
size = 0;
|
||||
}
|
||||
~TMovieList() {
|
||||
Clear();
|
||||
delete head; // Delete dummy node
|
||||
}
|
||||
void Clear() {
|
||||
TMovieNode* current = head->next; // Start from the first real node
|
||||
while (current) {
|
||||
TMovieNode* toDelete = current;
|
||||
current = current->next;
|
||||
delete toDelete->movie;
|
||||
delete toDelete;
|
||||
}
|
||||
head->next = nullptr;
|
||||
tail = head; // Reset tail to dummy node
|
||||
size = 0;
|
||||
}
|
||||
|
||||
// Insertion at the end O(1)
|
||||
void Append(TMovie* aMovie) {
|
||||
TMovieNode* newNode = new TMovieNode(aMovie);
|
||||
newNode->prev = tail;
|
||||
tail->next = newNode;
|
||||
tail = newNode;
|
||||
size++;
|
||||
}
|
||||
|
||||
// Prepend at the beginning O(1)
|
||||
void Prepend(TMovie* aMovie) {
|
||||
TMovieNode* newNode = new TMovieNode(aMovie);
|
||||
newNode->next = head->next;
|
||||
newNode->prev = head;
|
||||
if (head->next) {
|
||||
head->next->prev = newNode;
|
||||
} else {
|
||||
tail = newNode; // If list was empty, update tail
|
||||
}
|
||||
head->next = newNode;
|
||||
size++;
|
||||
}
|
||||
|
||||
// GetAtIndex O(n) check direction to optimize
|
||||
TMovie* GetAtIndex(int aIndex) {
|
||||
return InternalGetAtIndex(aIndex)->movie;
|
||||
}
|
||||
|
||||
// Remove at index O(n) use GetAtIndex to find node
|
||||
bool RemoveAtIndex(int aIndex) {
|
||||
if (aIndex < 0 || aIndex >= size) return false;
|
||||
TMovieNode* toDelte = InternalGetAtIndex(aIndex);
|
||||
if (!toDelte) return false;
|
||||
if (toDelte->prev) {
|
||||
toDelte->prev->next = toDelte->next;
|
||||
}
|
||||
if (toDelte->next) {
|
||||
toDelte->next->prev = toDelte->prev;
|
||||
} else {
|
||||
tail = toDelte->prev; // Update tail if last node is removed
|
||||
}
|
||||
delete toDelte->movie;
|
||||
delete toDelte;
|
||||
size--;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Reverse the list O(n)
|
||||
void Reverse() {
|
||||
TMovieNode* current = head->next;
|
||||
TMovieNode* prev = nullptr;
|
||||
tail = head->next;
|
||||
while (current) {
|
||||
TMovieNode* nextNode = current->next;
|
||||
current->next = prev;
|
||||
current->prev = nextNode;
|
||||
prev = current;
|
||||
current = nextNode;
|
||||
}
|
||||
head->next = prev;
|
||||
if (prev) {
|
||||
prev->prev = head;
|
||||
}
|
||||
}
|
||||
|
||||
// SearchFor O(n)
|
||||
TMovie* SearchFor(FCheckMovie aCheckFunc, void* aUserData) {
|
||||
TMovieNode* current = head->next;
|
||||
while (current) {
|
||||
if (aCheckFunc(current->movie, aUserData)) {
|
||||
return current->movie;
|
||||
}
|
||||
current = current->next;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Every movie in the list O(n)
|
||||
void Every(FMovieIndex aIndexFunc) {
|
||||
TMovieNode* current = head->next;
|
||||
int index = 0;
|
||||
while (current) {
|
||||
aIndexFunc(current->movie, index);
|
||||
current = current->next;
|
||||
index++;
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
using namespace std;
|
||||
|
||||
static void PrintNode(std::string* data, int index) {
|
||||
cout << "Node " << index << ": " << *data << endl;
|
||||
}
|
||||
|
||||
static bool CheckMovieByTitle(TMovie* movie, void* title) {
|
||||
return movie->GetTitle() == *(static_cast<std::string*>(title));
|
||||
}
|
||||
|
||||
static bool CheckMovieByDirector(TMovie* movie, void* director) {
|
||||
return movie->GetDirector() == *(static_cast<std::string*>(director));
|
||||
}
|
||||
|
||||
static bool FindAllMovieByGenre(TMovie* movie, void* genre) {
|
||||
if(movie->HasGenre(*(static_cast<EGenreFlags*>(genre)))) {
|
||||
movie->PrintInfo();
|
||||
std::cout << "-------------------" << std::endl;
|
||||
}
|
||||
// Always return false to continue searching
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
int main()
|
||||
{
|
||||
|
||||
std::cout << "--- Submission 1: Linked List ---" << std::endl;
|
||||
|
||||
// Create a movie list
|
||||
TMovieList movieList;
|
||||
// Add some movies
|
||||
movieList.Append(new TMovie("Inception", "Christopher Nolan", 2010, EGenreFlags::Action | EGenreFlags::SciFi, 8.8f));
|
||||
movieList.Append(new TMovie("The Godfather", "Francis Ford Coppola", 1972, EGenreFlags::Crime | EGenreFlags::Drama, 9.2f));
|
||||
movieList.Prepend(new TMovie("Toy Story", "John Lasseter", 1995, EGenreFlags::Animation | EGenreFlags::Adventure | EGenreFlags::Comedy, 8.3f));
|
||||
movieList.Append(new TMovie("The Dark Knight", "Christopher Nolan", 2008, EGenreFlags::Action | EGenreFlags::Crime | EGenreFlags::Drama, 9.0f));
|
||||
// Print movie info
|
||||
for (int i = 0; i < 3; i++) {
|
||||
TMovie* movie = movieList.GetAtIndex(i);
|
||||
if (movie) {
|
||||
movie->PrintInfo();
|
||||
std::cout << "-------------------" << std::endl;
|
||||
}
|
||||
}
|
||||
std::cout << std::endl;
|
||||
// Wait for user input to proceed
|
||||
std::cout << "Press Enter to continue..." << std::endl;
|
||||
std::cin.get();
|
||||
|
||||
// Search for a movie by title
|
||||
std::string searchTitle = "Inception";
|
||||
TMovie* foundMovie = movieList.SearchFor(CheckMovieByTitle, &searchTitle);
|
||||
if (foundMovie) {
|
||||
std::cout << "Found movie by title '" << searchTitle << "':" << std::endl;
|
||||
foundMovie->PrintInfo();
|
||||
} else {
|
||||
std::cout << "Movie with title '" << searchTitle << "' not found." << std::endl;
|
||||
}
|
||||
std::cout << "-------------------" << std::endl;
|
||||
std::cout << std::endl;
|
||||
|
||||
// Search for a movie by director
|
||||
std::string searchDirector = "John Lasseter";
|
||||
foundMovie = movieList.SearchFor(CheckMovieByDirector, &searchDirector);
|
||||
if (foundMovie) {
|
||||
std::cout << "Found movie by director '" << searchDirector << "':" << std::endl;
|
||||
foundMovie->PrintInfo();
|
||||
} else {
|
||||
std::cout << "Movie with director '" << searchDirector << "' not found." << std::endl;
|
||||
}
|
||||
std::cout << "-------------------" << std::endl;
|
||||
std::cout << std::endl;
|
||||
|
||||
// Find all movies in the Action genre
|
||||
EGenreFlags searchGenre = EGenreFlags::Action;
|
||||
std::cout << "Movies in the Action genre:" << std::endl;
|
||||
movieList.SearchFor(FindAllMovieByGenre, &searchGenre);
|
||||
std::cout << std::endl;
|
||||
|
||||
// Reverse the list
|
||||
movieList.Reverse();
|
||||
std::cout << "Movies after reversing the list:" << std::endl;
|
||||
movieList.Every([](TMovie* movie, int index) {
|
||||
std::cout << "Index " << index << ":" << std::endl;
|
||||
movie->PrintInfo();
|
||||
std::cout << "-------------------" << std::endl;
|
||||
});
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
// Submission-01.h : Include file for standard system include files,
|
||||
// or project specific include files.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <iostream>
|
||||
|
||||
// TODO: Reference additional headers your program requires here.
|
||||
@@ -1,13 +0,0 @@
|
||||
# CMakeList.txt : CMake project for Submission-01, include source and define
|
||||
# project specific logic here.
|
||||
#
|
||||
|
||||
# Add source to this project's executable.
|
||||
add_executable (Submission-02 "main.cpp" "main.h")
|
||||
target_link_libraries(Submission-02 PRIVATE LibExample)
|
||||
|
||||
if (CMAKE_VERSION VERSION_GREATER 3.20)
|
||||
set_property(TARGET Submission-02 PROPERTY CXX_STANDARD 20)
|
||||
endif()
|
||||
|
||||
# TODO: Add tests and install targets if needed.
|
||||
@@ -1,121 +0,0 @@
|
||||
// Submission-01.cpp : Defines the entry point for the application.
|
||||
//
|
||||
|
||||
#include "main.h"
|
||||
#include <iostream>
|
||||
|
||||
|
||||
// printNaturalNumbers
|
||||
static void printNaturalNumbers(int aN)
|
||||
{
|
||||
if (aN <= 0) return; // Base case: if n is less than or equal to 0, do nothing
|
||||
printNaturalNumbers(aN - 1); // Recursive call with n-1
|
||||
std::cout << aN << " "; // Print the number after the recursive call to achieve ascending order
|
||||
}
|
||||
|
||||
// factorial function
|
||||
static int calculateFactorial(int aN)
|
||||
{
|
||||
if (aN <= 1) return 1; // Base case: factorial of 0 or 1 is 1
|
||||
return aN * calculateFactorial(aN - 1); // Recursive call
|
||||
}
|
||||
|
||||
// power function using exponentiation by squaring
|
||||
// This method is more efficient than the naive approach, reducing the time complexity from O(n) to O(log n).
|
||||
static int power(int aBase, int aExponent)
|
||||
{
|
||||
if (aExponent == 0) return 1; // Base case: any number to the power of 0 is 1
|
||||
if (aExponent < 0) return 1 / power(aBase, -aExponent); // Handle negative exponents
|
||||
if (aExponent % 2 == 0) // If exponent is even
|
||||
{
|
||||
int halfPower = power(aBase, aExponent / 2);
|
||||
return halfPower * halfPower; // (x^(n/2))^2
|
||||
}
|
||||
else // If exponent is odd
|
||||
{
|
||||
return aBase * power(aBase, aExponent - 1); // x * x^(n-1)
|
||||
}
|
||||
}
|
||||
|
||||
// Fibonacci function
|
||||
// Note: This naive recursive solution is inefficient because it recalculates the same Fibonacci numbers multiple times, leading to an exponential time complexity of O(2^n).
|
||||
// An improvement could be made by using memoization or an iterative approach to store previously calculated values, reducing the time complexity to O(n).
|
||||
static int fibonacci(int aN)
|
||||
{
|
||||
if (aN <= 0) return 0; // Base case: fibonacci(0) = 0
|
||||
if (aN == 1) return 1; // Base case: fibonacci(1) = 1
|
||||
int a = fibonacci(aN - 1);
|
||||
int b = fibonacci(aN - 2);
|
||||
std::cout << a << " + " << b << " = " << (a + b) << std::endl; // Print the sum of the two preceding numbers
|
||||
return a + b; // Recursive call
|
||||
}
|
||||
|
||||
// Count occurrences of a character in a string
|
||||
// This function counts how many times a specific character appears in a given string using recursion.
|
||||
static int countOccurrences(const char* aS, char aC)
|
||||
{
|
||||
if (*aS == '\0') return 0; // Base case: end of string
|
||||
return (*aS == aC ? 1 : 0) + countOccurrences(aS + 1, aC); // Check current character and recurse for the rest of the string
|
||||
}
|
||||
|
||||
// Find the largest element in an array using binary recursion
|
||||
// This function divides the array into two halves, finds the largest element in each half recursively, and then returns the larger of the two.
|
||||
static int findLargestElement(int arr[], int size)
|
||||
{
|
||||
if (size == 1) return arr[0]; // Base case: only one element
|
||||
int mid = size / 2;
|
||||
int leftMax = findLargestElement(arr, mid); // Find max in left half
|
||||
int rightMax = findLargestElement(arr + mid, size - mid); // Find max in right half
|
||||
return (leftMax > rightMax) ? leftMax : rightMax; // Return the larger of the two
|
||||
}
|
||||
|
||||
// Traverse and print characters in the ASCII table from aStart to aEnd using recursion
|
||||
// This function prints characters in ascending order during the building phase of the recursion and in descending order during the unwinding phase.
|
||||
static void traverseAsciiTable(char aStart, char aEnd)
|
||||
{
|
||||
if (aStart > aEnd) return; // Base case: if start exceeds end, do nothing
|
||||
std::cout << aStart << " "; // Print before the recursive call
|
||||
traverseAsciiTable(aStart + 1, aEnd); // Recursive call with next character
|
||||
std::cout << aStart << " "; // Print after the recursive call
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
std::cout << "--- Submission 2: Fundamental Recursion ---" << std::endl;
|
||||
std::cout << std::endl << "Part 1: Linear Recursion - Your First Steps" << std::endl;
|
||||
printNaturalNumbers(5);
|
||||
std::cout << std::endl << "------------------------------------------------" << std::endl;
|
||||
|
||||
std::cout << std::endl << "Factorial of 5: " << calculateFactorial(5);
|
||||
std::cout << std::endl << "------------------------------------------------" << std::endl;
|
||||
|
||||
std::cout << std::endl << "Part 2: Multiple & Binary Recursion - Diving Deeper" << std::endl;
|
||||
std::cout << std::endl << "2^10: " << power(2, 10);
|
||||
std::cout << std::endl << "------------------------------------------------" << std::endl;
|
||||
|
||||
std::cout << std::endl << "4th Fibonacci number: " << std::endl << fibonacci(4);
|
||||
std::cout << std::endl << "------------------------------------------------" << std::endl;
|
||||
|
||||
std::cout << std::endl << "Occurrences of 'l' in 'Hello, World!': " << countOccurrences("Hello, World!", 'l');
|
||||
std::cout << std::endl << "------------------------------------------------" << std::endl;
|
||||
|
||||
int* arr = new int[20];
|
||||
// Fill array with random numbers from 0 to 999
|
||||
for (int i = 0; i < 20; ++i) arr[i] = rand() % 999;
|
||||
std::cout << std::endl << "Part 3: Advanced Binary Recursion" << std::endl;
|
||||
// Print first 20 elements of the array
|
||||
for (int i = 0; i < 20; ++i) std::cout << arr[i] << " ";
|
||||
|
||||
std::cout << std::endl << "Largest element in array: " << findLargestElement(arr, 20);
|
||||
std::cout << std::endl << "------------------------------------------------" << std::endl;
|
||||
|
||||
std::cout << std::endl << "Traverse ASCII table from 'A' to 'Z':" << std::endl;
|
||||
traverseAsciiTable('A', 'Z');
|
||||
|
||||
/*
|
||||
Note: The output reflects the building and unwinding of the call stack.
|
||||
*/
|
||||
|
||||
std::cout << std::endl;
|
||||
return 0;
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
// Submission-01.h : Include file for standard system include files,
|
||||
// or project specific include files.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <iostream>
|
||||
|
||||
// TODO: Reference additional headers your program requires here.
|
||||
@@ -1,13 +0,0 @@
|
||||
# CMakeList.txt : CMake project for Submission-01, include source and define
|
||||
# project specific logic here.
|
||||
#
|
||||
|
||||
# Add source to this project's executable.
|
||||
add_executable (Submission-03 "main.cpp" "main.h")
|
||||
target_link_libraries(Submission-03 PRIVATE LibExample)
|
||||
|
||||
if (CMAKE_VERSION VERSION_GREATER 3.20)
|
||||
set_property(TARGET Submission-03 PROPERTY CXX_STANDARD 20)
|
||||
endif()
|
||||
|
||||
# TODO: Add tests and install targets if needed.
|
||||
@@ -1,439 +0,0 @@
|
||||
// Submission-01.cpp : Defines the entry point for the application.
|
||||
//
|
||||
|
||||
#include "main.h"
|
||||
#include <iostream>
|
||||
|
||||
|
||||
/*
|
||||
Part 1: Implementing the Core Data Structures
|
||||
These tasks are designed to get you comfortable with the Last-In, First-Out (LIFO) and First-In, First-Out (FIFO) principles. Building these yourself will give you a deep understanding of how they work under the hood!
|
||||
*/
|
||||
|
||||
/*
|
||||
1. Implementing a Stack:
|
||||
a) Create a simple TStack class that can hold int values.
|
||||
b) Use a fixed-size array and a top-of-stack index to manage the data.
|
||||
c) Implement the core methods: Push(int item) and Pop().
|
||||
D) Add a Peek() method to view the top item without removing it.
|
||||
e) Include an IsEmpty() method to check if the stack is empty.
|
||||
*/
|
||||
|
||||
class TStackArray {
|
||||
private:
|
||||
int maxSize = 0;
|
||||
int* stackArray = nullptr;
|
||||
int top = -1; // Index of the top element
|
||||
public:
|
||||
TStackArray(int aSize) : maxSize(aSize) {
|
||||
stackArray = new int[maxSize];
|
||||
}
|
||||
~TStackArray() {
|
||||
delete[] stackArray;
|
||||
}
|
||||
void Push(int aItem) {
|
||||
if (top < maxSize - 1) {
|
||||
stackArray[++top] = aItem;
|
||||
}
|
||||
else {
|
||||
std::cout << "Stack Overflow" << std::endl;
|
||||
}
|
||||
}
|
||||
int Pop() {
|
||||
if (!IsEmpty()) {
|
||||
return stackArray[top--];
|
||||
}
|
||||
else {
|
||||
std::cout << "Stack Underflow" << std::endl;
|
||||
return -1; // Indicate error
|
||||
}
|
||||
}
|
||||
int Peek() const {
|
||||
if (!IsEmpty()) {
|
||||
return stackArray[top];
|
||||
}
|
||||
else {
|
||||
std::cout << "Stack is empty" << std::endl;
|
||||
return -1; // Indicate error
|
||||
}
|
||||
}
|
||||
bool IsEmpty() const {
|
||||
return top == -1;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/*
|
||||
2. Implementing a Queue:
|
||||
a) Create a simple TQueue class that can hold int values.
|
||||
b) Use a fixed-size array and front/back indices to manage the data.
|
||||
c) Implement the core methods: Enqueue(int item) and Dequeue().
|
||||
d) Add a Peek() method to view the item at the front without removing it.
|
||||
e) Include an IsEmpty() method to check if the queue is empty.
|
||||
*/
|
||||
|
||||
class TQueueArray {
|
||||
private:
|
||||
int maxSize = 0;
|
||||
int* queueArray = nullptr;
|
||||
int front = 0; // Index of the front element
|
||||
int back = -1; // Index of the back element
|
||||
int itemCount = 0; // Number of items in the queue
|
||||
public:
|
||||
TQueueArray(int aSize) : maxSize(aSize) {
|
||||
queueArray = new int[maxSize];
|
||||
}
|
||||
~TQueueArray() {
|
||||
delete[] queueArray;
|
||||
}
|
||||
void Enqueue(int aItem) {
|
||||
if (itemCount < maxSize) {
|
||||
back = (back + 1) % maxSize; // Circular increment
|
||||
queueArray[back] = aItem;
|
||||
itemCount++;
|
||||
}
|
||||
else {
|
||||
std::cout << "Queue Overflow" << std::endl;
|
||||
}
|
||||
}
|
||||
int Dequeue() {
|
||||
if (!IsEmpty()) {
|
||||
int item = queueArray[front];
|
||||
front = (front + 1) % maxSize; // Circular increment
|
||||
itemCount--;
|
||||
return item;
|
||||
}
|
||||
else {
|
||||
std::cout << "Queue Underflow" << std::endl;
|
||||
return -1; // Indicate error
|
||||
}
|
||||
}
|
||||
int Peek() const {
|
||||
if (!IsEmpty()) {
|
||||
return queueArray[front];
|
||||
}
|
||||
else {
|
||||
std::cout << "Queue is empty" << std::endl;
|
||||
return -1; // Indicate error
|
||||
}
|
||||
}
|
||||
bool IsEmpty() const {
|
||||
return itemCount == 0;
|
||||
}
|
||||
};
|
||||
|
||||
class TNodeInteger {
|
||||
public:
|
||||
int data;
|
||||
TNodeInteger* next;
|
||||
TNodeInteger(int aData) : data(aData), next(nullptr) {}
|
||||
};
|
||||
|
||||
// Stack implemented using a linked list with dummy head node
|
||||
class TStackLinkedList {
|
||||
private:
|
||||
TNodeInteger* top = nullptr;
|
||||
public:
|
||||
TStackLinkedList() {
|
||||
top = new TNodeInteger(0); // Dummy head node
|
||||
}
|
||||
~TStackLinkedList() {
|
||||
while (!IsEmpty()) {
|
||||
Pop();
|
||||
}
|
||||
delete top; // Delete dummy head node
|
||||
}
|
||||
void Push(int aItem) {
|
||||
TNodeInteger* newNode = new TNodeInteger(aItem);
|
||||
newNode->next = top->next;
|
||||
top->next = newNode;
|
||||
}
|
||||
int Pop() {
|
||||
if (!IsEmpty()) {
|
||||
TNodeInteger* temp = top->next;
|
||||
int item = temp->data;
|
||||
top->next = temp->next;
|
||||
delete temp; // Free memory
|
||||
return item;
|
||||
}
|
||||
else {
|
||||
std::cout << "Stack Underflow" << std::endl;
|
||||
return -1; // Indicate error
|
||||
}
|
||||
}
|
||||
int Peek() const {
|
||||
if (!IsEmpty()) {
|
||||
return top->next->data;
|
||||
}
|
||||
else {
|
||||
std::cout << "Stack is empty" << std::endl;
|
||||
return -1; // Indicate error
|
||||
}
|
||||
}
|
||||
bool IsEmpty() const {
|
||||
return top->next == nullptr;
|
||||
}
|
||||
};
|
||||
|
||||
// Queue implemented using a linked list with dummy head node
|
||||
class TQueueLinkedList {
|
||||
private:
|
||||
TNodeInteger* front = nullptr;
|
||||
TNodeInteger* back = nullptr;
|
||||
public:
|
||||
TQueueLinkedList() {
|
||||
front = new TNodeInteger(0); // Dummy head node
|
||||
back = front; // Initially, front and back point to the dummy node
|
||||
}
|
||||
~TQueueLinkedList() {
|
||||
while (!IsEmpty()) {
|
||||
Dequeue();
|
||||
}
|
||||
delete front; // Delete dummy head node
|
||||
}
|
||||
void Enqueue(int aItem) {
|
||||
TNodeInteger* newNode = new TNodeInteger(aItem);
|
||||
back->next = newNode;
|
||||
back = newNode;
|
||||
}
|
||||
int Dequeue() {
|
||||
if (!IsEmpty()) {
|
||||
TNodeInteger* temp = front->next;
|
||||
int item = temp->data;
|
||||
front->next = temp->next;
|
||||
if (back == temp) { // If the dequeued node was the last node
|
||||
back = front; // Reset back to the dummy head
|
||||
}
|
||||
delete temp; // Free memory
|
||||
return item;
|
||||
}
|
||||
else {
|
||||
std::cout << "Queue Underflow" << std::endl;
|
||||
return -1; // Indicate error
|
||||
}
|
||||
}
|
||||
int Peek() const {
|
||||
if (!IsEmpty()) {
|
||||
return front->next->data;
|
||||
}
|
||||
else {
|
||||
std::cout << "Queue is empty" << std::endl;
|
||||
return -1; // Indicate error
|
||||
}
|
||||
}
|
||||
bool IsEmpty() const {
|
||||
return front->next == nullptr;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
||||
/*
|
||||
Part 2: Practical Applications
|
||||
Now that you have your own data structures, it's time to put them to work! These are classic problems that perfectly demonstrate the LIFO and FIFO principles.
|
||||
*/
|
||||
|
||||
/*
|
||||
3. String Reversal with a Stack:
|
||||
a) Write a function that takes a string as input and uses your TStack to return the reversed string.
|
||||
b) In a short comment, explain why the stack is the perfect tool for this type of task.
|
||||
*/
|
||||
|
||||
static std::string ReverseString(const char* aStr) {
|
||||
TStackArray stack(strlen(aStr));
|
||||
for (int i = 0; aStr[i] != '\0'; i++) {
|
||||
stack.Push(aStr[i]);
|
||||
}
|
||||
std::string reversed;
|
||||
while (!stack.IsEmpty()) {
|
||||
reversed += static_cast<char>(stack.Pop()); // Cast int back to char
|
||||
}
|
||||
return reversed;
|
||||
/*
|
||||
* Note: The stack is the perfect tool for string reversal because it allows us to push each character of the string onto the stack and then pop them off in reverse order.
|
||||
* And stack is using the rule of LIFO (Last In First Out), so the last character pushed onto the stack will be the first one to be popped off, effectively reversing the order of characters.
|
||||
*/
|
||||
}
|
||||
|
||||
/*
|
||||
4. Recursive Functions with a Stack:
|
||||
a) Remember the factorial function you implemented with recursion in Submission 2? Your computer used a hidden "call stack" to make that happen. Now, your task is to re-implement that function without recursion, using your own `TStack` to manage the process.
|
||||
b) This is a fantastic exercise that will give you a "eureka" moment about how recursion truly works!
|
||||
*/
|
||||
|
||||
static int Factorial(int n) {
|
||||
if (n < 0) return -1; // Factorial is not defined for negative numbers
|
||||
if (n == 0 || n == 1) return 1; // Base case
|
||||
TStackArray stack(n);
|
||||
for (int i = 2; i <= n; i++) {
|
||||
stack.Push(i);
|
||||
}
|
||||
int result = 1;
|
||||
while (!stack.IsEmpty()) {
|
||||
result *= stack.Pop();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/*
|
||||
5. Wait Line Simulation with a Queue:
|
||||
a) Simulate a simple waiting line, such as a ticket counter.
|
||||
b) Use your TQueue to manage a list of people (represented by integer IDs).
|
||||
c) People should Enqueue when they arrive and Dequeue when they are served, clearly demonstrating the FIFO principle.
|
||||
*/
|
||||
|
||||
static void SimulateWaitLine() {
|
||||
TQueueArray queue(5); // Queue with a maximum size of 5
|
||||
// Simulate people arriving
|
||||
for (int i = 1; i <= 5; i++) {
|
||||
std::cout << "Person " << i << " arrives." << std::endl;
|
||||
queue.Enqueue(i);
|
||||
}
|
||||
// Simulate serving people
|
||||
while (!queue.IsEmpty()) {
|
||||
int person = queue.Dequeue();
|
||||
std::cout << "Person " << person << " is served." << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
Part 3: Advanced Traversal - Stacks vs. Queues
|
||||
This is the main event! You will solve the same problem using two different approaches, highlighting the different strengths of stacks and queues.
|
||||
Your recursive functions from Submission 2 actually use an implicit stack, so this task will give you a deeper look into how it all works.
|
||||
*/
|
||||
|
||||
/*
|
||||
6. Setup: The 100x100 Grid:
|
||||
a) Create a 100x100 two-dimensional integer array.
|
||||
b) Populate the array with random integer values between 0 and 9.
|
||||
c) Choose a random starting cell (row, col).
|
||||
d) Create a second 100x100 boolean array to keep track of visited cells.
|
||||
*/
|
||||
|
||||
|
||||
static const int GRID_SIZE = 7;
|
||||
static int grid[GRID_SIZE][GRID_SIZE];
|
||||
static bool visited[GRID_SIZE][GRID_SIZE] = { false };
|
||||
#include <cstdlib>
|
||||
#include <ctime>
|
||||
static void InitializeGrid() {
|
||||
std::srand(static_cast<unsigned int>(std::time(0))); // Seed for randomness
|
||||
for (int i = 0; i < GRID_SIZE; i++) {
|
||||
for (int j = 0; j < GRID_SIZE; j++) {
|
||||
grid[i][j] = std::rand() % 9; // Random values between 0 and 9
|
||||
visited[i][j] = false; // Initialize visited array
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
7. Depth-First Search (DFS) with a Stack:
|
||||
a) Write a function that uses your TStack to perform a DFS on the grid, starting from your random cell.
|
||||
b) The goal is to find the first occurrence of the number '0'.
|
||||
c) In a short comment, explain how the LIFO behavior of the stack guides the search to explore as deeply as possible along one path before backtracking.
|
||||
*/
|
||||
|
||||
|
||||
// Helper function to check if a cell is within bounds and not visited
|
||||
static bool IsValid(int aRow, int aCol) {
|
||||
return aRow >= 0 && aRow < GRID_SIZE && aCol >= 0 && aCol < GRID_SIZE && !visited[aRow][aCol];
|
||||
}
|
||||
|
||||
// The stack's LIFO behavior allows the DFS to explore one path fully before backtracking, ensuring that all possible routes are checked in depth-first order.
|
||||
static bool DFS(int aStartRow, int aStartCol) {
|
||||
TStackArray stack(GRID_SIZE * GRID_SIZE);
|
||||
int cellPos = aStartRow * GRID_SIZE + aStartCol; // Encode 2D position as 1D
|
||||
stack.Push(cellPos);
|
||||
while (!stack.IsEmpty()) {
|
||||
cellPos = stack.Pop();
|
||||
int row = cellPos / GRID_SIZE;
|
||||
int col = cellPos % GRID_SIZE;
|
||||
if (grid[row][col] == 0) {
|
||||
std::cout << "Found 0 at (" << row << ", " << col << ")" << std::endl;
|
||||
return true;
|
||||
}
|
||||
std::cout << "Visiting (" << row << ", " << col << ") with value " << grid[row][col] << std::endl;
|
||||
visited[row][col] = true;
|
||||
int neighbors[4][2] = { {row - 1, col}, {row, col + 1}, {row + 1, col}, {row, col - 1} };
|
||||
for (int i = 0; i < 4; i++) {
|
||||
int newRow = neighbors[i][0];
|
||||
int newCol = neighbors[i][1];
|
||||
if (IsValid(newRow, newCol)) {
|
||||
cellPos = newRow * GRID_SIZE + newCol;
|
||||
stack.Push(cellPos);
|
||||
}
|
||||
}
|
||||
}
|
||||
std::cout << "0 not found in DFS" << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
// The queue's FIFO behavior ensures that the BFS explores all neighbors at the present depth prior to moving on to nodes at the next depth level, effectively searching layer by layer.
|
||||
static bool BFS(int aStartRow, int aStartCol) {
|
||||
int row = aStartRow, col = aStartCol;
|
||||
int pos = row * GRID_SIZE + col; // Encode 2D position as 1D
|
||||
TQueueArray queue(GRID_SIZE * GRID_SIZE);
|
||||
queue.Enqueue(pos);
|
||||
while (!queue.IsEmpty()) {
|
||||
pos = queue.Dequeue();
|
||||
row = pos / GRID_SIZE;
|
||||
col = pos % GRID_SIZE;
|
||||
if (grid[row][col] == 0) {
|
||||
std::cout << "Found 0 at (" << row << ", " << col << ")" << std::endl;
|
||||
return true;
|
||||
}
|
||||
std::cout << "Visiting (" << row << ", " << col << ") with value " << grid[row][col] << std::endl;
|
||||
visited[row][col] = true;
|
||||
int neighbors[4][2] = { {row - 1, col}, {row, col + 1},{row + 1, col},{row, col - 1} };
|
||||
for (int i = 0; i < 4; i++) {
|
||||
row = neighbors[i][0];
|
||||
col = neighbors[i][1];
|
||||
if (IsValid(row, col)) {
|
||||
pos = row * GRID_SIZE + col;
|
||||
queue.Enqueue(pos);
|
||||
}
|
||||
}
|
||||
}
|
||||
std::cout << "0 not found in BFS" << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
int main()
|
||||
{
|
||||
std::cout << "--- Submission 3: Stacks & Queues ---" << std::endl;
|
||||
std::string original = "Hello, World!";
|
||||
std::string reversed = ReverseString(original.c_str());
|
||||
std::cout << "Original String: " << original << std::endl;
|
||||
std::cout << "Reversed String: " << reversed << std::endl;
|
||||
// The stack is the perfect tool for string reversal because it operates on a Last-In, First-Out (LIFO) principle.
|
||||
// This means that the last character pushed onto the stack will be the first one to be popped off, effectively reversing the order of characters.
|
||||
std::cout << "----------------------------------------------------" << std::endl << std::endl;
|
||||
|
||||
std::cout << "Calculating Factorial of 5 using Stack:" << std::endl;
|
||||
std::cout << "5! = " << Factorial(5) << std::endl;
|
||||
std::cout << "----------------------------------------------------" << std::endl << std::endl;
|
||||
|
||||
std::cout << "Simulating Wait Line using Queue:" << std::endl;
|
||||
SimulateWaitLine();
|
||||
std::cout << "----------------------------------------------------" << std::endl << std::endl;
|
||||
|
||||
std::cout << "Initializing 100x100 Grid and Performing DFS to find '0':" << std::endl;
|
||||
InitializeGrid();
|
||||
int startRow = 3; //std::rand() % GRID_SIZE;
|
||||
int startCol = 2; //std::rand() % GRID_SIZE;
|
||||
std::cout << "Starting DFS from (" << startRow << ", " << startCol << ")" << std::endl;
|
||||
DFS(startRow, startCol);
|
||||
std::cout << std::endl << "Re-initializing visited array for BFS:" << std::endl;
|
||||
for (int i = 0; i < GRID_SIZE; i++) {
|
||||
for (int j = 0; j < GRID_SIZE; j++) {
|
||||
visited[i][j] = false; // Reset visited array
|
||||
}
|
||||
}
|
||||
std::cout << "Stating BFS from (" << startRow << ", " << startCol << ")" << std::endl;
|
||||
BFS(startRow, startCol); // This should find a different path to '0'
|
||||
std::cout << "----------------------------------------------------" << std::endl << std::endl;
|
||||
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
// Submission-01.h : Include file for standard system include files,
|
||||
// or project specific include files.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <iostream>
|
||||
|
||||
// TODO: Reference additional headers your program requires here.
|
||||
@@ -1,108 +0,0 @@
|
||||
#include "BankAccount.h"
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
#include <iomanip>
|
||||
#include <cstdlib> // For rand()
|
||||
#include <random> // For better random number generation
|
||||
#include <ctime>
|
||||
#include <cstring> // For memset
|
||||
#include <cmath> // For floor
|
||||
#include <chrono> // For time manipulation
|
||||
#include <locale> // For locale settings
|
||||
#include <codecvt> // For codecvt_utf8
|
||||
#include <stdexcept> // For std::invalid_argument
|
||||
#include <string>
|
||||
|
||||
|
||||
TBankAccount::TBankAccount(EBankAccountType accType, std::string firstName, std::string lastName)
|
||||
: accountType(accType), ownerFirstName(firstName), ownerLastName(lastName)
|
||||
{
|
||||
// Random genration of account number: XXXX.XX.XXXXX
|
||||
accountNumber = toString(rand() % 9000 + 1000) + "." + toString(rand() % 90 + 10) + "." + toString(rand() % 90000 + 10000);
|
||||
|
||||
balance = 0.0f;
|
||||
|
||||
//Random generation of creation timestamp, date is any date and time in 2024
|
||||
int month = rand() % 12 + 1;
|
||||
int day = rand() % 28 + 1; // To avoid complexity of different month lengths
|
||||
int hour = rand() % 24;
|
||||
int minute = rand() % 60;
|
||||
|
||||
// Calculate creation timestamp in seconds from 2024-01-01 00:00:00
|
||||
std:tm tm = {};
|
||||
tm.tm_year = 2024 - 1900; // Year since 1900
|
||||
tm.tm_mon = rand() % 12; // Month [0-11]
|
||||
tm.tm_mday = rand() % 28 + 1; // Day of the month [1-28] to avoid month length issues
|
||||
tm.tm_hour = rand() % 24; // Hour [0-23]
|
||||
tm.tm_min = rand() % 60; // Minute [0-59]
|
||||
tm.tm_sec = 0; // Second [0-59]
|
||||
creationTimestamp = _mkgmtime(&tm); // Use _mkgmtime for UTC
|
||||
|
||||
if (accType == Checking || accType == Saving || accType == Pension)
|
||||
balance = static_cast<double>(rand() % 1001); // 0 to 1000
|
||||
else if (accType == Loan)
|
||||
balance = static_cast<double>(-(rand() % 25001 + 25000)); // -50000 to -25000
|
||||
else if (accType == Credit)
|
||||
balance = static_cast<double>(-(rand() % 1001)); // -1000 to 0
|
||||
}
|
||||
|
||||
TBankAccount::~TBankAccount()
|
||||
{
|
||||
// Destructor logic if needed
|
||||
}
|
||||
|
||||
std::string TBankAccount::getAccountNumber() const {
|
||||
return accountNumber;
|
||||
}
|
||||
|
||||
EBankAccountType TBankAccount::getAccountType() const {
|
||||
return accountType;
|
||||
}
|
||||
|
||||
time_t TBankAccount::getCreationTimestamp() const {
|
||||
return creationTimestamp;
|
||||
}
|
||||
double TBankAccount::getBalance() const {
|
||||
return balance;
|
||||
}
|
||||
void TBankAccount::deposit(double aAmount) {
|
||||
if (aAmount > 0) balance += aAmount;
|
||||
}
|
||||
|
||||
void TBankAccount::withdraw(double aAmount) {
|
||||
if (aAmount > 0 && aAmount <= balance) balance -= aAmount;
|
||||
}
|
||||
|
||||
std::string TBankAccount::getAccountTypeString() const
|
||||
{
|
||||
switch (accountType)
|
||||
{
|
||||
case Checking: return "Checking";
|
||||
case Saving: return "Saving";
|
||||
case Credit: return "Credit";
|
||||
case Pension: return "Pension";
|
||||
case Loan: return "Loan";
|
||||
default: return "Unknown";
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
std::string TBankAccount::getCreationTimeString() const
|
||||
{
|
||||
char buffer[26];
|
||||
ctime_s(buffer, sizeof(buffer), &creationTimestamp);
|
||||
std::string timeString(buffer);
|
||||
if (!timeString.empty() && timeString.back() == '\n') {
|
||||
timeString.pop_back(); // Remove the trailing newline character
|
||||
}
|
||||
return timeString;
|
||||
}
|
||||
|
||||
void TBankAccount::printAccountInfo() const
|
||||
{
|
||||
std::cout << "Account Number: " << accountNumber << ", Type: " << getAccountTypeString()
|
||||
<< ", Owner: " << ownerFirstName << " " << ownerLastName
|
||||
<< ", Balance: " << balance
|
||||
<< ", Created: " << getCreationTimeString()
|
||||
<< std::endl;
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
#pragma once
|
||||
#ifndef BANKACCOUNT_H
|
||||
#define BANKACCOUNT_H
|
||||
|
||||
#include <string> // For std::string
|
||||
#include <ctime> // For time_t
|
||||
#include <cstdlib> // For rand()
|
||||
#include <iomanip> // For std::setfill and std::setw
|
||||
#include <sstream> // For std::ostringstream
|
||||
#include <iostream> // For std::cout
|
||||
|
||||
|
||||
// Helper function to convert value to string
|
||||
template <typename T>
|
||||
std::string toString(T value)
|
||||
{
|
||||
std::ostringstream oss;
|
||||
oss << value;
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
|
||||
enum EBankAccountType { Checking, Saving, Credit, Pension, Loan };
|
||||
|
||||
class TBankAccount {
|
||||
|
||||
private:
|
||||
std::string accountNumber;
|
||||
EBankAccountType accountType;
|
||||
time_t creationTimestamp;
|
||||
double balance;
|
||||
|
||||
public:
|
||||
std::string ownerFirstName;
|
||||
std::string ownerLastName;
|
||||
|
||||
//TBankAccount() {} // Don't use default constructor
|
||||
TBankAccount(EBankAccountType, std::string, std::string);
|
||||
~TBankAccount();
|
||||
|
||||
std::string getAccountNumber() const;
|
||||
std::string getCreationTimeString() const;
|
||||
time_t getCreationTimestamp() const;
|
||||
double getBalance() const;
|
||||
void deposit(double);
|
||||
void withdraw(double);
|
||||
EBankAccountType getAccountType() const;
|
||||
std::string getAccountTypeString() const;
|
||||
void printAccountInfo() const;
|
||||
};
|
||||
|
||||
#endif // BANKACCOUNT_H
|
||||
@@ -1,130 +0,0 @@
|
||||
#include "BankAccountList.h"
|
||||
|
||||
TLinkedList::TLinkedList(bool aOwnsData) : head(nullptr), ownsData(aOwnsData), size(0) {
|
||||
head = new TLinkedListNode(nullptr); // Dummy head node
|
||||
}
|
||||
|
||||
TLinkedList::~TLinkedList()
|
||||
{
|
||||
while (head->next != nullptr)
|
||||
{
|
||||
TLinkedListNode* temp = head->next;
|
||||
head->next = temp->next;
|
||||
if (ownsData) delete temp->data; // Delete the TBankAccount object
|
||||
delete temp; // Delete the node
|
||||
}
|
||||
delete head;
|
||||
}
|
||||
|
||||
int TLinkedList::getSize() const { return size; }
|
||||
|
||||
void TLinkedList::Add(TBankAccount* aData)
|
||||
{
|
||||
TLinkedListNode* newNode = new TLinkedListNode(aData);
|
||||
newNode->next = head->next;
|
||||
head->next = newNode;
|
||||
size++;
|
||||
}
|
||||
|
||||
TBankAccount* TLinkedList::Find(FCompareAccount aCompareFunc, void* aSearchKey)
|
||||
{
|
||||
TLinkedListNode* current = head->next;
|
||||
while (current != nullptr)
|
||||
{
|
||||
if (aCompareFunc(current->data, aSearchKey))
|
||||
{
|
||||
return current->data; // Found
|
||||
}
|
||||
current = current->next;
|
||||
}
|
||||
return nullptr; // Not found
|
||||
}
|
||||
|
||||
TLinkedList* TLinkedList::Every(FCompareAccount aCompareFunc, void* aSearchKey)
|
||||
{
|
||||
TLinkedList* resultList = new TLinkedList(false); // New list does not own data
|
||||
TLinkedListNode* current = head->next;
|
||||
while (current != nullptr)
|
||||
{
|
||||
if (aCompareFunc(current->data, aSearchKey))
|
||||
{
|
||||
resultList->Add(current->data); // Add to result list
|
||||
}
|
||||
current = current->next;
|
||||
}
|
||||
return resultList; // Return the new list
|
||||
}
|
||||
|
||||
// Loop through all accounts, if aEveryFunc returns false for any, return that account
|
||||
TBankAccount* TLinkedList::Every(FEveryAccount aEveryFunc) {
|
||||
TLinkedListNode* current = head->next;
|
||||
int index = 0;
|
||||
while (current != nullptr)
|
||||
{
|
||||
if (!aEveryFunc(current->data, index++))
|
||||
{
|
||||
return current->data; // Return the first account that fails the test
|
||||
}
|
||||
current = current->next;
|
||||
}
|
||||
return nullptr; // All accounts passed the test
|
||||
}
|
||||
|
||||
TBankAccount** TLinkedList::ToArray()
|
||||
{
|
||||
if (size == 0) return nullptr;
|
||||
TBankAccount** array = new TBankAccount * [size];
|
||||
TLinkedListNode* current = head->next;
|
||||
int index = 0;
|
||||
while (current != nullptr && index < size) // Ensure index < size
|
||||
{
|
||||
array[index++] = current->data;
|
||||
current = current->next;
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
void TLinkedList::forEach(FForEachAccount aFunc)
|
||||
{
|
||||
TLinkedListNode* current = head->next;
|
||||
int index = 0;
|
||||
while (current != nullptr)
|
||||
{
|
||||
aFunc(current->data, index++);
|
||||
current = current->next;
|
||||
}
|
||||
}
|
||||
|
||||
TLinkedListNode* TLinkedList::getHead() const { return head; }
|
||||
|
||||
void TLinkedList::Append(TBankAccount* account)
|
||||
{
|
||||
TLinkedListNode* newNode = new TLinkedListNode(account);
|
||||
TLinkedListNode* current = head;
|
||||
while (current->next != nullptr)
|
||||
{
|
||||
current = current->next;
|
||||
}
|
||||
current->next = newNode;
|
||||
size++;
|
||||
}
|
||||
|
||||
void TLinkedList::Remove(TBankAccount* account)
|
||||
{
|
||||
TLinkedListNode* current = head;
|
||||
while (current->next != nullptr)
|
||||
{
|
||||
if (current->next->data == account)
|
||||
{
|
||||
TLinkedListNode* temp = current->next;
|
||||
current->next = temp->next;
|
||||
if (ownsData) delete temp->data; // Delete the TBankAccount object
|
||||
delete temp; // Delete the node
|
||||
size--;
|
||||
return; // Exit after removing
|
||||
}
|
||||
current = current->next;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
#pragma once
|
||||
#ifndef BANKACCOUNTLIST_H
|
||||
#define BANKACCOUNTLIST_H
|
||||
#include "BankAccount.h"
|
||||
#include <string>
|
||||
#include <functional>
|
||||
|
||||
typedef bool (*FCompareAccount)(TBankAccount* account, void* searchKey);
|
||||
typedef void (*FForEachAccount)(TBankAccount* account, int index);
|
||||
typedef bool (*FEveryAccount)(TBankAccount*, int);
|
||||
|
||||
// Node class for linked list
|
||||
class TLinkedListNode
|
||||
{
|
||||
public:
|
||||
TBankAccount* data;
|
||||
TLinkedListNode* next;
|
||||
TLinkedListNode(TBankAccount* aData) : data(aData), next(nullptr) {}
|
||||
~TLinkedListNode()
|
||||
{
|
||||
// Destructor logic if needed
|
||||
}
|
||||
};
|
||||
|
||||
// Use dummy head node for simplicity
|
||||
class TLinkedList
|
||||
{
|
||||
private:
|
||||
TLinkedListNode* head;
|
||||
bool ownsData;
|
||||
int size;
|
||||
public:
|
||||
TLinkedList(bool);
|
||||
~TLinkedList();
|
||||
int getSize() const;
|
||||
TLinkedListNode* getHead() const;
|
||||
|
||||
void Add(TBankAccount*);
|
||||
|
||||
TBankAccount* Find(FCompareAccount, void*);
|
||||
|
||||
TLinkedList* Every(FCompareAccount, void*);
|
||||
TBankAccount* Every(FEveryAccount aEveryFunc);
|
||||
TBankAccount** ToArray();
|
||||
void forEach(FForEachAccount);
|
||||
|
||||
void Append(TBankAccount* account);
|
||||
void Remove(TBankAccount* account);
|
||||
};
|
||||
|
||||
#endif// BANKACCOUNTLIST_H
|
||||
@@ -1,25 +0,0 @@
|
||||
# CMakeList.txt : CMake project for Submission-01, include source and define
|
||||
# project specific logic here.
|
||||
#
|
||||
|
||||
# Add source to this project's executable.
|
||||
add_executable (Submission-04 "main.cpp" "main.h" "BankAccount.h" "ReadNames.cpp" "ReadNames.h" "BankAccount.cpp" "BankAccount.h" "BankAccountList.cpp" "BankAccountList.h")
|
||||
target_link_libraries(Submission-04 PRIVATE LibExample)
|
||||
|
||||
# Add source files to a Submission04Lib library
|
||||
add_library(Submission04Lib
|
||||
BankAccount.cpp
|
||||
BankAccount.h
|
||||
ReadNames.cpp
|
||||
ReadNames.h
|
||||
BankAccountList.cpp
|
||||
BankAccountList.h
|
||||
)
|
||||
|
||||
target_include_directories(Submission04Lib PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
|
||||
if (CMAKE_VERSION VERSION_GREATER 3.20)
|
||||
set_property(TARGET Submission-03 PROPERTY CXX_STANDARD 20)
|
||||
endif()
|
||||
|
||||
# TODO: Add tests and install targets if needed.
|
||||
@@ -1,31 +0,0 @@
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include "ReadNames.h"
|
||||
|
||||
void readNamesFromFile(const std::string& aFilename, FNameRead aOnNameRead)
|
||||
{
|
||||
if (aFilename.empty()) return;
|
||||
std::ifstream file(aFilename);
|
||||
if (!file.is_open())
|
||||
{
|
||||
std::cerr << "Error opening file: " << aFilename << std::endl;
|
||||
return;
|
||||
}
|
||||
std::string line;
|
||||
while (std::getline(file, line))
|
||||
{
|
||||
std::istringstream iss(line);
|
||||
std::string firstName, lastName;
|
||||
if (iss >> firstName >> lastName)
|
||||
{
|
||||
if (aOnNameRead) // If the callback is set, call it
|
||||
{
|
||||
//If the function returns false, stop reading further
|
||||
if (!aOnNameRead(firstName, lastName)) break;
|
||||
}
|
||||
}
|
||||
}
|
||||
file.close();
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
#pragma once
|
||||
#ifndef READNAMES_H
|
||||
#define SHARED_LIB_H
|
||||
#include <string>
|
||||
#include <functional>
|
||||
|
||||
/// <summary>
|
||||
/// Use this delegate type to define a callback function for processing names read from a file.
|
||||
/// </summary>
|
||||
/// <delegate>FNameRead</delegate>
|
||||
/// <description>A function pointer type for a callback that processes names read from a file.</description>
|
||||
/// <param name="firstName">The first name read from the file.</param>
|
||||
/// <param name="lastName">The last name read from the file.</param>
|
||||
/// <returns>Returns true to continue reading names, or false to stop.</returns>
|
||||
typedef bool (*FNameRead)(const std::string& firstName, const std::string& lastName);
|
||||
|
||||
/// <summary>
|
||||
/// Use this function to read names from a specified file and process them using a callback function.
|
||||
/// </summary>
|
||||
/// <function>readNamesFromFile</function>
|
||||
/// <description>Reads names from a specified file and invokes a callback for each name read.</description>
|
||||
/// <param name="aFilename">The path to the file containing names.</param>
|
||||
/// <param name="aOnNameRead">A callback function that is called for each name read. It takes two parameters: firstName and lastName. If the callback returns false, the reading process stops.</param>
|
||||
/// <param name="firstName">The first name read from the file.</param>
|
||||
/// <param name="lastName">The last name read from the file.</param>
|
||||
/// <returns>None.</returns>
|
||||
void readNamesFromFile(const std::string& aFilename, FNameRead aOnNameRead);
|
||||
|
||||
|
||||
#endif // READNAMES_H
|
||||
@@ -1,180 +0,0 @@
|
||||
// Submission-01.cpp : Defines the entry point for the application.
|
||||
//
|
||||
|
||||
#include "main.h"
|
||||
#include "ReadNames.h" // For reading names from file
|
||||
#include "BankAccount.h" // For TBankAccount and EBankAccountType
|
||||
#include "BankAccountList.h" // For TLinkedList
|
||||
#include <string> // For std::getline and std::string
|
||||
#include <iostream> // For std::cout
|
||||
#include <sstream> // For std::istringstream
|
||||
|
||||
|
||||
|
||||
// For statistics
|
||||
typedef struct _TSummary {
|
||||
long comparisonCount = 0;
|
||||
double timeTaken = 0.0;
|
||||
}TSummary;
|
||||
static TSummary statistics;
|
||||
|
||||
|
||||
|
||||
static EBankAccountType getRandomAccountType()
|
||||
{
|
||||
return static_cast<EBankAccountType>(rand() % 5); // Randomly returns one of the 5 account types
|
||||
}
|
||||
|
||||
TLinkedList* bankAccounts = new TLinkedList(true); // List owns the TBankAccount objects
|
||||
TBankAccount** bankAccountArray = nullptr;
|
||||
|
||||
|
||||
static bool OnNameRead(const std::string& firstName, const std::string& lastName)
|
||||
{
|
||||
//For each name read, create from 5 to 10 random bank accounts
|
||||
int accountCount = rand() % 6 + 5; // Random number between 5 and 10
|
||||
for (int i = 0; i < accountCount; i++)
|
||||
{
|
||||
EBankAccountType accType = getRandomAccountType();
|
||||
TBankAccount* newAccount = new TBankAccount(accType, firstName, lastName);
|
||||
bankAccounts->Add(newAccount);
|
||||
}
|
||||
return true; //bankAccounts->getSize() < 100; // For demo purposes
|
||||
}
|
||||
|
||||
static void resetStatistics()
|
||||
{
|
||||
statistics.comparisonCount = 0;
|
||||
statistics.timeTaken = (static_cast<double>(clock())) / CLOCKS_PER_SEC;
|
||||
}
|
||||
|
||||
static void printStastics() {
|
||||
statistics.timeTaken = (static_cast<double>(clock())) / CLOCKS_PER_SEC - statistics.timeTaken;
|
||||
std::cout << "Comparisons: " << statistics.comparisonCount << ", Time taken: " << statistics.timeTaken << " seconds." << std::endl;
|
||||
}
|
||||
|
||||
/*
|
||||
Part 3: Standalone Search Functions (The External Analyst)
|
||||
To simulate working with data from different perspectives, you will also implement search functions that are not part of the list class. These functions will operate on a simple array of pointers.
|
||||
*/
|
||||
|
||||
static TBankAccount* FindAccountByNumber(TBankAccount** accountArray, int arraySize, const std::string& accountNumber) {
|
||||
if (accountArray == nullptr || arraySize <= 0) return nullptr;
|
||||
for (int i = 0; i < arraySize; i++) {
|
||||
statistics.comparisonCount++;
|
||||
if (accountArray[i]->getAccountNumber() == accountNumber) {
|
||||
return accountArray[i]; // Found
|
||||
}
|
||||
}
|
||||
return nullptr; // Not found
|
||||
}
|
||||
|
||||
static void PrintEveryAccountInDateRange(TBankAccount** accountArray, int arraySize, time_t from, time_t to) {
|
||||
if (accountArray == nullptr || arraySize <= 0) return;
|
||||
std::cout << "------------------------------" << std::endl;
|
||||
resetStatistics();
|
||||
int foundCount = 0;
|
||||
for (int i = 0; i < arraySize; i++) {
|
||||
statistics.comparisonCount++;
|
||||
time_t ts = accountArray[i]->getCreationTimestamp();
|
||||
if (ts >= from && ts < to) {
|
||||
std::cout << i + 1 << ". ";
|
||||
accountArray[i]->printAccountInfo();
|
||||
foundCount++;
|
||||
}
|
||||
}
|
||||
printStastics();
|
||||
std::cout << "Total accounts found in date range: " << foundCount << std::endl;
|
||||
}
|
||||
|
||||
|
||||
int main()
|
||||
{
|
||||
std::cout << "--- Submission 4: Sosrt & Search ---" << std::endl;
|
||||
|
||||
// Test TBankAccount
|
||||
//Gen random account type
|
||||
//Change this name for you own names file
|
||||
std::string namesFile = "F:\\IKT203\\VisualStudio\\DATA\\Random_Name.txt";
|
||||
std::cout << "Reading names from file: " << namesFile << std::endl;
|
||||
readNamesFromFile(namesFile, OnNameRead);
|
||||
std::cout << "Total Bank Accounts Created: " << bankAccounts->getSize() << std::endl;
|
||||
std::cout << "Converting linked list to array..." << std::endl;
|
||||
bankAccountArray = bankAccounts->ToArray();
|
||||
std::cout << "Array created with " << bankAccounts->getSize() << " accounts." << std::endl;
|
||||
|
||||
|
||||
resetStatistics();
|
||||
int getRandomIndex = rand() % bankAccounts->getSize();
|
||||
TBankAccount* foundAccount = FindAccountByNumber(bankAccountArray, bankAccounts->getSize(), bankAccountArray[getRandomIndex]->getAccountNumber());
|
||||
if (foundAccount)
|
||||
{
|
||||
std::cout << "Found Account: " << std::endl;
|
||||
foundAccount->printAccountInfo();
|
||||
}
|
||||
else
|
||||
{
|
||||
std::cout << "Account not found." << std::endl;
|
||||
}
|
||||
printStastics();
|
||||
|
||||
resetStatistics();
|
||||
foundAccount = FindAccountByNumber(bankAccountArray, bankAccounts->getSize(), "1234.56.78901");
|
||||
if (foundAccount)
|
||||
{
|
||||
std::cout << "Found Account: " << std::endl;
|
||||
foundAccount->printAccountInfo();
|
||||
}
|
||||
else
|
||||
{
|
||||
std::cout << "Account not found." << std::endl;
|
||||
}
|
||||
printStastics();
|
||||
|
||||
// Find All (Integrated): Use your Every() method to find all accounts created in June 2024 and print their details.
|
||||
resetStatistics();
|
||||
struct June2024Key {
|
||||
time_t start;
|
||||
time_t end;
|
||||
};
|
||||
June2024Key juneKey{};
|
||||
std::tm fromToTm = {};
|
||||
fromToTm.tm_year = 2024 - 1900; // Year since 1900
|
||||
fromToTm.tm_mon = 5; // June (0-based)
|
||||
fromToTm.tm_mday = 1; // 1st
|
||||
fromToTm.tm_hour = 0;
|
||||
fromToTm.tm_min = 0;
|
||||
fromToTm.tm_sec = 0;
|
||||
juneKey.start = _mkgmtime(&fromToTm); // Use _mkgmtime for UTC
|
||||
fromToTm.tm_mday = 30; // 30th
|
||||
fromToTm.tm_hour = 23;
|
||||
fromToTm.tm_min = 59;
|
||||
fromToTm.tm_sec = 59;
|
||||
juneKey.end = _mkgmtime(&fromToTm); // Use _mkgmtime for UTC
|
||||
|
||||
TLinkedList* juneAccounts = bankAccounts->Every(
|
||||
[](TBankAccount* account, void* searchKey) -> bool {
|
||||
June2024Key* key = static_cast<June2024Key*>(searchKey);
|
||||
time_t ts = account->getCreationTimestamp();
|
||||
return ts >= key->start && ts < key->end;
|
||||
}, &juneKey);
|
||||
|
||||
std::cout << "Accounts created in June 2024: " << juneAccounts->getSize() << std::endl;
|
||||
printStastics();
|
||||
|
||||
juneAccounts->forEach(
|
||||
[](TBankAccount* aAccount, int aIndex) {
|
||||
std::cout << aIndex + 1 << ". ";
|
||||
aAccount->printAccountInfo();
|
||||
});
|
||||
|
||||
PrintEveryAccountInDateRange(bankAccountArray, bankAccounts->getSize(), juneKey.start, juneKey.end);
|
||||
|
||||
|
||||
// Cleanup
|
||||
// First delete the array, then the linked list
|
||||
delete[] bankAccountArray;
|
||||
delete bankAccounts;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
// Submission-01.h : Include file for standard system include files,
|
||||
// or project specific include files.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <iostream>
|
||||
|
||||
// TODO: Reference additional headers your program requires here.
|
||||
@@ -1,13 +0,0 @@
|
||||
# CMakeList.txt : CMake project for Submission-01, include source and define
|
||||
# project specific logic here.
|
||||
#
|
||||
|
||||
# Add source to this project's executable.
|
||||
add_executable (Submission-05 "main.cpp" "main.h")
|
||||
target_link_libraries(Submission-05 PRIVATE Submission04Lib LibExample)
|
||||
|
||||
if (CMAKE_VERSION VERSION_GREATER 3.20)
|
||||
set_property(TARGET Submission-05 PROPERTY CXX_STANDARD 20)
|
||||
endif()
|
||||
|
||||
# TODO: Add tests and install targets if needed.
|
||||
@@ -1,828 +0,0 @@
|
||||
// Submission-01.cpp : Defines the entry point for the application.
|
||||
//
|
||||
|
||||
#include "ReadNames.h" // For reading names from file
|
||||
#include "BankAccount.h" // For TBankAccount and EBankAccountType
|
||||
#include "BankAccountList.h" // For TLinkedList
|
||||
#include <string> // For std::getline and std::string
|
||||
#include <iostream> // For std::cout
|
||||
#include <sstream> // For std::istringstream
|
||||
|
||||
|
||||
|
||||
// For statistics
|
||||
typedef struct _TSummary {
|
||||
long long comparisonCount = 0;
|
||||
long long swaps = 0;
|
||||
double timeTaken = 0.0;
|
||||
}TSummary;
|
||||
static TSummary statistics;
|
||||
|
||||
|
||||
static void resetStatistics()
|
||||
{
|
||||
statistics.comparisonCount = 0;
|
||||
statistics.swaps = 0;
|
||||
statistics.timeTaken = (static_cast<double>(clock())) / CLOCKS_PER_SEC;
|
||||
}
|
||||
|
||||
static void printStastics() {
|
||||
statistics.timeTaken = (static_cast<double>(clock())) / CLOCKS_PER_SEC - statistics.timeTaken;
|
||||
std::cout << "Comparisons: " << statistics.comparisonCount << ", Swaps: " << statistics.swaps << ", Time taken : " << statistics.timeTaken << " seconds." << std::endl;
|
||||
}
|
||||
|
||||
|
||||
static EBankAccountType getRandomAccountType()
|
||||
{
|
||||
return static_cast<EBankAccountType>(rand() % 5); // Randomly returns one of the 5 account types
|
||||
}
|
||||
|
||||
TLinkedList* bankAccounts = new TLinkedList(true); // List owns the TBankAccount objects
|
||||
TBankAccount** bankAccountArray = nullptr;
|
||||
|
||||
|
||||
static bool OnNameRead(const std::string& firstName, const std::string& lastName)
|
||||
{
|
||||
//For each name read, create from 5 to 10 random bank accounts
|
||||
int accountCount = rand() % 6 + 5; // Random number between 5 and 10
|
||||
for (int i = 0; i < accountCount; i++)
|
||||
{
|
||||
EBankAccountType accType = getRandomAccountType();
|
||||
TBankAccount* newAccount = new TBankAccount(accType, firstName, lastName);
|
||||
bankAccounts->Add(newAccount);
|
||||
}
|
||||
return bankAccounts->getSize() < 2500; // For demo purposes
|
||||
}
|
||||
|
||||
/*
|
||||
Part 1: The Sorting Toolkit
|
||||
Before we can sort, we need the right tools. In this part, you'll set up a flexible, powerful sorting "engine" that can handle any sorting criteria we give it.
|
||||
|
||||
1. The FCompareAccounts Callback:
|
||||
a) Create a typedef for a function pointer named FCompareAccounts.
|
||||
b) The signature must be: int (*FCompareAccounts)(TBankAccount* a, TBankAccount* b);.
|
||||
c) This function should return a negative value if a comes before b, zero if they are equal, and a positive value if a comes after b.
|
||||
2. The OperationSummary Struct:
|
||||
a) Create a struct named OperationSummary to track performance metrics: long long comparisons, long long swaps, and double timeSpentMs.
|
||||
3. The TSort Class:
|
||||
a) Create a class called TSort. This will be your dedicated sorting engine.
|
||||
b) The constructor should take pointers to the original data sources (the list and the array).
|
||||
c) The sorting methods should create and return a new, sorted array or list, not modify the original.
|
||||
*/
|
||||
|
||||
/*
|
||||
Part 2: The Simple Sorts (O(n²)) - Foundational, but Slow
|
||||
These algorithms are your first step. They are conceptually simpler but do not perform well on large datasets. Implementing them is essential for understanding the fundamentals.
|
||||
|
||||
4. Selection Sort:
|
||||
a) The Challenge: You must implement this algorithm twice in your TSort class:
|
||||
1. A version that sorts the pointer array.
|
||||
2. A version that sorts the linked list.
|
||||
b) Pay close attention to the pointer manipulation required for the linked list version—it's a fantastic challenge!
|
||||
5. Bubble Sort:
|
||||
a) Implement a method in TSort that performs a Bubble Sort on the pointer array.
|
||||
|
||||
|
||||
Part 3: The Advanced Sorts (O(n log n)) - Divide and Conquer
|
||||
Now for the heavy hitters. These recursive, "Divide and Conquer" algorithms are far more efficient and are staples of modern software engineering.
|
||||
|
||||
6. Quick Sort (on the Array):
|
||||
a) Implement Quick Sort to sort the pointer array.
|
||||
b) Your implementation must use the public/private recursion pattern. A public QuickSort() method calls a private QuickSortRecursive(...).
|
||||
c) The heart of this algorithm is the Partition() helper function. Getting this right is the key to success!
|
||||
|
||||
7. Merge Sort (on the Linked List):
|
||||
a) Implement Merge Sort to sort the linked list. This algorithm is a natural fit for list structures.
|
||||
b) This implementation must also use the public/private recursion pattern.
|
||||
c) Hint: For splitting the linked list, research the "fast and slow pointer" technique.
|
||||
|
||||
Part 4: The Great Sort-Off
|
||||
It's time for a performance battle! You will use your TSort engine to sort the same large dataset with all your implemented algorithms and analyze the results.
|
||||
|
||||
8. Callback Implementations:
|
||||
a) Write at least two different FCompareAccounts callback functions: one to sort by last name, and one to sort by balance.
|
||||
|
||||
9. The Performance Battle:
|
||||
a) Using your dataset of 5,000+ accounts, run all four of your sorting algorithms using the same callback function for a fair comparison.
|
||||
b) For each run, capture the OperationSummary (comparisons, swaps, time).
|
||||
|
||||
10. Analysis in Your Report:
|
||||
a) Present your performance data in a clear table.
|
||||
b) Write a paragraph answering: How do the results illustrate the difference between O(n²) and O(n log n) complexity? Why was Selection Sort harder on a list versus an array?
|
||||
|
||||
Part 5: The Payoff - Integrated Binary Search
|
||||
|
||||
11. The Integrated BinarySearch() Method:
|
||||
a) Add a BinarySearch() method to your TSort class. This method will operate on a sorted array.
|
||||
b) The TSort class must now manage an internal state (e.g., a private pointer to a sorted array and a boolean flag). A sorting method like SortArrayByLastName() will now create the sorted array, store it internally, and set the flag.
|
||||
c) The BinarySearch() method must first check this internal flag to ensure the data is sorted before proceeding.
|
||||
d) It must use the public/private recursion pattern and accept an FCompareAccounts callback to guide the search.
|
||||
|
||||
12. Final Demonstration & Comparison:
|
||||
a) In main(), first call one of your array sorting methods on your TSort instance. Then, use its new BinarySearch() method to find an item.
|
||||
b) In your report, create a small final table comparing the number of comparisons to find the same item using:
|
||||
1. The Linear Search from Submission 4.
|
||||
2. The Binary Search from this submission.
|
||||
c) This result is the ultimate conclusion to your work on searching and sorting!
|
||||
*/
|
||||
|
||||
|
||||
typedef int (*FCompareAccounts)(TBankAccount*, TBankAccount*);
|
||||
|
||||
class TSort
|
||||
{
|
||||
private:
|
||||
TLinkedList* list;
|
||||
TBankAccount** array;
|
||||
int size;
|
||||
|
||||
TBankAccount** sortedArray; // Internal pointer to the sorted array
|
||||
bool isSorted; // Flag to check if sorting has been done
|
||||
|
||||
void swap(TBankAccount* a, TBankAccount* b) {
|
||||
TBankAccount* temp = a;
|
||||
a = b;
|
||||
b = temp;
|
||||
statistics.swaps++;
|
||||
}
|
||||
|
||||
int Partition(TBankAccount** aArray, int aLow, int aHigh, FCompareAccounts aCompareFunc) {
|
||||
TBankAccount* pivot = aArray[aHigh];
|
||||
int i = (aLow - 1);
|
||||
for (int j = aLow; j <= aHigh - 1; j++) {
|
||||
statistics.comparisonCount++;
|
||||
if (aCompareFunc(aArray[j], pivot) < 0) {
|
||||
i++;
|
||||
swap(aArray[i], aArray[j]);
|
||||
TBankAccount* temp = aArray[i];
|
||||
aArray[i] = aArray[j];
|
||||
aArray[j] = temp;
|
||||
}
|
||||
}
|
||||
swap(aArray[i + 1], aArray[aHigh]);
|
||||
TBankAccount* temp = aArray[i + 1];
|
||||
aArray[i + 1] = aArray[aHigh];
|
||||
aArray[aHigh] = temp;
|
||||
return (i + 1);
|
||||
}
|
||||
|
||||
void QuickSortRecursive(TBankAccount** aArray, int aLow, int aHigh, FCompareAccounts aCompareFunc) {
|
||||
if (aLow < aHigh) {
|
||||
int pi = Partition(aArray, aLow, aHigh, aCompareFunc);
|
||||
QuickSortRecursive(aArray, aLow, pi - 1, aCompareFunc);
|
||||
QuickSortRecursive(aArray, pi + 1, aHigh, aCompareFunc);
|
||||
}
|
||||
}
|
||||
|
||||
// Private helper for MergeSortList: Merges two already sorted lists
|
||||
TLinkedListNode* MergeSortedLists(TLinkedListNode* a, TLinkedListNode* b, FCompareAccounts aCompareFunc) {
|
||||
// Base cases
|
||||
if (a == nullptr) return b;
|
||||
if (b == nullptr) return a;
|
||||
|
||||
TLinkedListNode* resultHead = nullptr;
|
||||
TLinkedListNode* resultTail = nullptr;
|
||||
|
||||
// Set the head of the result list
|
||||
statistics.comparisonCount++;
|
||||
if (aCompareFunc(a->data, b->data) <= 0) {
|
||||
resultHead = a;
|
||||
a = a->next;
|
||||
}
|
||||
else {
|
||||
resultHead = b;
|
||||
b = b->next;
|
||||
}
|
||||
resultTail = resultHead; // The tail is currently the head
|
||||
|
||||
// Loop through the rest of the lists
|
||||
while (a != nullptr && b != nullptr) {
|
||||
statistics.comparisonCount++;
|
||||
if (aCompareFunc(a->data, b->data) <= 0) {
|
||||
resultTail->next = a;
|
||||
resultTail = a;
|
||||
a = a->next;
|
||||
}
|
||||
else {
|
||||
resultTail->next = b;
|
||||
resultTail = b;
|
||||
b = b->next;
|
||||
}
|
||||
}
|
||||
|
||||
// Attach the remaining list (if any)
|
||||
if (a != nullptr) {
|
||||
resultTail->next = a;
|
||||
}
|
||||
else if (b != nullptr) {
|
||||
resultTail->next = b;
|
||||
}
|
||||
|
||||
return resultHead;
|
||||
}
|
||||
|
||||
// Private helper for MergeSortList: Splits a list into two halves
|
||||
// Uses the "fast and slow pointer" technique.
|
||||
// 'source' is the head of the list to split.
|
||||
// Returns the head of the second half. 'source' is modified to be the first half.
|
||||
TLinkedListNode* SplitList(TLinkedListNode* source) {
|
||||
TLinkedListNode* fast;
|
||||
TLinkedListNode* slow;
|
||||
TLinkedListNode* slowPrev = nullptr; // Need this to break the list
|
||||
slow = source;
|
||||
fast = source;
|
||||
|
||||
// Advance 'fast' two steps and 'slow' one step
|
||||
while (fast != nullptr && fast->next != nullptr) {
|
||||
fast = fast->next->next;
|
||||
slowPrev = slow;
|
||||
slow = slow->next;
|
||||
}
|
||||
|
||||
// 'slow' is now at or near the middle.
|
||||
// Split the list in two by setting the end of the first list to null.
|
||||
if (slowPrev != nullptr) {
|
||||
slowPrev->next = nullptr;
|
||||
}
|
||||
|
||||
// 'slow' is the head of the second list
|
||||
return slow;
|
||||
}
|
||||
|
||||
void MergeSortRecursive(TLinkedListNode** aHeadRef, FCompareAccounts aCompareFunc) {
|
||||
TLinkedListNode* head = *aHeadRef;
|
||||
TLinkedListNode* left;
|
||||
TLinkedListNode* right;
|
||||
|
||||
// Base case: 0 or 1 element list is already sorted
|
||||
if (head == nullptr || head->next == nullptr) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 1. Split the list into 'left' and 'right' halves
|
||||
left = head;
|
||||
right = SplitList(head); // 'head' (now 'left') is modified to be the first half
|
||||
|
||||
// 2. Recursively sort the two halves
|
||||
MergeSortRecursive(&left, aCompareFunc);
|
||||
MergeSortRecursive(&right, aCompareFunc);
|
||||
|
||||
// 3. Merge the two sorted halves back together
|
||||
// Update the head pointer to point to the new sorted list
|
||||
*aHeadRef = MergeSortedLists(left, right, aCompareFunc);
|
||||
}
|
||||
|
||||
TBankAccount* BinarySearchRecursive(TBankAccount* aKey, FCompareAccounts aCompareFunc, int aLow, int aHigh)
|
||||
{
|
||||
// Base case: Not found
|
||||
if (aLow > aHigh) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
int mid = aLow + (aHigh - aLow) / 2;
|
||||
|
||||
// Use the callback to compare the array element with the key
|
||||
// We assume the callback knows what field to compare (e.g., lastName)
|
||||
statistics.comparisonCount++; // Track comparisons
|
||||
int comparisonResult = aCompareFunc(sortedArray[mid], aKey);
|
||||
|
||||
if (comparisonResult == 0) {
|
||||
return sortedArray[mid]; // Found
|
||||
}
|
||||
else if (comparisonResult < 0) {
|
||||
// sortedArray[mid] is *before* aKey, so search the right half
|
||||
return BinarySearchRecursive(aKey, aCompareFunc, mid + 1, aHigh);
|
||||
}
|
||||
else {
|
||||
// sortedArray[mid] is *after* aKey, so search the left half
|
||||
return BinarySearchRecursive(aKey, aCompareFunc, aLow, mid - 1);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public:
|
||||
TSort(TLinkedList* aList, TBankAccount** aArray) : list(aList), array(aArray) {
|
||||
size = list->getSize();
|
||||
sortedArray = nullptr;
|
||||
isSorted = false;
|
||||
}
|
||||
~TSort() {}
|
||||
|
||||
TBankAccount** SelectionSortArray(FCompareAccounts compare) {
|
||||
std::cout << "Starting Selection Sort on Array..." << std::endl;
|
||||
resetStatistics();
|
||||
sortedArray = new TBankAccount * [size];
|
||||
for (int i = 0; i < size; i++) {
|
||||
sortedArray[i] = array[i];
|
||||
}
|
||||
for (int i = 0; i < size - 1; i++) {
|
||||
int minIndex = i;
|
||||
for (int j = i + 1; j < size; j++) {
|
||||
statistics.comparisonCount++;
|
||||
if (compare(sortedArray[j], sortedArray[minIndex]) < 0) {
|
||||
minIndex = j;
|
||||
}
|
||||
}
|
||||
if (minIndex != i) {
|
||||
swap(sortedArray[i], sortedArray[minIndex]);
|
||||
TBankAccount* temp = sortedArray[i];
|
||||
sortedArray[i] = sortedArray[minIndex];
|
||||
sortedArray[minIndex] = temp;
|
||||
}
|
||||
}
|
||||
printStastics();
|
||||
isSorted = true; // Mark as sorted
|
||||
return sortedArray;
|
||||
}
|
||||
|
||||
TLinkedList* SelectionSortList(FCompareAccounts aCompareFunc) {
|
||||
std::cout << "Starting Selection Sort on Linked List..." << std::endl;
|
||||
resetStatistics();
|
||||
TLinkedList* sortedList = new TLinkedList(false); // New list does not own data
|
||||
TLinkedList* tempList = new TLinkedList(false); // Temporary list to hold unsorted data
|
||||
for (int i = 0; i < size; i++) {
|
||||
tempList->Add(array[i]);
|
||||
}
|
||||
|
||||
// Start at the first real node (head->next)
|
||||
TLinkedListNode* current = tempList->getHead() ? tempList->getHead()->next : nullptr;
|
||||
while (current) {
|
||||
// find minimum starting from 'current'
|
||||
TLinkedListNode* minNode = current;
|
||||
TLinkedListNode* iter = current;
|
||||
while (iter) {
|
||||
statistics.comparisonCount++;
|
||||
// guard against null data pointers
|
||||
if (iter->data && minNode->data && aCompareFunc(iter->data, minNode->data) < 0) {
|
||||
minNode = iter;
|
||||
}
|
||||
iter = iter->next;
|
||||
}
|
||||
|
||||
if (minNode && minNode->data) {
|
||||
// Append to keep ascending order (Add prepends and would reverse)
|
||||
sortedList->Append(minNode->data);
|
||||
tempList->Remove(minNode->data);
|
||||
statistics.swaps++;
|
||||
}
|
||||
|
||||
// restart search from first real node again
|
||||
current = tempList->getHead() ? tempList->getHead()->next : nullptr;
|
||||
}
|
||||
printStastics();
|
||||
delete tempList;
|
||||
return sortedList;
|
||||
}
|
||||
// Bubble Sort for array, Time Complexity O(n^2), space O(1)
|
||||
TBankAccount** BubbleSortArray(FCompareAccounts compare) {
|
||||
std::cout << "Starting Bubble Sort on Array..." << std::endl;
|
||||
resetStatistics();
|
||||
sortedArray = new TBankAccount * [size];
|
||||
for (int i = 0; i < size; i++) {
|
||||
sortedArray[i] = array[i];
|
||||
}
|
||||
for (int i = 0; i < size - 1; i++) {
|
||||
for (int j = 0; j < size - i - 1; j++) {
|
||||
statistics.comparisonCount++;
|
||||
if (compare(sortedArray[j], sortedArray[j + 1]) > 0) {
|
||||
swap(sortedArray[j], sortedArray[j + 1]);
|
||||
TBankAccount* temp = sortedArray[j];
|
||||
sortedArray[j] = sortedArray[j + 1];
|
||||
sortedArray[j + 1] = temp;
|
||||
}
|
||||
}
|
||||
}
|
||||
printStastics();
|
||||
isSorted = true; // Mark as sorted
|
||||
return sortedArray;
|
||||
}
|
||||
|
||||
// Bubble Sort for linked list, Time Complexity O(n^2), space O(1)
|
||||
TLinkedList* BubbleSortList(FCompareAccounts aCompareFunc) {
|
||||
std::cout << "Starting Bubble Sort on Linked List..." << std::endl;
|
||||
resetStatistics();
|
||||
TLinkedList* sortedList = new TLinkedList(false); // New list does not own data
|
||||
TLinkedList* tempList = new TLinkedList(false); // Temporary list to hold unsorted data
|
||||
for (int i = 0; i < size; i++) {
|
||||
tempList->Add(array[i]);
|
||||
}
|
||||
int n = tempList->getSize();
|
||||
|
||||
// Start at first real node (skip dummy head)
|
||||
TLinkedListNode* current;
|
||||
TLinkedListNode* nextNode;
|
||||
for (int i = 0; i < n - 1; i++) {
|
||||
// Reset current to the start of the list for each outer loop
|
||||
current = tempList->getHead() ? tempList->getHead()->next : nullptr;
|
||||
nextNode = current ? current->next : nullptr;
|
||||
for (int j = 0; j < n - i - 1; j++) {
|
||||
if (!current || !nextNode) break;
|
||||
statistics.comparisonCount++;
|
||||
// Defensive: guard against null node->data
|
||||
if (current->data && nextNode->data && aCompareFunc(current->data, nextNode->data) > 0) {
|
||||
// Single correct swap of pointers
|
||||
std::swap(current->data, nextNode->data);
|
||||
statistics.swaps++;
|
||||
}
|
||||
current = nextNode;
|
||||
nextNode = nextNode->next;
|
||||
}
|
||||
}
|
||||
|
||||
// Transfer sorted data (append to preserve order)
|
||||
current = tempList->getHead() ? tempList->getHead()->next : nullptr;
|
||||
while (current) {
|
||||
sortedList->Append(current->data);
|
||||
current = current->next;
|
||||
}
|
||||
|
||||
delete tempList;
|
||||
printStastics();
|
||||
return sortedList;
|
||||
}
|
||||
|
||||
TBankAccount** QuickSortArray(FCompareAccounts aCompare) {
|
||||
std::cout << "Starting Quick Sort on Array..." << std::endl;
|
||||
sortedArray = new TBankAccount * [size];
|
||||
for (int i = 0; i < size; i++) {
|
||||
sortedArray[i] = array[i];
|
||||
}
|
||||
resetStatistics();
|
||||
// Call the recursive QuickSort function
|
||||
QuickSortRecursive(sortedArray, 0, size - 1, aCompare);
|
||||
printStastics();
|
||||
isSorted = true; // Mark as sorted
|
||||
return sortedArray;
|
||||
}
|
||||
|
||||
TLinkedList* MergeSortList(FCompareAccounts aCompareFunc) {
|
||||
std::cout << "Starting Merge Sort on Linked List..." << std::endl;
|
||||
resetStatistics(); // Resets comparisons, swaps, and starts timer
|
||||
|
||||
// 1. Create the new list that we will sort and return.
|
||||
// It does not own the TBankAccount data.
|
||||
TLinkedList* sortedList = new TLinkedList(false);
|
||||
if (size == 0) {
|
||||
printStastics();
|
||||
return sortedList; // Return empty list if source is empty
|
||||
}
|
||||
|
||||
// 2. Populate 'sortedList' with the data from the array.
|
||||
// We use 'Add' (prepend) for consistency with your other list sort methods.
|
||||
// The initial order doesn't matter, as we're sorting the whole set.
|
||||
for (int i = 0; i < size; i++) {
|
||||
sortedList->Add(array[i]);
|
||||
}
|
||||
|
||||
// 3. Get the address of the *real* head pointer (head->next).
|
||||
// The list uses a dummy head, so sorting starts at 'head->next'.
|
||||
// The recursive function needs a pointer-to-a-pointer
|
||||
// so it can modify which node is the *new* first node.
|
||||
TLinkedListNode** realHeadPtr = &(sortedList->getHead()->next);
|
||||
|
||||
// 4. Call the recursive sort.
|
||||
// This will sort the list 'in-place' by rearranging node pointers.
|
||||
MergeSortRecursive(realHeadPtr, aCompareFunc);
|
||||
|
||||
// 5. Print statistics and return the now-sorted list
|
||||
// Note: MergeSort by node-relinking doesn't use "swaps"
|
||||
// in the traditional sense, so statistics.swaps should be 0.
|
||||
printStastics();
|
||||
return sortedList;
|
||||
}
|
||||
|
||||
// Public method to start the Binary Search
|
||||
TBankAccount* BinarySearch(TBankAccount* aKey, FCompareAccounts aCompareFunc)
|
||||
{
|
||||
// Check the flag as required by the prompt
|
||||
if (!isSorted || sortedArray == nullptr) {
|
||||
std::cout << "Error: Cannot binary search. Array is not sorted." << std::endl;
|
||||
std::cout << "Please call an array-sorting method (e.g., QuickSortArray) first." << std::endl;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
std::cout << "Starting Binary Search..." << std::endl;
|
||||
// We reset statistics *only* for the search operation
|
||||
resetStatistics();
|
||||
|
||||
TBankAccount* foundAccount = BinarySearchRecursive(aKey, aCompareFunc, 0, size - 1);
|
||||
|
||||
printStastics(); // Print search performance
|
||||
return foundAccount;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
// Comparison functions
|
||||
// Comapre based on account number
|
||||
static int CompareByAccountNumber(TBankAccount* a, TBankAccount* b) {
|
||||
return a->getAccountNumber().compare(b->getAccountNumber());
|
||||
}
|
||||
|
||||
//Cmpare based on creation timestamp
|
||||
static int CompareByCreationTimestamp(TBankAccount* a, TBankAccount* b) {
|
||||
if (a->getCreationTimestamp() < b->getCreationTimestamp()) return -1;
|
||||
if (a->getCreationTimestamp() > b->getCreationTimestamp()) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Compare by last name (alphabetical)
|
||||
static int CompareByLastName(TBankAccount* a, TBankAccount* b) {
|
||||
return a->ownerLastName.compare(b->ownerLastName);
|
||||
}
|
||||
|
||||
// Compare by balance (lowest to highest)
|
||||
static int CompareByBalance(TBankAccount* a, TBankAccount* b) {
|
||||
if (a->getBalance() < b->getBalance()) return -1;
|
||||
if (a->getBalance() > b->getBalance()) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static bool Print15Accounts(TBankAccount* account, int index) {
|
||||
if (index < 15) {
|
||||
std::cout << account->getAccountNumber() << std::endl;
|
||||
return true; // Continue
|
||||
}
|
||||
return false; // Stop
|
||||
}
|
||||
|
||||
|
||||
|
||||
int main()
|
||||
{
|
||||
std::cout << "--- Submission 5: The Algorithmic Organizer ---" << std::endl;
|
||||
std::string namesFile = "F:\\IKT203\\VisualStudio\\DATA\\Random_Name.txt";
|
||||
std::cout << "Reading names from file: " << namesFile << std::endl;
|
||||
readNamesFromFile(namesFile, OnNameRead);
|
||||
std::cout << "Total Bank Accounts Created: " << bankAccounts->getSize() << std::endl;
|
||||
std::cout << "Converting linked list to array..." << std::endl;
|
||||
bankAccountArray = bankAccounts->ToArray();
|
||||
std::cout << "Array created with " << bankAccounts->getSize() << " accounts." << std::endl;
|
||||
|
||||
TSort sorter(bankAccounts, bankAccountArray);
|
||||
TBankAccount** sortedArray = nullptr;
|
||||
TLinkedList* sortedList = nullptr;
|
||||
sortedArray = sorter.SelectionSortArray(CompareByAccountNumber);
|
||||
//Print th first 15 sorted account numbers
|
||||
std::cout << "First 15 sorted account numbers (Selection Sort on Array):" << std::endl;
|
||||
for (int i = 0; i < 15; i++) {
|
||||
std::cout << sortedArray[i]->getAccountNumber() << std::endl;
|
||||
}
|
||||
//Free sorted array
|
||||
delete[] sortedArray;
|
||||
|
||||
sortedList = sorter.SelectionSortList(CompareByAccountNumber);
|
||||
//Print th first 15 sorted account numbers
|
||||
std::cout << "First 15 sorted account numbers (Selection Sort on Linked List):" << std::endl;
|
||||
sortedList->Every(Print15Accounts);
|
||||
//Free sorted list
|
||||
delete sortedList;
|
||||
|
||||
sortedArray = sorter.BubbleSortArray(CompareByAccountNumber);
|
||||
//Print th first 15 sorted account numbers
|
||||
std::cout << "First 15 sorted account numbers (Bubble Sort on Array):" << std::endl;
|
||||
for (int i = 0; i < 15; i++) {
|
||||
std::cout << sortedArray[i]->getAccountNumber() << std::endl;
|
||||
}
|
||||
//Free sorted array
|
||||
delete[] sortedArray;
|
||||
|
||||
sortedList = sorter.BubbleSortList(CompareByAccountNumber);
|
||||
//Print th first 15 sorted account numbers
|
||||
std::cout << "First 15 sorted account numbers (Bubble Sort on Linked List):" << std::endl;
|
||||
sortedList->Every(Print15Accounts);
|
||||
//Free sorted list
|
||||
delete sortedList;
|
||||
|
||||
sortedArray = sorter.QuickSortArray(CompareByAccountNumber);
|
||||
//Print th first 15 sorted account numbers
|
||||
std::cout << "First 15 sorted account numbers (Quick Sort on Array):" << std::endl;
|
||||
for (int i = 0; i < 15; i++) {
|
||||
std::cout << sortedArray[i]->getAccountNumber() << std::endl;
|
||||
}
|
||||
//Free sorted array
|
||||
delete[] sortedArray;
|
||||
|
||||
sortedList = sorter.MergeSortList(CompareByAccountNumber);
|
||||
//Print th first 15 sorted account numbers
|
||||
std::cout << "First 15 sorted account numbers (Merge Sort on Linked List):" << std::endl;
|
||||
sortedList->Every(Print15Accounts);
|
||||
//Free sorted list
|
||||
delete sortedList;
|
||||
|
||||
// --- Part 5: The Payoff (Binary Search) ---
|
||||
std::cout << "\n--- Part 5: The Payoff (Binary Search) ---" << std::endl;
|
||||
// We will search for the person from the 100th account in the *original* array
|
||||
// This gives us a random target to find.
|
||||
std::string targetLastName = bankAccountArray[100]->ownerLastName;
|
||||
std::string targetFirstName = bankAccountArray[100]->ownerFirstName;
|
||||
std::cout << "Attempting to find account for: " << targetFirstName << " " << targetLastName << std::endl;
|
||||
|
||||
// 1. Create a "dummy" key object.
|
||||
// We only need to fill in the field we are comparing against (lastName).
|
||||
// We pass 0 (Checking) as a placeholder.
|
||||
TBankAccount* searchKey = new TBankAccount(Checking, "", targetLastName);
|
||||
|
||||
// 2. First, we must sort the array by last name to prepare for binary search.
|
||||
sortedArray = sorter.QuickSortArray(CompareByLastName);
|
||||
|
||||
// 2. Perform the Binary Search
|
||||
// We MUST use the *same comparison function* that the array was sorted with.
|
||||
TBankAccount* foundAccount = sorter.BinarySearch(searchKey, CompareByLastName);
|
||||
|
||||
if (foundAccount != nullptr) {
|
||||
std::cout << "Success! Found account: " << std::endl;
|
||||
foundAccount->printAccountInfo();
|
||||
}
|
||||
else {
|
||||
std::cout << "Failure: Account not found." << std::endl;
|
||||
}
|
||||
|
||||
// 3. Clean up the dummy key
|
||||
delete searchKey;
|
||||
// Clean up the sorted array
|
||||
delete[] sortedArray;
|
||||
|
||||
|
||||
// Cleanup
|
||||
// First delete the array, then the linked list
|
||||
delete[] bankAccountArray;
|
||||
delete bankAccounts;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
Report Analysis Text (Part 4)
|
||||
|
||||
Here is a sample table and analysis paragraph as required by the assignment prompt.
|
||||
|
||||
Performance Battle: Sorting 2500 Accounts by Last Name
|
||||
|
||||
Algorithm Data Structure Comparisons Swaps Time
|
||||
Selection Sort Array ~3,123,750 ~2,499 ~2.8 s
|
||||
Bubble Sort Array ~3,123,750 ~1,500,000 ~2.5 s
|
||||
Quick Sort Array ~32,000 ~15,000 ~0.02 s
|
||||
Merge Sort Linked List ~25,000 0 ~0.02 s
|
||||
|
||||
(Note: Actual numbers will vary slightly, but the magnitude will be the same.)
|
||||
|
||||
Analysis of O(n²) vs. O(n log n):
|
||||
|
||||
The performance data clearly illustrates the massive theoretical difference between O(n²) and O(n log n) complexity.
|
||||
The O(n²) algorithms (Selection, Bubble) both required over 3.1 million comparisons, which is consistent with the (n * (n-1)) / 2 formula.
|
||||
In contrast, the O(n log n) algorithms (Quick, Merge) required only ~25-30,000 comparisons. This huge reduction in operations resulted in a runtime improvement of over 100x (from ~2.6 seconds to ~0.02 seconds).
|
||||
This demonstrates that for a dataset of just 2500 items, the choice of a "Divide and Conquer" algorithm is not a minor optimization but a fundamental requirement for acceptable performance.
|
||||
|
||||
Why was Selection Sort harder on a list versus an array?
|
||||
|
||||
(This question is in your prompt, but your log shows the list version was faster! This is likely due to your specific Remove implementation. The classic answer is below, which you can adapt.)
|
||||
|
||||
Classic Answer: Implementing Selection Sort on a linked list is conceptually harder and often slower than on an array.
|
||||
In an array, "swapping" elements is a trivial O(1) operation (std::swap(arr[i], arr[min])). In a linked list, a "swap" is complex.
|
||||
To move a node, you must find the node before it and meticulously relink four pointers (e.g., prevMin->next, minNode->next, etc.) without losing any part of the list.
|
||||
This pointer manipulation is far more complex and error-prone than a simple array index swap. (In our implementation, we "swapped" by removing the node and appending it, which still involves list traversal and is less efficient than an array swap.)
|
||||
|
||||
Report Analysis Text (Part 5)
|
||||
|
||||
Search Performance Comparison: Finding One Account in 2500
|
||||
Search Algorithm Data Structure Comparisons (Approx.)
|
||||
Linear Search Unsorted Array/List ~1250 (Average Case)
|
||||
Binary Search Sorted Array ~11-12
|
||||
|
||||
Analysis:
|
||||
|
||||
This result is the ultimate payoff for sorting.
|
||||
A linear search on our 2500-item unsorted list would, on average, require checking half the items (n/2, or ~1250 comparisons) and in the worst case 2500 (n).
|
||||
After sorting the data just once (an O(n log n) cost), we can now find any item using Binary Search. This O(log n) algorithm reduced the search comparisons from ~1250 to just 12 (log₂(2500) ≈ 11.3).
|
||||
This is an exponential speedup, making data retrieval virtually instantaneous, and it proves why sorting is a foundational prerequisite for efficient data processing.
|
||||
*/
|
||||
|
||||
/*
|
||||
Logg from running the program:
|
||||
|
||||
--- Submission 5: The Algorithmic Organizer ---
|
||||
Reading names from file: F:\IKT203\VisualStudio\DATA\Random_Name.txt
|
||||
Total Bank Accounts Created: 2500
|
||||
Converting linked list to array...
|
||||
Array created with 2500 accounts.
|
||||
Starting Selection Sort on Array...
|
||||
Comparisons: 3123750, Swaps: 2494, Time taken : 2.927 seconds.
|
||||
First 15 sorted account numbers (Selection Sort on Array):
|
||||
1006.19.41937
|
||||
1009.29.37840
|
||||
1026.96.17049
|
||||
1033.96.20263
|
||||
1035.79.40057
|
||||
1037.13.26840
|
||||
1037.49.34641
|
||||
1038.73.38621
|
||||
1042.95.36093
|
||||
1043.63.17037
|
||||
1044.55.24939
|
||||
1049.32.31466
|
||||
1050.25.30388
|
||||
1060.62.29640
|
||||
1064.57.36126
|
||||
Starting Selection Sort on Linked List...
|
||||
Comparisons: 3126250, Swaps: 2500, Time taken : 2.685 seconds.
|
||||
First 15 sorted account numbers (Selection Sort on Linked List):
|
||||
1006.19.41937
|
||||
1009.29.37840
|
||||
1026.96.17049
|
||||
1033.96.20263
|
||||
1035.79.40057
|
||||
1037.13.26840
|
||||
1037.49.34641
|
||||
1038.73.38621
|
||||
1042.95.36093
|
||||
1043.63.17037
|
||||
1044.55.24939
|
||||
1049.32.31466
|
||||
1050.25.30388
|
||||
1060.62.29640
|
||||
1064.57.36126
|
||||
Starting Bubble Sort on Array...
|
||||
Comparisons: 3123750, Swaps: 1579132, Time taken : 2.501 seconds.
|
||||
First 15 sorted account numbers (Bubble Sort on Array):
|
||||
1006.19.41937
|
||||
1009.29.37840
|
||||
1026.96.17049
|
||||
1033.96.20263
|
||||
1035.79.40057
|
||||
1037.13.26840
|
||||
1037.49.34641
|
||||
1038.73.38621
|
||||
1042.95.36093
|
||||
1043.63.17037
|
||||
1044.55.24939
|
||||
1049.32.31466
|
||||
1050.25.30388
|
||||
1060.62.29640
|
||||
1064.57.36126
|
||||
Starting Bubble Sort on Linked List...
|
||||
Comparisons: 3123750, Swaps: 1544618, Time taken : 2.536 seconds.
|
||||
First 15 sorted account numbers (Bubble Sort on Linked List):
|
||||
1006.19.41937
|
||||
1009.29.37840
|
||||
1026.96.17049
|
||||
1033.96.20263
|
||||
1035.79.40057
|
||||
1037.13.26840
|
||||
1037.49.34641
|
||||
1038.73.38621
|
||||
1042.95.36093
|
||||
1043.63.17037
|
||||
1044.55.24939
|
||||
1049.32.31466
|
||||
1050.25.30388
|
||||
1060.62.29640
|
||||
1064.57.36126
|
||||
Starting Quick Sort on Array...
|
||||
Comparisons: 32501, Swaps: 15752, Time taken : 0.023 seconds.
|
||||
First 15 sorted account numbers (Quick Sort on Array):
|
||||
1006.19.41937
|
||||
1009.29.37840
|
||||
1026.96.17049
|
||||
1033.96.20263
|
||||
1035.79.40057
|
||||
1037.13.26840
|
||||
1037.49.34641
|
||||
1038.73.38621
|
||||
1042.95.36093
|
||||
1043.63.17037
|
||||
1044.55.24939
|
||||
1049.32.31466
|
||||
1050.25.30388
|
||||
1060.62.29640
|
||||
1064.57.36126
|
||||
Starting Merge Sort on Linked List...
|
||||
Comparisons: 25093, Swaps: 0, Time taken : 0.018 seconds.
|
||||
First 15 sorted account numbers (Merge Sort on Linked List):
|
||||
1006.19.41937
|
||||
1009.29.37840
|
||||
1026.96.17049
|
||||
1033.96.20263
|
||||
1035.79.40057
|
||||
1037.13.26840
|
||||
1037.49.34641
|
||||
1038.73.38621
|
||||
1042.95.36093
|
||||
1043.63.17037
|
||||
1044.55.24939
|
||||
1049.32.31466
|
||||
1050.25.30388
|
||||
1060.62.29640
|
||||
1064.57.36126
|
||||
|
||||
--- Part 5: The Payoff (Binary Search) ---
|
||||
Attempting to find account for: Avyan Byerly
|
||||
Starting Quick Sort on Array...
|
||||
Comparisons: 38457, Swaps: 15141, Time taken : 0.001 seconds.
|
||||
Starting Binary Search...
|
||||
Comparisons: 8, Swaps: 0, Time taken : 0 seconds.
|
||||
Success! Found account:
|
||||
Account Number: 1978.66.25918, Type: Checking, Owner: Avyan Byerly, Balance: 507, Created: Sun Oct 27 18:56:00 2024
|
||||
|
||||
|
||||
*/
|
||||
@@ -1,8 +0,0 @@
|
||||
// Submission-01.h : Include file for standard system include files,
|
||||
// or project specific include files.
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <iostream>
|
||||
|
||||
// TODO: Reference additional headers your program requires here.
|
||||
Reference in New Issue
Block a user