From 88f15e35713c9632216931d26443dc588238732f Mon Sep 17 00:00:00 2001 From: Syndamia Date: Tue, 7 May 2024 22:17:12 +0300 Subject: [w10] Added rough solutions to ex 1-10 --- week10/Exercise01/Array.hpp | 89 +++++++++++++++++++ week10/Exercise02/Array.hpp | 143 ++++++++++++++++++++++++++++++ week10/Exercise03/main.cpp | 45 ++++++++++ week10/Exercise04/Time12.cpp | 10 +++ week10/Exercise04/Time12.h | 9 ++ week10/Exercise04/Time24.cpp | 11 +++ week10/Exercise04/Time24.h | 11 +++ week10/Exercise05/FN.cpp | 10 +++ week10/Exercise05/FN.h | 9 ++ week10/Exercise05/ModernFN.cpp | 13 +++ week10/Exercise05/ModernFN.h | 10 +++ week10/Exercise06/Grade.cpp | 5 ++ week10/Exercise06/Grade.h | 9 ++ week10/Exercise06/GradeWithName.cpp | 50 +++++++++++ week10/Exercise06/GradeWithName.h | 19 ++++ week10/Exercise07/FileString.cpp | 43 +++++++++ week10/Exercise07/FileString.h | 10 +++ week10/Exercise07/String.cpp | 67 ++++++++++++++ week10/Exercise07/String.h | 23 +++++ week10/Exercise08/Administrator.cpp | 97 ++++++++++++++++++++ week10/Exercise08/Administrator.h | 24 +++++ week10/Exercise08/Moderator.cpp | 60 +++++++++++++ week10/Exercise08/Moderator.h | 20 +++++ week10/Exercise08/User.cpp | 57 ++++++++++++ week10/Exercise08/User.h | 21 +++++ week10/Exercise09/CommunicationPacket.cpp | 10 +++ week10/Exercise09/CommunicationPacket.h | 12 +++ week10/Exercise09/IntPacket.cpp | 11 +++ week10/Exercise09/IntPacket.h | 10 +++ week10/Exercise09/StringPacket.cpp | 62 +++++++++++++ week10/Exercise09/StringPacket.h | 19 ++++ week10/Exercise10/ModifiableString.cpp | 14 +++ week10/Exercise10/ModifiableString.h | 9 ++ week10/Exercise10/SaveableString.cpp | 32 +++++++ week10/Exercise10/SaveableString.h | 8 ++ week10/Exercise10/ShowableString.cpp | 9 ++ week10/Exercise10/ShowableString.h | 9 ++ week10/Exercise10/String.cpp | 71 +++++++++++++++ week10/Exercise10/String.h | 21 +++++ week10/README.md | 126 ++++++++++++++++++++++++++ 40 files changed, 1288 insertions(+) create mode 100644 week10/Exercise01/Array.hpp create mode 100644 week10/Exercise02/Array.hpp create mode 100644 week10/Exercise03/main.cpp create mode 100644 week10/Exercise04/Time12.cpp create mode 100644 week10/Exercise04/Time12.h create mode 100644 week10/Exercise04/Time24.cpp create mode 100644 week10/Exercise04/Time24.h create mode 100644 week10/Exercise05/FN.cpp create mode 100644 week10/Exercise05/FN.h create mode 100644 week10/Exercise05/ModernFN.cpp create mode 100644 week10/Exercise05/ModernFN.h create mode 100644 week10/Exercise06/Grade.cpp create mode 100644 week10/Exercise06/Grade.h create mode 100644 week10/Exercise06/GradeWithName.cpp create mode 100644 week10/Exercise06/GradeWithName.h create mode 100644 week10/Exercise07/FileString.cpp create mode 100644 week10/Exercise07/FileString.h create mode 100644 week10/Exercise07/String.cpp create mode 100644 week10/Exercise07/String.h create mode 100644 week10/Exercise08/Administrator.cpp create mode 100644 week10/Exercise08/Administrator.h create mode 100644 week10/Exercise08/Moderator.cpp create mode 100644 week10/Exercise08/Moderator.h create mode 100644 week10/Exercise08/User.cpp create mode 100644 week10/Exercise08/User.h create mode 100644 week10/Exercise09/CommunicationPacket.cpp create mode 100644 week10/Exercise09/CommunicationPacket.h create mode 100644 week10/Exercise09/IntPacket.cpp create mode 100644 week10/Exercise09/IntPacket.h create mode 100644 week10/Exercise09/StringPacket.cpp create mode 100644 week10/Exercise09/StringPacket.h create mode 100644 week10/Exercise10/ModifiableString.cpp create mode 100644 week10/Exercise10/ModifiableString.h create mode 100644 week10/Exercise10/SaveableString.cpp create mode 100644 week10/Exercise10/SaveableString.h create mode 100644 week10/Exercise10/ShowableString.cpp create mode 100644 week10/Exercise10/ShowableString.h create mode 100644 week10/Exercise10/String.cpp create mode 100644 week10/Exercise10/String.h create mode 100644 week10/README.md diff --git a/week10/Exercise01/Array.hpp b/week10/Exercise01/Array.hpp new file mode 100644 index 0000000..29a5906 --- /dev/null +++ b/week10/Exercise01/Array.hpp @@ -0,0 +1,89 @@ +#pragma once + +template +class Array { + T* arr; + unsigned size; + unsigned allocated; + + void resize(); + + void free(); + void copyFrom(const Array& other); + +public: + Array(); + ~Array(); + Array(const Array& other); + Array& operator=(const Array& other); + Array(Array&& other); + Array& operator=(Array&& other); +}; + +template +void Array::resize() { + allocated *= 2; + T* biggerArr = new T[allocated]; + for (int i = 0; i < size; i++) { + biggerArr[i] = arr[i]; + } + delete[] arr; + arr = biggerArr; +} + +template +void Array::free() { + delete[] arr; +} + +template +void Array::copyFrom(const Array& other) { + this->size = other.size; + this->allocated = other.allocated; + this->arr = new T[allocated]; + for (int i = 0; i < size; i++) { + this->arr[i] = other.arr[i]; + } +} + +template +Array::Array() { + this->arr = nullptr; + allocated = size = 0; +} + +template +Array::~Array() { + free(); +} + +template +Array::Array(const Array& other) { + copyFrom(other); +} + +template +Array& Array::operator=(const Array& other) { + if (this != &other) { + free(); + copyFrom(other); + } + return *this; +} + +template +Array::Array(Array&& other) { + this->arr = other.arr; + other.arr = nullptr; +} + +template +Array& Array::operator=(Array&& other) { + if (this != &other) { + free(); + + this->arr = other.arr; + other.arr = nullptr; + } + return *this; +} diff --git a/week10/Exercise02/Array.hpp b/week10/Exercise02/Array.hpp new file mode 100644 index 0000000..114a1bc --- /dev/null +++ b/week10/Exercise02/Array.hpp @@ -0,0 +1,143 @@ +#pragma once + +template +class Array { + T* arr; + unsigned size; + unsigned allocated; + + void resize(); + + void free(); + void copyFrom(const Array& other); + +public: + Array(); + ~Array(); + Array(const Array& other); + Array& operator=(const Array& other); + Array(Array&& other); + Array& operator=(Array&& other); + + T& operator[](unsigned index); + T& operator[](unsigned index) const; + Array& operator+=(const Array& right); + friend bool operator==(const Array& left, const Array& right); + friend bool operator!=(const Array& left, const Array& right); + friend Array operator+(const Array& left, const Array& right); +}; + +template +void Array::resize() { + allocated *= 2; + T* biggerArr = new T[allocated]; + for (int i = 0; i < size; i++) { + biggerArr[i] = arr[i]; + } + delete[] arr; + arr = biggerArr; +} + +template +void Array::free() { + delete[] arr; +} + +template +void Array::copyFrom(const Array& other) { + this->size = other.size; + this->allocated = other.allocated; + this->arr = new T[allocated]; + for (int i = 0; i < size; i++) { + this->arr[i] = other.arr[i]; + } +} + +template +Array::Array() { + this->arr = nullptr; + allocated = size = 0; +} + +template +Array::~Array() { + free(); +} + +template +Array::Array(const Array& other) { + copyFrom(other); +} + +template +Array& Array::operator=(const Array& other) { + if (this != &other) { + free(); + copyFrom(other); + } + return *this; +} + +template +Array::Array(Array&& other) { + this->arr = other.arr; + other.arr = nullptr; +} + +template +Array& Array::operator=(Array&& other) { + if (this != &other) { + free(); + + this->arr = other.arr; + other.arr = nullptr; + } + return *this; +} + +template +T& Array::operator[](unsigned index) { + return arr[index]; +} + +template +T& Array::operator[](unsigned index) const { + return arr[index]; +} + +template +Array& Array::operator+=(const Array& right) { + for (int i = 0; i < right.size; i++) { + if (size == allocated) { + resize(); + } + arr[size++] = right[i]; + } +} + +template +bool operator==(const Array& left, const Array& right) { + if (left.size != right.size) { + return false; + } + + for (int i = 0; i < left.size; i++) { + if (left.arr[i] != right.arr[i]) { + return false; + } + } + return true; +} + +template +bool operator!=(const Array& left, const Array& right) { + return !(left == right); +} + +template +Array operator+(const Array& left, const Array& right) { + Array concat; + concat += left; + concat += right; + return concat; +} diff --git a/week10/Exercise03/main.cpp b/week10/Exercise03/main.cpp new file mode 100644 index 0000000..d394cbb --- /dev/null +++ b/week10/Exercise03/main.cpp @@ -0,0 +1,45 @@ +#include +#include + +void firstRow(const char* fileName) { + std::ifstream inFile(fileName); + if (!inFile.is_open()) { + throw "Couldn't open file!"; + } + + while (!inFile.eof() && inFile.peek() != '\n') { + inFile.get(); + } + if (inFile.eof()) { + inFile.seekg(0, std::ios::end); + unsigned len = inFile.tellg(); + inFile.close(); + throw len; + } + + inFile.seekg(0, std::ios::beg); + while (inFile.peek() != '\n') { + std::cout << inFile.get(); + } + + inFile.close(); +} + +int main() { + char buffer[1024]; + + while (true) { + try { + std::cin.getline(buffer, 1024); + firstRow(buffer); + } + catch (const char* couldntOpen) { + std::cout << couldntOpen; + } + catch (unsigned fileSize) { + std::cout << "In " << fileSize << " characters, there is now newline!" << std::endl; + continue; + } + break; + } +} diff --git a/week10/Exercise04/Time12.cpp b/week10/Exercise04/Time12.cpp new file mode 100644 index 0000000..3d1d681 --- /dev/null +++ b/week10/Exercise04/Time12.cpp @@ -0,0 +1,10 @@ +#include "Time12.h" +#include + +Time12::Time12(unsigned hours, unsigned minutes, bool pm) : Time24(hours, minutes) { + this->pm = pm; +} + +void Time12::Print12() { + std::cout << hours << ":" << minutes << " " << (pm ? "PM" : "AM"); +} diff --git a/week10/Exercise04/Time12.h b/week10/Exercise04/Time12.h new file mode 100644 index 0000000..24669e6 --- /dev/null +++ b/week10/Exercise04/Time12.h @@ -0,0 +1,9 @@ +#pragma once +#include "Time24.h" + +class Time12 : Time24 { + bool pm; +public: + Time12(unsigned hours, unsigned minutes, bool pm); + void Print12(); +}; diff --git a/week10/Exercise04/Time24.cpp b/week10/Exercise04/Time24.cpp new file mode 100644 index 0000000..59f4680 --- /dev/null +++ b/week10/Exercise04/Time24.cpp @@ -0,0 +1,11 @@ +#include "Time24.h" +#include + +void Time24::Print24() { + std::cout << hours << ":" << minutes; +} + +Time24::Time24(unsigned hours, unsigned minutes) { + this->hours = hours; + this->minutes = minutes; +} diff --git a/week10/Exercise04/Time24.h b/week10/Exercise04/Time24.h new file mode 100644 index 0000000..9b5d598 --- /dev/null +++ b/week10/Exercise04/Time24.h @@ -0,0 +1,11 @@ +#pragma once + +class Time24 { +protected: + unsigned hours; + unsigned minutes; + +public: + Time24(unsigned hours, unsigned minutes); + void Print24(); +}; diff --git a/week10/Exercise05/FN.cpp b/week10/Exercise05/FN.cpp new file mode 100644 index 0000000..877c551 --- /dev/null +++ b/week10/Exercise05/FN.cpp @@ -0,0 +1,10 @@ +#include "FN.h" +#include + +FN::FN(unsigned facultyNumber) { + this->facultyNumber = facultyNumber; +} + +void FN::PrintOldFN() { + std::cout << facultyNumber; +} diff --git a/week10/Exercise05/FN.h b/week10/Exercise05/FN.h new file mode 100644 index 0000000..9310281 --- /dev/null +++ b/week10/Exercise05/FN.h @@ -0,0 +1,9 @@ +#pragma once + +class FN { + unsigned facultyNumber; + +public: + FN(unsigned facultyNumber); + void PrintOldFN(); +}; diff --git a/week10/Exercise05/ModernFN.cpp b/week10/Exercise05/ModernFN.cpp new file mode 100644 index 0000000..72b51f0 --- /dev/null +++ b/week10/Exercise05/ModernFN.cpp @@ -0,0 +1,13 @@ +#include "ModernFN.h" +#include +#include + +ModernFN::ModernFN(const char* fn) : FN(atoi(fn + 5)) { + strncpy(this->prefix, fn, 5); + this->prefix[5] = '\0'; +} + +void ModernFN::PrintNewFN() { + std::cout << this->prefix; + PrintOldFN(); +} diff --git a/week10/Exercise05/ModernFN.h b/week10/Exercise05/ModernFN.h new file mode 100644 index 0000000..86ca2b9 --- /dev/null +++ b/week10/Exercise05/ModernFN.h @@ -0,0 +1,10 @@ +#pragma once +#include "FN.h" + +class ModernFN : public FN { + char prefix[6]; + +public: + ModernFN(const char* fn); + void PrintNewFN(); +}; diff --git a/week10/Exercise06/Grade.cpp b/week10/Exercise06/Grade.cpp new file mode 100644 index 0000000..3c7bf20 --- /dev/null +++ b/week10/Exercise06/Grade.cpp @@ -0,0 +1,5 @@ +#include "Grade.h" + +Grade::Grade(unsigned numericValue) { + this->numericValue = numericValue; +} diff --git a/week10/Exercise06/Grade.h b/week10/Exercise06/Grade.h new file mode 100644 index 0000000..8ebf3a7 --- /dev/null +++ b/week10/Exercise06/Grade.h @@ -0,0 +1,9 @@ +#pragma once + +class Grade { +protected: + unsigned numericValue; + +public: + Grade(unsigned numericValue); +}; diff --git a/week10/Exercise06/GradeWithName.cpp b/week10/Exercise06/GradeWithName.cpp new file mode 100644 index 0000000..4a1b0b2 --- /dev/null +++ b/week10/Exercise06/GradeWithName.cpp @@ -0,0 +1,50 @@ +#include "GradeWithName.h" +#include "Grade.h" +#include + +void GradeWithName::free() { + delete[] name; +} + +void GradeWithName::copyFrom(const GradeWithName& other) { + this->numericValue = other.numericValue; + this->name = new char[strlen(other.name) + 1]; + strcpy(this->name, other.name); +} + +GradeWithName::GradeWithName(unsigned numericValue, const char* name) : Grade(numericValue) { + this->name = new char[strlen(name) + 1]; + strcpy(this->name, name); +} + +GradeWithName::~GradeWithName() { + free(); +} + +GradeWithName::GradeWithName(const GradeWithName& other) { + copyFrom(other); +} + +GradeWithName& GradeWithName::operator=(const GradeWithName& other) { + if (this != &other) { + free(); + copyFrom(other); + } + return *this; +} + +GradeWithName::GradeWithName(GradeWithName&& other) : Grade(other.numericValue) { + this->name = other.name; + other.name = nullptr; +} + +GradeWithName& GradeWithName::operator=(GradeWithName&& other) { + if (this != &other) { + free(); + + this->numericValue = other.numericValue; + this->name = other.name; + other.name = nullptr; + } + return *this; +} diff --git a/week10/Exercise06/GradeWithName.h b/week10/Exercise06/GradeWithName.h new file mode 100644 index 0000000..d310975 --- /dev/null +++ b/week10/Exercise06/GradeWithName.h @@ -0,0 +1,19 @@ +#pragma once +#include "Grade.h" + +class GradeWithName : public Grade { + char* name; + + void free(); + void copyFrom(const GradeWithName& other); + +public: + GradeWithName(unsigned numericValue, const char* name); + + GradeWithName(); + ~GradeWithName(); + GradeWithName(const GradeWithName& other); + GradeWithName& operator=(const GradeWithName& other); + GradeWithName(GradeWithName&& other); + GradeWithName& operator=(GradeWithName&& other); +}; diff --git a/week10/Exercise07/FileString.cpp b/week10/Exercise07/FileString.cpp new file mode 100644 index 0000000..e3d601e --- /dev/null +++ b/week10/Exercise07/FileString.cpp @@ -0,0 +1,43 @@ +#include "FileString.h" +#include + +FileString::FileString(const char* fileName) : String() { + this->fileName = fileName; // Конвертиращ конструктор! + + std::ifstream inFile(fileName); + if (!inFile.is_open()) { + throw "Couldn't open file!"; + } + + while (!inFile.eof() && inFile.peek() != '\n') { + inFile.get(); + } + + if (inFile.eof()) { + inFile.seekg(0, std::ios::end); + this->length = inFile.peek(); + } + else { + this->length = inFile.peek() - 1; + } + + inFile.seekg(0, std::ios::beg); + str = new char[this->length + 1]; + inFile.getline(str, this->length); + str[this->length] = '\0'; + + inFile.close(); +} + +void FileString::ChangeAt(unsigned index, char newValue) { + std::fstream file(fileName.GetPtr()); + if (!file.is_open()) { + throw "Couldn't open file!"; + } + + file.seekp(index, std::ios::beg); + file.put(newValue); + str[index] = newValue; + + file.close(); +} diff --git a/week10/Exercise07/FileString.h b/week10/Exercise07/FileString.h new file mode 100644 index 0000000..830dae9 --- /dev/null +++ b/week10/Exercise07/FileString.h @@ -0,0 +1,10 @@ +#pragma once +#include "String.h" + +class FileString : String { + String fileName; // Така си спестяваме повторно писане на голяма петица + +public: + FileString(const char* fileName); + void ChangeAt(unsigned index, char newValue); +}; diff --git a/week10/Exercise07/String.cpp b/week10/Exercise07/String.cpp new file mode 100644 index 0000000..a9276c3 --- /dev/null +++ b/week10/Exercise07/String.cpp @@ -0,0 +1,67 @@ +#include "String.h" +#include + +void String::free() { + delete[] str; +} + +void String::copyFrom(const String& other) { + this->length = other.length; + this->str = new char[strlen(other.str) + 1]; + strcpy(this->str, other.str); +} + +String::String(const char* str) { + this->length = strlen(str); + this->str = new char[this->length + 1]; + strcpy(this->str, str); +} + +String::String() { + this->str = nullptr; + this->length = 0; +} + +String::~String() { + free(); +} + +String::String(const String& other) { + copyFrom(other); +} + +String& String::operator=(const String& other) { + if (this != &other) { + free(); + copyFrom(other); + } + return *this; +} + +String::String(String&& other) { + this->length = other.length; + this->str = other.str; + other.str = nullptr; +} + +String& String::operator=(String&& other) { + if (this != &other) { + free(); + + this->length = other.length; + this->str = other.str; + other.str = nullptr; + } + return *this; +} + +char& String::At(unsigned index) { + if (index >= length) { + throw "Index too big!"; + } + return str[index]; +} + +const char* String::GetPtr() { + return str; +} diff --git a/week10/Exercise07/String.h b/week10/Exercise07/String.h new file mode 100644 index 0000000..3ea986a --- /dev/null +++ b/week10/Exercise07/String.h @@ -0,0 +1,23 @@ +#pragma once + +class String { +protected: + char* str; + unsigned length; + + void free(); + void copyFrom(const String& other); + +public: + String(const char* str); + + String(); + ~String(); + String(const String& other); + String& operator=(const String& other); + String(String&& other); + String& operator=(String&& other); + + char& At(unsigned index); + const char* GetPtr(); +}; diff --git a/week10/Exercise08/Administrator.cpp b/week10/Exercise08/Administrator.cpp new file mode 100644 index 0000000..aaeecf8 --- /dev/null +++ b/week10/Exercise08/Administrator.cpp @@ -0,0 +1,97 @@ +#include "Administrator.h" + +void Administrator::resize() { + allocated *= 2; + int* bigger = new int[allocated]; + for (int i = 0; i < size; i++) { + bigger[i] = arr[i]; + } + delete[] arr; + arr = bigger; +} + +void Administrator::free() { + Moderator::free(); + delete[] arr; +} + +void Administrator::copyFrom(const Administrator& other) { + Moderator::copyFrom(other); + this->arr = new int[other.allocated]; + for (int i = 0; i < other.size; i++) { + this->arr[i] = other.arr[i]; +} +} + +Administrator::Administrator() : Moderator() { + arr = nullptr; + size = allocated = 0; +} + +Administrator::~Administrator() { + Administrator::free(); +} + +Administrator::Administrator(const Administrator& other) { + Administrator::copyFrom(other); +} + +Administrator& Administrator::operator=(const Administrator& other) { + if (this != &other) { + Administrator::free(); + Administrator::copyFrom(other); + } + return *this; +} + +Administrator::Administrator(Administrator&& other) { + this->name = other.name; + other.name = nullptr; + this->password = other.password; + other.password = nullptr; + this->signature = other.signature; + other.signature = nullptr; + this->arr = other.arr; + other.arr = nullptr; + this->size = other.size; + this->allocated = other.allocated; +} + +Administrator& Administrator::operator=(Administrator&& other) { + if (this != &other) { + Administrator::free(); + + this->name = other.name; + other.name = nullptr; + this->password = other.password; + other.password = nullptr; + this->signature = other.signature; + other.signature = nullptr; + this->arr = other.arr; + other.arr = nullptr; + this->size = other.size; + this->allocated = other.allocated; + } + return *this; +} + +void Administrator::AddID(int value) { + if (allocated <= size) { + resize(); + } + + arr[size++] = value; +} + +void Administrator::RemoveID(int value) { + int i; + for (i = 0; i < size; i++) { + if (arr[i] == value) { + break; + } + } + for (; i < size - 1; i++) { + arr[i] = arr[i+1]; + } + size--; +} diff --git a/week10/Exercise08/Administrator.h b/week10/Exercise08/Administrator.h new file mode 100644 index 0000000..c0f9975 --- /dev/null +++ b/week10/Exercise08/Administrator.h @@ -0,0 +1,24 @@ +#pragma once +#include "Moderator.h" + +class Administrator : public Moderator { + int* arr; + unsigned size; + unsigned allocated; + + void resize(); + + void free(); + void copyFrom(const Administrator& other); + +public: + Administrator(); + ~Administrator(); + Administrator(const Administrator& other); + Administrator& operator=(const Administrator& other); + Administrator(Administrator&& other); + Administrator& operator=(Administrator&& other); + + void AddID(int value); + void RemoveID(int value); +}; diff --git a/week10/Exercise08/Moderator.cpp b/week10/Exercise08/Moderator.cpp new file mode 100644 index 0000000..d5d53b8 --- /dev/null +++ b/week10/Exercise08/Moderator.cpp @@ -0,0 +1,60 @@ +#include "Moderator.h" +#include + +void Moderator::free() { + User::free(); + delete[] signature; +} + +void Moderator::copyFrom(const Moderator& other) { + User::copyFrom(other); + this->signature = new char[strlen(other.signature) + 1]; + strcpy(this->signature, other.signature); +} + +Moderator::Moderator() : User() { + signature = nullptr; +} + +Moderator::~Moderator() { + Moderator::free(); +} + +Moderator::Moderator(const Moderator& other) { + Moderator::copyFrom(other); +} + +Moderator& Moderator::operator=(const Moderator& other) { + if (this != &other) { + Moderator::free(); + Moderator::copyFrom(other); + } + return *this; +} + +Moderator::Moderator(Moderator&& other) { + this->name = other.name; + other.name = nullptr; + this->password = other.password; + other.password = nullptr; + this->signature = other.signature; + other.signature = nullptr; +} + +Moderator& Moderator::operator=(Moderator&& other) { + if (this != &other) { + Moderator::free(); + + this->name = other.name; + other.name = nullptr; + this->password = other.password; + other.password = nullptr; + this->signature = other.signature; + other.signature = nullptr; + } + return *this; +} + +const char* Moderator::GetSignature() { + return this->signature; +} diff --git a/week10/Exercise08/Moderator.h b/week10/Exercise08/Moderator.h new file mode 100644 index 0000000..41bb5c6 --- /dev/null +++ b/week10/Exercise08/Moderator.h @@ -0,0 +1,20 @@ +#pragma once +#include "User.h" + +class Moderator : public User { +protected: + char* signature; + + void free(); + void copyFrom(const Moderator& other); + +public: + Moderator(); + ~Moderator(); + Moderator(const Moderator& other); + Moderator& operator=(const Moderator& other); + Moderator(Moderator&& other); + Moderator& operator=(Moderator&& other); + + const char* GetSignature(); +}; diff --git a/week10/Exercise08/User.cpp b/week10/Exercise08/User.cpp new file mode 100644 index 0000000..663bfd3 --- /dev/null +++ b/week10/Exercise08/User.cpp @@ -0,0 +1,57 @@ +#include "User.h" +#include + +void User::free() { + delete[] name; + delete[] password; +} + +void User::copyFrom(const User& other) { + this->name = new char[strlen(other.name) + 1]; + strcpy(this->name, other.name); + this->password = new char[strlen(other.password) + 1]; + strcpy(this->password, other.password); +} + +User::User() { + name = password = nullptr; +} + +User::~User() { + free(); +} + +User::User(const User& other) { + copyFrom(other); +} + +User& User::operator=(const User& other) { + if (this != &other) { + free(); + copyFrom(other); + } + return *this; +} + +User::User(User&& other) { + this->name = other.name; + other.name = nullptr; + this->password = other.password; + other.password = nullptr; +} + +User& User::operator=(User&& other) { + if (this != &other) { + free(); + copyFrom(other); + } + return *this; +} + +const char* User::GetName() { + return this->name; +} + +const char* User::GetPassword() { + return this->password; +} diff --git a/week10/Exercise08/User.h b/week10/Exercise08/User.h new file mode 100644 index 0000000..dd86c76 --- /dev/null +++ b/week10/Exercise08/User.h @@ -0,0 +1,21 @@ +#pragma once + +class User { +protected: + char* name; + char* password; + + void free(); + void copyFrom(const User& other); + +public: + User(); + ~User(); + User(const User& other); + User& operator=(const User& other); + User(User&& other); + User& operator=(User&& other); + + const char* GetName(); + const char* GetPassword(); +}; diff --git a/week10/Exercise09/CommunicationPacket.cpp b/week10/Exercise09/CommunicationPacket.cpp new file mode 100644 index 0000000..4e9cb58 --- /dev/null +++ b/week10/Exercise09/CommunicationPacket.cpp @@ -0,0 +1,10 @@ +#include "CommunicationPacket.h" + +CommunicationPacket::CommunicationPacket(unsigned startAddress, unsigned endAddress) { + this->startAddress = startAddress; + this->endAddress = endAddress; + dataSize = 0; +} + +CommunicationPacket::CommunicationPacket() : CommunicationPacket(0, 0) { +} diff --git a/week10/Exercise09/CommunicationPacket.h b/week10/Exercise09/CommunicationPacket.h new file mode 100644 index 0000000..18ea7be --- /dev/null +++ b/week10/Exercise09/CommunicationPacket.h @@ -0,0 +1,12 @@ +#pragma once + +class CommunicationPacket { +protected: + unsigned startAddress; + unsigned endAddress; + unsigned dataSize; + +public: + CommunicationPacket(unsigned startAddress, unsigned endAddress); + CommunicationPacket(); +}; diff --git a/week10/Exercise09/IntPacket.cpp b/week10/Exercise09/IntPacket.cpp new file mode 100644 index 0000000..a4b4842 --- /dev/null +++ b/week10/Exercise09/IntPacket.cpp @@ -0,0 +1,11 @@ +#include "IntPacket.h" +#include "CommunicationPacket.h" + +IntPacket::IntPacket() : CommunicationPacket() { + data = 0; +} + +IntPacket::IntPacket(unsigned startAddress, unsigned endAddress, int data) : CommunicationPacket(startAddress, endAddress) { + this->data = data; + this->dataSize = sizeof(int); +} diff --git a/week10/Exercise09/IntPacket.h b/week10/Exercise09/IntPacket.h new file mode 100644 index 0000000..be88bce --- /dev/null +++ b/week10/Exercise09/IntPacket.h @@ -0,0 +1,10 @@ +#pragma once +#include "CommunicationPacket.h" + +class IntPacket : CommunicationPacket { + int data; + +public: + IntPacket(); + IntPacket(unsigned startAddress, unsigned endAddress, int data); +}; diff --git a/week10/Exercise09/StringPacket.cpp b/week10/Exercise09/StringPacket.cpp new file mode 100644 index 0000000..2b8aa72 --- /dev/null +++ b/week10/Exercise09/StringPacket.cpp @@ -0,0 +1,62 @@ +#include "StringPacket.h" +#include "CommunicationPacket.h" +#include + +void StringPacket::free() { + delete[] data; +} + +void StringPacket::copyFrom(const StringPacket& other) { + this->startAddress = other.startAddress; + this->endAddress = other.endAddress; + this->dataSize = other.dataSize; + this->data = new char[dataSize + 1]; + strcpy(this->data, other.data); +} + +StringPacket::StringPacket() : CommunicationPacket() { + data = nullptr; +} + +StringPacket::~StringPacket() { + free(); +} + +StringPacket::StringPacket(const StringPacket& other) { + copyFrom(other); +} + +StringPacket& StringPacket::operator=(const StringPacket& other) { + if (this != &other) { + free(); + copyFrom(other); + } + return *this; +} + +StringPacket::StringPacket(StringPacket&& other) { + this->startAddress = other.startAddress; + this->endAddress = other.endAddress; + this->dataSize = other.dataSize; + this->data = other.data; + other.data = nullptr; +} + +StringPacket& StringPacket::operator=(StringPacket&& other) { + if (this != &other) { + free(); + + this->startAddress = other.startAddress; + this->endAddress = other.endAddress; + this->dataSize = other.dataSize; + this->data = other.data; + other.data = nullptr; + } + return *this; +} + +StringPacket::StringPacket(unsigned startAddress, unsigned endAddress, const char* data) : CommunicationPacket(startAddress, endAddress) { + this->dataSize = strlen(data); + this->data = new char[dataSize + 1]; + strcpy(this->data, data); +} diff --git a/week10/Exercise09/StringPacket.h b/week10/Exercise09/StringPacket.h new file mode 100644 index 0000000..b7bbc73 --- /dev/null +++ b/week10/Exercise09/StringPacket.h @@ -0,0 +1,19 @@ +#pragma once + +#include "CommunicationPacket.h" +class StringPacket : CommunicationPacket { + char* data; + + void free(); + void copyFrom(const StringPacket& other); + +public: + StringPacket(); + ~StringPacket(); + StringPacket(const StringPacket& other); + StringPacket& operator=(const StringPacket& other); + StringPacket(StringPacket&& other); + StringPacket& operator=(StringPacket&& other); + + StringPacket(unsigned startAddress, unsigned endAddress, const char* data); +}; diff --git a/week10/Exercise10/ModifiableString.cpp b/week10/Exercise10/ModifiableString.cpp new file mode 100644 index 0000000..bd42088 --- /dev/null +++ b/week10/Exercise10/ModifiableString.cpp @@ -0,0 +1,14 @@ +#include "ModifiableString.h" + +char& ModifiableString::operator[](int index) { + return str[index]; +} + +char& ModifiableString::operator[](int index) const { + return str[index]; +} + +ModifiableString& ModifiableString::operator+=(const ModifiableString& right) { + String::operator=(*this + right); + return *this; +} diff --git a/week10/Exercise10/ModifiableString.h b/week10/Exercise10/ModifiableString.h new file mode 100644 index 0000000..971ceb8 --- /dev/null +++ b/week10/Exercise10/ModifiableString.h @@ -0,0 +1,9 @@ +#pragma once +#include "String.h" + +class ModifiableString : protected String { +public: + char& operator[](int index); + char& operator[](int index) const; + ModifiableString& operator+=(const ModifiableString& right); +}; diff --git a/week10/Exercise10/SaveableString.cpp b/week10/Exercise10/SaveableString.cpp new file mode 100644 index 0000000..4fa41e8 --- /dev/null +++ b/week10/Exercise10/SaveableString.cpp @@ -0,0 +1,32 @@ +#include "SaveableString.h" +#include +#include + +void SaveableString::write(const char* fileName) { + std::ofstream outFile(fileName); + if (!outFile.is_open()) { + throw "Coudln't open file!"; + } + + outFile.write(fileName, sizeof(char) * strlen(str)); + + outFile.close(); +} + +void SaveableString::read(const char* fileName) { + std::ifstream inFile(fileName); + if (!inFile.is_open()) { + throw "Coudln't open file!"; + } + + inFile.seekg(0, std::ios::end); + unsigned length = inFile.tellg(); + inFile.seekg(0, std::ios::beg); + + free(); + str = new char[length + 1]; + inFile.read(str, sizeof(char) * length); + str[length] = '\0'; + + inFile.close(); +} diff --git a/week10/Exercise10/SaveableString.h b/week10/Exercise10/SaveableString.h new file mode 100644 index 0000000..3952c27 --- /dev/null +++ b/week10/Exercise10/SaveableString.h @@ -0,0 +1,8 @@ +#pragma once +#include "ModifiableString.h" + +class SaveableString : ModifiableString { +public: + void write(const char* fileName); + void read(const char* fileName); +}; diff --git a/week10/Exercise10/ShowableString.cpp b/week10/Exercise10/ShowableString.cpp new file mode 100644 index 0000000..1231a9c --- /dev/null +++ b/week10/Exercise10/ShowableString.cpp @@ -0,0 +1,9 @@ +#include "ShowableString.h" + +std::ostream& operator<<(std::ostream& ostr, const ShowableString& str) { + return ostr << str; +} + +std::istream& operator>>(std::istream& istr, const ShowableString& str) { + return istr >> str; // Лошо! +} diff --git a/week10/Exercise10/ShowableString.h b/week10/Exercise10/ShowableString.h new file mode 100644 index 0000000..ff46f6c --- /dev/null +++ b/week10/Exercise10/ShowableString.h @@ -0,0 +1,9 @@ +#pragma once +#include "ModifiableString.h" +#include + +class ShowableString : ModifiableString { +public: + friend std::ostream& operator<<(std::ostream& ostr, const ShowableString& str); + friend std::istream& operator>>(std::istream& istr, const ShowableString& str); +}; diff --git a/week10/Exercise10/String.cpp b/week10/Exercise10/String.cpp new file mode 100644 index 0000000..7fd689f --- /dev/null +++ b/week10/Exercise10/String.cpp @@ -0,0 +1,71 @@ +#include "String.h" +#include + +void String::free() { + delete[] str; +} + +void String::copyFrom(const String& other) { + this->str = new char[strlen(other.str) + 1]; + strcpy(this->str, other.str); +} + +String::String() { + str = nullptr; +} + +String::~String() { + free(); +} + +String::String(const String& other) { + copyFrom(other); +} + +String& String::operator=(const String& other) { + if (this != &other) { + free(); + copyFrom(other); + } + return *this; +} + +String::String(String&& other) { + this->str = other.str; +} + +String& String::operator=(String&& other) { + if (this != &other) { + free(); + + this->str = other.str; + } + return *this; +} + +bool operator==(const String& left, const String& right) { + int i; + for (i = 0; left.str[i] != '\0' && right.str[i] != '\0'; i++) { + if (left.str[i] != right.str[i]) + return false; + } + return left.str[i] == '\0' && right.str[i] == '\0'; +} + +bool operator!=(const String& left, const String& right) { + return !(left == right); +} + +String operator+(const String& left, const String& right) { + String concat; + concat.str = new char[strlen(left.str) + strlen(right.str) + 1]; + int i; + for (i = 0; left.str[i] != '\0'; i++) { + concat.str[i] = left.str[i]; + } + int j; + for (j = 0; right.str[j] != '\0'; j++) { + concat.str[i+j] = right.str[j]; + } + return concat; +} diff --git a/week10/Exercise10/String.h b/week10/Exercise10/String.h new file mode 100644 index 0000000..4ae55c0 --- /dev/null +++ b/week10/Exercise10/String.h @@ -0,0 +1,21 @@ +#pragma once + +class String { +protected: + char* str; + + void free(); + void copyFrom(const String& other); + +public: + String(); + ~String(); + String(const String& other); + String& operator=(const String& other); + String(String&& other); + String& operator=(String&& other); + + friend bool operator==(const String& left, const String& right); + friend bool operator!=(const String& left, const String& right); + friend String operator+(const String& left, const String& right); +}; diff --git a/week10/README.md b/week10/README.md new file mode 100644 index 0000000..b43d5f4 --- /dev/null +++ b/week10/README.md @@ -0,0 +1,126 @@ +# Задачи - ООП, Седмица 10, 25.04.2024 + +*Този файл е копие на задачите от: [syndamia.com/teaching/oop-2023/week10](https://syndamia.com/teaching/oop-2023/week10)* + +## Преговорни + +&:warn Моля, не отделяйте на преговорните задачи повече от 30мин + +### Задача 1 - Шаблони + +Реализирайте шаблонен клас `Array`, който запазва динамично-заделен и оразмеряем масив от елементи с подаден тип. +Имплементирайте голяма четворка. + +### Задача 2 - Оператори + +За предходния шаблонен клас имплементирайте оператори: + +- [], който връща рефернция към елемента на подадения индекс +- == и !=, които сравняват поелементно +- +, += които конкатенират (слепват) два масива + +### Задача 3 - Грешки + +Имплементирайте функция, която приема име на текстов файл и изкарва на екрана първия ред от него. +Ако файлът не може да бъде отворен, хвърлете грешка - низ. +Ако във файлът няма други редове (няма знакът `'\n'`), тогава върнете число - размерът на файла. + +В главната функция, приемете името на файла от потребителския вход и извикайте функцията. +Ако файлът не може да бъде отворен, тогава изкарайте хвърлената грешка на терминала и приключете програмата (успешно). +Ако няма други редове в него, тогава изкарайте съобщението "In X characters, there is no newline!", където X е хвърленото число, и приемете пак име на файла от потребителския вход. + +## Лесни + +### Задача 4 + +Реализирайте клас `Time24`, който запазва час и минути (в 24-часов формат) в две отделни целичислени член-данни. +Имплементирайте член-функция `Print24`, която изкарва часа на екрана в 24-часов формат. +Нека конструкторът му приема две целочислени променливи, една за часа и втора за минутите. + +Реализирайте негов наследник `Time12`, който имплементира метод `Print12`, принтиращ часа в 12-часов формат. +Имплементирайте и негов конструктор, който приема две целочислени променливи (една за часа и една за минутите), заедно с булева променлива описваща дали часа е следобеден или не. + +### Задача 5 + +Реализирайте клас `FN`, който запазва факултетен номер като неотрицателно цяло число от 5 цифри. +Реализирайте негов наследник `ModernFN`, който запазва и начален низ, състоящ се от цифра, две букви и още две цифри. + +Имплементирайте конструктори, като този на `FN` приема число, докато този на `ModernFN` приема низ, състоящ се от целия факултетен номер (и трябва да конвертирате последните 5 цифри). +Имплементирайте метод `PrintOldFN` на класа `FN` и метод `PrintNewFN` на класа `ModernFN`, които изкарват целия факултетен номер на съответния клас. + +### Задача 6 + +Реализирайте клас `Grade`, който запазва оценка (от 2 до 6) като неотрицателна целочислена член-данна. +Реализирайте и негов наследник `GradeWithName`, който запазва и името на оценката като низ с произволна дължина. + +Конструктора на `Grade` приема само числовата стойност, докато този на наследника приема и името на оценката. +Имплементирайте голяма петица на `GradeWithName`. + +### Задача 7 + +Реализирайте клас `String`, който запазва низ с произволна дължина. +Имплементирайте голяма петица и член-функция `At`, която приема индекс и връща референция към буквата на този индекс (при невалиден индекс хвърляте грешка). + +Реализирайте негов наследник `FileString`, който запазва и името на текстов файл като низ с произволна дължина. +Ако е нужно, имплементирайте голяма петица. + +Самия низ в `FileString` е първия низ (начало първата буква и край `'\n'`) от файла с подадено име. + +Имплементирайте метод `ChangeAt`, който приема индекс и нова буква, променя буквата на дадения индекс с подадената и обновява файла със запазеното име. + +### Задача 8 + +Реализирайте клас `User`, който запава име и парола като два низа с произволна дължина. +Реализирайте негов наследник `Moderator`, който запазва и подпис, който също е низ с произволна дължина. +Реализирайте наследник `Administrator` на `Moderator`, който запазва и оразмеряващ се масив от цели числа. + +Идеята е, че всяко действие от модератор или администратор се "подписва" публично (за да се знае, че той го е направил, дори да си смени името), а за администратор допълнително пазим масив от идентификатори на форуми, които администрира. + +За всеки клас имплементирайте голяма петица и гетъри и сетъри за името и паролата, когато е нужно. +За `Moderator` имплементирайте гетър за подписа, но без сетър. +За `Administrator` имплементирайте методи за добавяне и премахване на идентификатор на форум. + +### Задача 9 + +Реализирайте клас `CommunicationPacket`, който запазва начален и краен адрес като две неотрицателни цели числа, заедно с трето число за размера на данните. +В този клас никога няма данни, затова размера винаги е нула. + +Реализирайте негови наследници `StringPacket` и `IntPacket`, където първия запазва и низ с произволна дължина (и дължината му е размера на данните) докато втория запазва и едно цяло число (и размера на `int` е размера на данните). + +Размерът не се подава на конструктори, а се изчислява в конструктори. +Имплементирайте голяма петица и конструктори с нужните параметри. + +### Задача 10 + +Реализирайте клас `String`, който запазва низ с произволна дължина, и имплементира оператори ==, !=, + (който връща нов низ с конкатенацията на двата низа). + +Реализирайте негов наследник `ModifiableString`, който имплементира оператор[] (връщащ референция към буквата на дадения индекс) и оператор+=. + +Реализирайте наследник на `ModifiableString`, `ShowableString`, който имплементира оператори << и >>. +Реализирайте наследник на `ModifiableString`, `SaveableString`, който имплементира методи write и read, приемащи име на двоичен файл и записващи или четещи низа от този файл. + +За всички класове имплементирайте голяма петица, когато е нужно. + +## Трудни + +### Задача 11 + +Реализирайте шаблонен клас `Array`, който запазва оразмеряем масив с елементи от подаден тип. +Имплементирайте оператор== и оператор!=, заедно с метод `isEmpty`. +Концептуално идеята е, че този масив не може да се променя след като му се въведат стойностите от конструктора. + +Реализирайте негов наследник `PrintableArray`, който имплементира оператори << и >>. +Реализирайте наследник `SaveableArray` на `Array`, който имплементира методи write и read, приемащи име на файл и булева стойност дали е двоичен или не, и съответно прочитат или запазват елементите от този масив във файла. + +Реализирайте трети наследник, `ModifiableArray`, на `Array`, в който са имплементирани член-функции: + +- `push`, която приема елемент и го вмъква в (десния) края на масива +- `pop`, който премахва елемент от (десния) края на масива +- `last`, който връща последния елемент от масива + +Може да се налага масива да се оразмерява. +Като подсказка, имплементирайте си метод, наличен за класа и наследници, който вмъква елемент на произволен индекс. + +Реализирайте наследник `IndexableArray` на `ModifiableArray`, който имплементира оператор[]. +Ако индекса е след края, тогава "вмъквате" елементи по подразбиране между края и подадения индекс, и връщате елемента от сега новия край. +Реализирайте наследник `FrontableArray` на `ModifiableArray`, който имплементира методи `pushf` и `popf`, който работят като `push` и `pop`, но с елемента в началото на масива (първия елемент). -- cgit v1.2.3