From 40f7cc8f54d0c221a391457fd38a44d0633aa088 Mon Sep 17 00:00:00 2001 From: angeld55 Date: Mon, 16 May 2022 14:05:08 +0300 Subject: fixed typo in folder name --- Utills/BigFour.cpp | 89 ------ Utills/Kindle/Book.cpp | 174 ---------- Utills/Kindle/Book.h | 34 -- Utills/Kindle/Kindle.cpp | 354 --------------------- Utills/Kindle/Kindle.h | 55 ---- Utills/Kindle/Page.cpp | 37 --- Utills/Kindle/Page.h | 21 -- Utills/Kindle/Pair.hpp | 29 -- Utills/Kindle/Source.cpp | 6 - Utills/Kindle/User.cpp | 22 -- Utills/Kindle/User.h | 22 -- Utills/Kindle/readme.md | 66 ---- Utills/Kindle/serialize.cpp | 71 ----- Utills/Kindle/serialize.h | 20 -- Utills/Kindle/string.cpp | 158 --------- Utills/Kindle/string.h | 42 --- Utills/Kindle/vector.hpp | 239 -------------- ...\320\260\320\261\320\276\321\202\320\260_1.pdf" | Bin 811843 -> 0 bytes Utills/k_1_SI/task1.cpp | 138 -------- Utills/k_1_SI/task2_read.cpp | 55 ---- Utills/k_1_SI/task2_write.cpp | 84 ----- ...20\236\320\236\320\237, \320\241\320\230, 2022" | 29 -- .../Source.cpp" | 12 - .../Task1/LogFile.cpp" | 92 ------ .../Task1/LogFile.h" | 24 -- .../Task1/Timestamp.cpp" | 5 - .../Task1/Timestamp.h" | 9 - .../User.cpp" | 97 ------ .../User.h" | 26 -- .../chatSystem.cpp" | 80 ----- .../chatSystem.h" | 31 -- ...5\320\275\320\270\320\265 \320\241\320\230.pdf" | Bin 69150 -> 0 bytes .../demo.cpp" | 89 ------ Utils/BigFour.cpp | 89 ++++++ Utils/Kindle/Book.cpp | 174 ++++++++++ Utils/Kindle/Book.h | 34 ++ Utils/Kindle/Kindle.cpp | 354 +++++++++++++++++++++ Utils/Kindle/Kindle.h | 55 ++++ Utils/Kindle/Page.cpp | 37 +++ Utils/Kindle/Page.h | 21 ++ Utils/Kindle/Pair.hpp | 29 ++ Utils/Kindle/Source.cpp | 6 + Utils/Kindle/User.cpp | 22 ++ Utils/Kindle/User.h | 22 ++ Utils/Kindle/readme.md | 66 ++++ Utils/Kindle/serialize.cpp | 71 +++++ Utils/Kindle/serialize.h | 20 ++ Utils/Kindle/string.cpp | 158 +++++++++ Utils/Kindle/string.h | 42 +++ Utils/Kindle/vector.hpp | 239 ++++++++++++++ ...\320\260\320\261\320\276\321\202\320\260_1.pdf" | Bin 0 -> 811843 bytes Utils/k_1_SI/task1.cpp | 138 ++++++++ Utils/k_1_SI/task2_read.cpp | 55 ++++ Utils/k_1_SI/task2_write.cpp | 84 +++++ ...20\236\320\236\320\237, \320\241\320\230, 2022" | 29 ++ .../Source.cpp" | 12 + .../Task1/LogFile.cpp" | 92 ++++++ .../Task1/LogFile.h" | 24 ++ .../Task1/Timestamp.cpp" | 5 + .../Task1/Timestamp.h" | 9 + .../User.cpp" | 97 ++++++ .../User.h" | 26 ++ .../chatSystem.cpp" | 80 +++++ .../chatSystem.h" | 31 ++ ...5\320\275\320\270\320\265 \320\241\320\230.pdf" | Bin 0 -> 69150 bytes .../demo.cpp" | 89 ++++++ 66 files changed, 2210 insertions(+), 2210 deletions(-) delete mode 100644 Utills/BigFour.cpp delete mode 100644 Utills/Kindle/Book.cpp delete mode 100644 Utills/Kindle/Book.h delete mode 100644 Utills/Kindle/Kindle.cpp delete mode 100644 Utills/Kindle/Kindle.h delete mode 100644 Utills/Kindle/Page.cpp delete mode 100644 Utills/Kindle/Page.h delete mode 100644 Utills/Kindle/Pair.hpp delete mode 100644 Utills/Kindle/Source.cpp delete mode 100644 Utills/Kindle/User.cpp delete mode 100644 Utills/Kindle/User.h delete mode 100644 Utills/Kindle/readme.md delete mode 100644 Utills/Kindle/serialize.cpp delete mode 100644 Utills/Kindle/serialize.h delete mode 100644 Utills/Kindle/string.cpp delete mode 100644 Utills/Kindle/string.h delete mode 100644 Utills/Kindle/vector.hpp delete mode 100644 "Utills/homework_1_SI/\320\224\320\276\320\274\320\260\321\210\320\275\320\260_\321\200\320\260\320\261\320\276\321\202\320\260_1.pdf" delete mode 100644 Utills/k_1_SI/task1.cpp delete mode 100644 Utills/k_1_SI/task2_read.cpp delete mode 100644 Utills/k_1_SI/task2_write.cpp delete mode 100644 "Utills/\320\242\320\265\320\274\320\270 \320\267\320\260 \321\203\321\201\321\202\320\265\320\275 \320\270\320\267\320\277\320\270\321\202 - \320\236\320\236\320\237, \320\241\320\230, 2022" delete mode 100644 "Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Source.cpp" delete mode 100644 "Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Task1/LogFile.cpp" delete mode 100644 "Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Task1/LogFile.h" delete mode 100644 "Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Task1/Timestamp.cpp" delete mode 100644 "Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Task1/Timestamp.h" delete mode 100644 "Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/User.cpp" delete mode 100644 "Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/User.h" delete mode 100644 "Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/chatSystem.cpp" delete mode 100644 "Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/chatSystem.h" delete mode 100644 "Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/\320\267\320\260\320\264\320\260\321\207\320\270 \320\267\320\260 \320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265 \320\241\320\230.pdf" delete mode 100644 "Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/\321\204\321\203\320\275\320\272\321\206\320\270\320\270 \320\276\321\202 \320\277\320\276 - \320\262\320\270\321\201\320\276\320\272 \321\200\320\265\320\264/demo.cpp" create mode 100644 Utils/BigFour.cpp create mode 100644 Utils/Kindle/Book.cpp create mode 100644 Utils/Kindle/Book.h create mode 100644 Utils/Kindle/Kindle.cpp create mode 100644 Utils/Kindle/Kindle.h create mode 100644 Utils/Kindle/Page.cpp create mode 100644 Utils/Kindle/Page.h create mode 100644 Utils/Kindle/Pair.hpp create mode 100644 Utils/Kindle/Source.cpp create mode 100644 Utils/Kindle/User.cpp create mode 100644 Utils/Kindle/User.h create mode 100644 Utils/Kindle/readme.md create mode 100644 Utils/Kindle/serialize.cpp create mode 100644 Utils/Kindle/serialize.h create mode 100644 Utils/Kindle/string.cpp create mode 100644 Utils/Kindle/string.h create mode 100644 Utils/Kindle/vector.hpp create mode 100644 "Utils/homework_1_SI/\320\224\320\276\320\274\320\260\321\210\320\275\320\260_\321\200\320\260\320\261\320\276\321\202\320\260_1.pdf" create mode 100644 Utils/k_1_SI/task1.cpp create mode 100644 Utils/k_1_SI/task2_read.cpp create mode 100644 Utils/k_1_SI/task2_write.cpp create mode 100644 "Utils/\320\242\320\265\320\274\320\270 \320\267\320\260 \321\203\321\201\321\202\320\265\320\275 \320\270\320\267\320\277\320\270\321\202 - \320\236\320\236\320\237, \320\241\320\230, 2022" create mode 100644 "Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Source.cpp" create mode 100644 "Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Task1/LogFile.cpp" create mode 100644 "Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Task1/LogFile.h" create mode 100644 "Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Task1/Timestamp.cpp" create mode 100644 "Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Task1/Timestamp.h" create mode 100644 "Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/User.cpp" create mode 100644 "Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/User.h" create mode 100644 "Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/chatSystem.cpp" create mode 100644 "Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/chatSystem.h" create mode 100644 "Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/\320\267\320\260\320\264\320\260\321\207\320\270 \320\267\320\260 \320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265 \320\241\320\230.pdf" create mode 100644 "Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/\321\204\321\203\320\275\320\272\321\206\320\270\320\270 \320\276\321\202 \320\277\320\276 - \320\262\320\270\321\201\320\276\320\272 \321\200\320\265\320\264/demo.cpp" diff --git a/Utills/BigFour.cpp b/Utills/BigFour.cpp deleted file mode 100644 index 383440d..0000000 --- a/Utills/BigFour.cpp +++ /dev/null @@ -1,89 +0,0 @@ - -#include -#include - -using namespace std; - -class Student -{ - char* name; - int* grades; - size_t gradesSize; - - void free() - { - delete[] name, grades; - } - - void copyFrom(const Student& other) - { - setName(other.name); - setGrades(other.grades); - } - - public: - - Student() : name(nullptr), grades(nullptr) {} - - Student(const Student& other) - { - copyFrom(other); - } - - Student& operator=(const Student& other) - { - if (this != &other) - { - free(); - copyFrom(other); - } - return *this; - } - - ~Student() - { - free(); - } - - const char* getName() const - { - return name; - } - - const int* getGrades() const - { - return grades; - } - - void setName(const char* givenName) - { - if(givenName == nullptr || givenName == name) - return; - delete[] name; - name = new char[strlen(givenName) + 1]; - strcpy(name, givenName); - } - - void setGrades(const int* givenGrades, size_t size) - { - if(givenGrades == nullptr || givenGrades == grades) - return; - - delete[] grades; - - grades = new int[size]; - for(size_t i = 0; i< size; i++) - grades[i] = givenGrades[i]; - gradesSize = size; - } - - -}; - -int main() -{ - - - return 0; -} - diff --git a/Utills/Kindle/Book.cpp b/Utills/Kindle/Book.cpp deleted file mode 100644 index 8bfb050..0000000 --- a/Utills/Kindle/Book.cpp +++ /dev/null @@ -1,174 +0,0 @@ -#include "Book.h" -#include - -void Book::addRating(unsigned short r, const string& name) { - if (r > 10) - return; - - int raterIndex = -1; - - for (size_t i = 0; i < ratings.getSize(); i++) { - if (name == ratings[i].getFirst()) { - raterIndex = i; - break; - } - } - - if (raterIndex != -1) - ratings[raterIndex].setSecond(r); - else { - Pair toPush(name, r); - ratings.pushBack(std::move(toPush)); - } -} - -void Book::print() const { - std::cout << title << " by: " << author << std::endl; -} - -Book::Book(const string& pAuthor, const string& pTitle) { - author = pAuthor; - title = pTitle; -} - -void Book::writeToFile(std::ofstream& outFile) const { - writeString(outFile, author); // Author - writeString(outFile, title); // Title - - // Write pages to file - int len = data.getSize(); - outFile.write((const char*)&len, sizeof(len)); - - for (size_t i = 0; i < len; i++) - data[i].writeToFile(outFile); - - // Write comments to file: - int commentsLen = comments.getSize(); - outFile.write((const char*)&commentsLen, sizeof(commentsLen)); - for (size_t i = 0; i < commentsLen; i++) - writeCommentsToFile(outFile, comments[i]); - - // Write rates to file: - int ratesCount = this->ratings.getSize(); - outFile.write((const char*)&ratesCount, sizeof(ratesCount)); - for (size_t i = 0; i < ratesCount; i++) - writeRatesToFile(outFile, ratings[i]); -} - -void Book::readFromFile(std::ifstream& inFile) { - author = readString(inFile); // Author - title = readString(inFile); // Title - - // Read pages: - int len = 0; - inFile.read((char*)&len, sizeof(len)); - - for (size_t i = 0; i < len; i++) { - data.pushBack(Page()); - data[i].readFromFile(inFile); - } - - // Read comments - int commentsLen = 0; - inFile.read((char*)&commentsLen, sizeof(commentsLen)); - - for (size_t i = 0; i < commentsLen; i++) { - Pair toInsert = readCommentsFromFile(inFile); - comments.pushBack(std::move(toInsert)); - } - - // Read rates from file - int ratesCount = 0; - inFile.read((char*)&ratesCount, sizeof(ratesCount)); - for (size_t i = 0; i < ratesCount; i++) { - Pair toPush = readRatesFromFile(inFile); - ratings.pushBack(std::move(toPush)); - } -} - -double Book::getAvarageRating() const { - double sum = 0; - for (size_t i = 0; i < ratings.getSize(); i++) - sum += ratings[i].getSecond(); - - return sum / (double)(ratings.getSize()); -} - -void Book::write(unsigned pagesCount) { - unsigned short lines = 0; - - for (int i = 0; i < pagesCount; i++) { - std::cout << "Enter lines in page " << i + 1 << ": "; - std::cin >> lines; - std::cin.ignore(); - Page toInsert; - - toInsert.write(lines); - - data.pushBack(std::move(toInsert)); - } -} - -void Book::displayBook() const { - bool reading = true; - bool displayMenu = true; - unsigned pageNumber = 0; - - char cmd = '\0'; - unsigned pageIndex = 0; - - while (reading) { - system("cls"); - if (displayMenu) - displayHelpMenu(); - - data[pageIndex].displayPage(); - - std::cin.get(cmd); - - switch (cmd) { - case 'n': - if (pageIndex < data.getSize() - 1) - pageIndex++; - break; - case 'p': - if (pageIndex > 0) - pageIndex--; - break; - case 'h': - displayMenu = !displayMenu; - break; - case 'q': - reading = false; - break; - case '@': - std::cin >> pageNumber; - if (pageNumber >= 1 && pageNumber < data.getSize() + 1) - pageIndex = pageNumber - 1; - break; - default: - break; - } - } - system("cls"); -} - -void Book::showComments() const { - for (size_t i = 0; i < comments.getSize(); i++) - std::cout << comments[i].getFirst() << " wrote: " << comments[i].getSecond() << std::endl; -} - -void Book::showRates() const { - for (size_t i = 0; i < ratings.getSize(); i++) - std::cout << ratings[i].getFirst() << ": " << ratings[i].getSecond() << " start" << std::endl; - std::cout << std::endl; - - std::cout << "Avarage rate: " << getAvarageRating() << std::endl; -} - -void Book::displayHelpMenu() const { - std::cout << "Entered reader mode." << std::endl - << "Press n for next, p for prev." << std::endl << - "Press @ + to go to that page" << std::endl << - "Press h to hide or show this menu or q to exit" << std::endl; -} diff --git a/Utills/Kindle/Book.h b/Utills/Kindle/Book.h deleted file mode 100644 index 29c4f13..0000000 --- a/Utills/Kindle/Book.h +++ /dev/null @@ -1,34 +0,0 @@ -#pragma once -#include"vector.hpp" -#include"Page.h" -#include"Pair.hpp" -#include"serialize.h" - -class Book { -private: - string author; - string title; - Vector> ratings; // User name + rate - Vector data; // Pages - Vector> comments; // commenter's name + comment - - void addRating(unsigned short r, const string& name); - - void write(unsigned pagesCount); - void displayBook() const; - - void showComments() const; - void showRates() const; - void print() const; - void displayHelpMenu() const; -public: - Book() {} - Book(const string& author, const string& title); - - void writeToFile(std::ofstream& outFile) const; - void readFromFile(std::ifstream& inFile); - double getAvarageRating() const; - - friend class Kindle; -}; - diff --git a/Utills/Kindle/Kindle.cpp b/Utills/Kindle/Kindle.cpp deleted file mode 100644 index 84477d2..0000000 --- a/Utills/Kindle/Kindle.cpp +++ /dev/null @@ -1,354 +0,0 @@ -#include "Kindle.h" - -void Kindle::displayUserDialog(User& currentUser) { - std::cout << "Wellcome, " << currentUser.name << std::endl; - string cmd; - - while (!(cmd == "exit")) { - std::cout << "> "; - std::cin >> cmd; - if (cmd == "read") { - readBookDialog(currentUser); - } - else if (cmd == "rate") { - rateBookDialog(currentUser); - } - else if (cmd == "comment") { - commentOnBookDialog(currentUser); - } - else if (cmd == "write") { - writeBookDialog(currentUser); - } - else if (cmd == "comments") { - displayCommentsDialog(); - } - else if (cmd == "view") { - viewBooks(); - } - else if (cmd == "rates") { - displayRatesDialog(); - } - } - - std::cout << "Exit user dialog" << std::endl; -} - -void Kindle::saveFileDialog() const { - string path; - std::cout << "Enter path: "; - std::cin >> path; - saveToFile(path.c_str()); -} - -void Kindle::readFileDialog() { - std::cout << "Enter path: "; - string path; - std::cin >> path; - readFromFile(path.c_str()); -} - -void Kindle::showHelpDialog() const { - std::cout << "Write one of the following commands and press enter: " << std::endl - << "| login | signup | load | saveas | view | exit" << std::endl << - "Press any key to exit" << std::endl; - std::cin.get(); - - std::cin.clear(); - std::cin.ignore(255, '\n'); -} - -void Kindle::saveToFile(const char* filePath) const { - std::ofstream outFile(filePath, std::ios::binary); - - if (!outFile) - return; - - outFile.write("#Ty", 4); - - size_t sizeOfLib = lib.getSize(); - size_t sizeOfUsers = users.getSize(); - // Write lib: - outFile.write((const char*)&sizeOfLib, sizeof(sizeOfLib)); - - for (size_t i = 0; i < sizeOfLib; i++) - lib[i].writeToFile(outFile); - - // Save users: - outFile.write((const char*)&sizeOfUsers, sizeof(sizeOfUsers)); - - for (size_t i = 0; i < sizeOfUsers; i++) - users[i].writeToFile(outFile); - - std::cout << "Saving success!" << std::endl; -} - -void Kindle::readFromFile(const char* filePath) { - std::ifstream inFile(filePath, std::ios::binary); - - if (!inFile) { - std::cout << "File does not exist" << std::endl; - return; - } - - char typeChecker[4]; - inFile.read(typeChecker, 4); - if (strcmp(typeChecker, "#Ty") != 0) { - std::cout << "Invalid file type" << std::endl; - return; - } - - size_t sizeOfLib = 0; - size_t sizeOfUsers = 0; - - // Read lib - inFile.read((char*)&sizeOfLib, sizeof(sizeOfLib)); - - for (size_t i = 0; i < sizeOfLib; i++) { - lib.pushBack(Book()); - lib[i].readFromFile(inFile); - } - - // Read users: - inFile.read((char*)&sizeOfUsers, sizeof(sizeOfUsers)); - - for (size_t i = 0; i < sizeOfUsers; i++) { - users.pushBack(User()); - users[i].readFromFile(inFile); - } - - std::cout << "Reading success!" << std::endl; -} - -int Kindle::findBookIndex(const string& name) const { - for (size_t i = 0; i < lib.getSize(); i++) - if (name == lib[i].title) - return i; - return -1; -} - -int Kindle::findUserIndex(const string& name) const { - for (size_t i = 0; i < users.getSize(); i++) - if (name == users[i].name) - return i; - return -1; -} - -bool Kindle::userReadTheBook(const User& currentUser, int bookIndex) const { - for (size_t i = 0; i < currentUser.indexesOfBooksRead.getSize(); i++) - if (currentUser.indexesOfBooksRead[i] == bookIndex) - return true; - return false; -} - -bool Kindle::existUser(const string& userName) const { - for (size_t i = 0; i < users.getSize(); i++) - if (userName == users[i].name) - return true; - return false; -} - -void Kindle::readBookDialog(User& reader) { - std::cout << "Which book would you like to read: "; - string bookName; - std::cin.ignore(); - bookName.getLine(std::cin); - - int indexOfBook = findBookIndex(bookName); - if (indexOfBook == -1) { - std::cout << "No such book" << std::endl; - return; - } - if (!(reader.name == lib[indexOfBook].author) && !userReadTheBook(reader, indexOfBook)) - reader.indexesOfBooksRead.pushBack(indexOfBook); - - lib[indexOfBook].displayBook(); -} - -void Kindle::rateBookDialog(const User& rater) { - std::cout << "Enter a book you'd line to rate: "; - string bookName; - std::cin.ignore(); - bookName.getLine(std::cin); - - int bookIndex = findBookIndex(bookName); - - if (bookIndex == -1) { - std::cout << "No such book" << std::endl; - return; - } - - if (rater.name == lib[bookIndex].author) { - std::cout << "You can't rate your own book" << std::endl; - return; - } - - unsigned short rate = 0; - std::cout << "Enter rate: "; - std::cin >> rate; - - lib[bookIndex].addRating(rate, rater.name); -} - -void Kindle::commentOnBookDialog(const User& commenter) { - std::cout << "Enter a book you would like to comment: "; - string bookName; - std::cin.ignore(); - bookName.getLine(std::cin);; - - int index = findBookIndex(bookName); - - if (index == -1) { - std::cout << "No such book"; - return; - } - - std::cout << "Enter comment: "; - string comment; - comment.getLine(std::cin); - if (commenter.name == lib[index].author || userReadTheBook(commenter, index)) { - Pair toAdd(commenter.name, std::move(comment)); - lib[index].comments.pushBack(std::move(toAdd)); - } - else { - std::cout << "You havent read the book" << std::endl; - return; - } -} - -void Kindle::writeBookDialog(User& writer) { - std::cout << "Enter title: "; - string title; - - std::cin.ignore(); - - title.getLine(std::cin); - - Book toAdd(writer.name, title); - - std::cout << "Enter pages count: "; - unsigned pagesCount = 0; - std::cin >> pagesCount; - - std::cin.ignore(); - - toAdd.write(pagesCount); - writer.indexesOfBooksWritten.pushBack(lib.getSize()); - lib.pushBack(std::move(toAdd)); -} - -void Kindle::displayCommentsDialog() const { - std::cout << "Enter book name: "; - string bookName; - std::cin.ignore(); - bookName.getLine(std::cin);; - - int indexOfBook = findBookIndex(bookName); - - if (indexOfBook == -1) { - std::cout << "No such book" << std::endl; - return; - } - - lib[indexOfBook].showComments(); -} - -void Kindle::displayRatesDialog() const { - std::cout << "Enter book name: "; - string bookName; - std::cin.ignore(); - bookName.getLine(std::cin); - - int indexOfBook = findBookIndex(bookName); - - if (indexOfBook == -1) { - std::cout << "No such book" << std::endl; - return; - } - - lib[indexOfBook].showRates(); -} - -void Kindle::viewBooks() const { - for (size_t i = 0; i < lib.getSize(); i++) - lib[i].print(); -} - -void Kindle::displayLoginDialog() { - std::cout << "Enter user name: "; - string userName; - - std::cin.ignore(); - - userName.getLine(std::cin); - - int userIndex = findUserIndex(userName); - - if (userIndex == -1) { - std::cout << "This user does not exist in our system\n"; - return; - } - string pwd; - std::cout << "Enter password: "; - - pwd.getLine(std::cin); - - if (!(pwd == users[userIndex].password)) { - std::cout << "Incorrect password.\n"; - return; - } - - displayUserDialog(users[userIndex]); -} - -void Kindle::displaySignupDialog() { - std::cout << "Enter name: "; - string name; - - std::cin.ignore(); - - name.getLine(std::cin); - - if (existUser(name)) { - std::cout << "User with that name already exist!" << std::endl; - return; - } - - std::cout << "Enter password: "; - string password; - password.getLine(std::cin); - - User toAdd(name, password); - users.pushBack(std::move(toAdd)); - std::cout << "Successful!" << std::endl; -} - - -void Kindle::display() { - string cmd; - while (!(cmd == "exit")) { - std::cout << "> "; - std::cin >> cmd; - - if (cmd == "login" || cmd == "log in") { - displayLoginDialog(); - } - else if (cmd == "signup" || cmd == "sign up") { - displaySignupDialog(); - } - else if (cmd == "view") { - viewBooks(); - } - else if (cmd == "load") { - readFileDialog(); - } - else if (cmd == "save") { - saveFileDialog(); - } - else if (cmd == "help") { - showHelpDialog(); - } - else { - std::cout << "Invalid command!" << std::endl; - } - } -} diff --git a/Utills/Kindle/Kindle.h b/Utills/Kindle/Kindle.h deleted file mode 100644 index 79bcbd3..0000000 --- a/Utills/Kindle/Kindle.h +++ /dev/null @@ -1,55 +0,0 @@ -#pragma once -#include"vector.hpp" -#include"Book.h" -#include"User.h" -#include"Pair.hpp" -#include -#include -#include - -class Kindle { -private: - Vector lib; - Vector users; - - // Helper functions - int findBookIndex(const string& name) const; - int findUserIndex(const string& name) const; - - // did user read the book? - bool userReadTheBook(const User& currentUser, int bookIndex) const; - - // does user exist? - bool existUser(const string& userName) const; - - // Functions used by user - void readBookDialog(User& reader); - void writeBookDialog(User& writer); - - void rateBookDialog(const User& rater); - void commentOnBookDialog(const User& commenter); - - void displayCommentsDialog() const; - void displayRatesDialog() const; - - // TODO: Change book (add or remove page etc.) - - // Functions used by main dialog - void displayLoginDialog(); - void displaySignupDialog(); - void displayUserDialog(User& currentUser); - - void saveFileDialog() const; - void readFileDialog(); - - void viewBooks() const; - void showHelpDialog() const; - - // read && write - void saveToFile(const char* filePath) const; - void readFromFile(const char* filePath); -public: - // The only function used by our Kindle class - void display(); -}; - diff --git a/Utills/Kindle/Page.cpp b/Utills/Kindle/Page.cpp deleted file mode 100644 index a905f25..0000000 --- a/Utills/Kindle/Page.cpp +++ /dev/null @@ -1,37 +0,0 @@ -#include "Page.h" - -void Page::write(unsigned linesCount) { - if (linesCount > MAX_LINES_IN_PAGE) - linesCount = MAX_LINES_IN_PAGE; - - - for (size_t i = 0; i < linesCount; i++) { - std::cout << i + 1 << " "; - lines.pushBack(string()); - - lines[i].getLine(std::cin); - } -} - -void Page::displayPage() const { - for (size_t i = 0; i < lines.getSize(); i++) - std::cout << lines[i] << std::endl; -} - -void Page::writeToFile(std::ofstream& outFile) const { - int len = lines.getSize(); - outFile.write((const char*)&len, sizeof(len)); - - for (size_t i = 0; i < len; i++) - writeString(outFile, lines[i]); -} - -void Page::readFromFile(std::ifstream& inFile) { - int len = 0; - inFile.read((char*)&len, sizeof(len)); - - for (size_t i = 0; i < len; i++) { - string s = readString(inFile); - lines.pushBack(std::move(s)); - } -} diff --git a/Utills/Kindle/Page.h b/Utills/Kindle/Page.h deleted file mode 100644 index e208691..0000000 --- a/Utills/Kindle/Page.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once -#include"vector.hpp" -#include"string.h" -#include -#include"serialize.h" - -const short MAX_LINES_IN_PAGE = 26; - -class Page { -private: - Vector lines; - - void write(unsigned linesCount); - void displayPage() const; - - void writeToFile(std::ofstream& outFile) const; - void readFromFile(std::ifstream& inFile); - - friend class Book; -}; - diff --git a/Utills/Kindle/Pair.hpp b/Utills/Kindle/Pair.hpp deleted file mode 100644 index 52859fe..0000000 --- a/Utills/Kindle/Pair.hpp +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -template -class Pair { - T first; - U second; -public: - Pair() { - first = T(); - second = U(); - } - Pair(const T& fst, const U& snd) : first(fst), second(snd) {} - - const T& getFirst() const { - return first; - } - - const U& getSecond() const { - return second; - } - - void setFirst(const T& arg) { - first = arg; - } - - void setSecond(const U& arg) { - second = arg; - } -}; \ No newline at end of file diff --git a/Utills/Kindle/Source.cpp b/Utills/Kindle/Source.cpp deleted file mode 100644 index 674cca7..0000000 --- a/Utills/Kindle/Source.cpp +++ /dev/null @@ -1,6 +0,0 @@ -#include"Kindle.h" - -int main() { - Kindle env; - env.display(); -} \ No newline at end of file diff --git a/Utills/Kindle/User.cpp b/Utills/Kindle/User.cpp deleted file mode 100644 index df1cea5..0000000 --- a/Utills/Kindle/User.cpp +++ /dev/null @@ -1,22 +0,0 @@ -#include "User.h" - -User::User(const string& pName, const string& pPassword) { - name = pName; - password = pPassword; -} - -void User::writeToFile(std::ofstream& outFile) const { - writeString(outFile, name); - writeString(outFile, password); - - writeVector(outFile, indexesOfBooksRead); - writeVector(outFile, indexesOfBooksWritten); -} - -void User::readFromFile(std::ifstream& inFile) { - name = readString(inFile); - password = readString(inFile); - - indexesOfBooksRead = readVector(inFile); - indexesOfBooksWritten = readVector(inFile); -} diff --git a/Utills/Kindle/User.h b/Utills/Kindle/User.h deleted file mode 100644 index f7c2dba..0000000 --- a/Utills/Kindle/User.h +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once -#include"string.h" -#include"vector.hpp" -#include"Book.h" -#include"serialize.h" - -class User { -private: - string name; - string password; - Vector indexesOfBooksRead; - Vector indexesOfBooksWritten; - - friend class Kindle; -public: - User() {} - User(const string& pName, const string& pPassword); - - void writeToFile(std::ofstream& outFile) const; - void readFromFile(std::ifstream& inFile); -}; - diff --git a/Utills/Kindle/readme.md b/Utills/Kindle/readme.md deleted file mode 100644 index d31119a..0000000 --- a/Utills/Kindle/readme.md +++ /dev/null @@ -1,66 +0,0 @@ -# Kindle - -## Помощни средства които използвахме -За решението на тази задача използваме клас string, клас vector и клас pair. String е взет директно от семинарите на първа група, с добавена функция getLine(), която използваме подобно на std::getline(); -Вектора е взет от семинарите на втора група. -Класът Pair е единствено с цел улеснение. Той представлява наредена двойка от два темплейтни типа. -Всяко едно нещо което сме направили с тези помощни средства може да се направи и без тях - просто кодът става по - дълъг. - -## Използване на командите -### Команди, които поддържаме преди да се логне потребител: -* login - влизаме в системата -* signup - регистрираме се в системата -* view - преглеждаме какви книги имаме -* save - запазваме текущия Kindle във файл -* load - зареждаме Kindle от файл -* exit - излизаме от системата -### Команди, които има потребител: -* read - прочита книга -* write - пише книга -* rate - оценява книга -* comment - коментира под книга -* rates - проверява рейтинга на книгата -* comments - проверява коментарите под книгата -* view - преглежда какви книги има -* exit - излиза от профила си -### Команди които имаме докато четем книга: -* n - следваща страница -* p - предишна страница -* @ + [number] - отива на страница, която е подадена -* h - показва/скрива help меню -* q - излиза от режим на четене - -Въвеждаме команда и натискаме Enter. След това програмата ни пита ако има нужда от допълнителна информация. Пример -``` -> login -> Enter user name: [Name] -> Enter user password: [Password] -> Success! -> -``` - -## Накратко за запазването във файлове -Имаме да запазваме сложна структура във файл. Това което можем да направим е да я разбием на по - прости. В Kindle имаме два вектора, които представляват книгите и потребителите. Ако измислим метод да запазим книга и потребител другото е лесно. Можете да видите, че в класовете представляващи книга и потребител имаме отделни функции, които се грижат за работата със запазването. -Логиката за тях е аналогична - разбиваме структурата на по - малки структурки, които стават все по - лесни и по - лесни за запазване. - -## Допълнителни бележки -В решението сме използвали friend класове. Това не винаги е лоша идея, но внимавайте с тях - възможно е да доведат до логически грешки, тоест на един клас да се дадат твърде много права над друг. - -При запазването на класа ще видите следния код -```cpp -outFile.write("#Ty", 4); -``` -При четенето на класа ще видите следния код -```cpp -char typeChecker[4]; -inFile.read(typeChecker, 4); -if (strcmp(typeChecker, "#Ty") != 0) { - std::cout << "Invalid file type" << std::endl; - return; -} -``` -Реално, няма как да гарантираме, че подадения файл ни е коректен. Потребителя винаги може да подаде некоректен файл, което може да счупи нашата система. За това правим следното: в началото на файла, който запазваме, записваме някаква последователност от n символа. Когато четем, прочитаме първите n (в случая 4) байта от файла и казваме - ако това е "тайният" низ, то значи този файл е писан от системата, тоест се очаква да е коректен. В противен случай приключваме изпълнението и не четем излишни данни, които могат да счупят системата ни. - -Също така, функционалността за промяна на книга оставяме на Вас. Чувствайте се свободни да експериментирате и pull-request вате. - -При каквито и да е въпроси екипът по ООП е на линия. \ No newline at end of file diff --git a/Utills/Kindle/serialize.cpp b/Utills/Kindle/serialize.cpp deleted file mode 100644 index af1e001..0000000 --- a/Utills/Kindle/serialize.cpp +++ /dev/null @@ -1,71 +0,0 @@ -#include"serialize.h" - -void writeString(std::ofstream& outFile, const string& str) { - int len = str.getSize(); - outFile.write((const char*)&len, sizeof(int)); - - outFile.write(str.c_str(), sizeof(char) * len); -} - -string readString(std::ifstream& inFile) { - int len = 0; - inFile.read((char*)&len, sizeof(len)); - - char* buff = new char[len + 1]; - inFile.read(buff, sizeof(char) * len); - - buff[len] = '\0'; - - string toReturn(buff); - - delete[] buff; - - return toReturn; -} - -void writeVector(std::ofstream& outFile, const Vector& v) { - int len = v.getSize(); - outFile.write((const char*)&len, sizeof(int)); - - for (size_t i = 0; i < v.getSize(); i++) - outFile.write((const char*)&v[i], sizeof(size_t)); -} - -Vector readVector(std::ifstream& inFile) { - int len = 0; - inFile.read((char*)&len, sizeof(int)); - Vector toReturn; - size_t read = 0; - - for (size_t i = 0; i < len; i++) { - inFile.read((char*)&read, sizeof(size_t)); - toReturn.pushBack(read); - } - - return toReturn; -} - -void writeCommentsToFile(std::ofstream& outFile, const Pair& p) { - writeString(outFile, p.getFirst()); - writeString(outFile, p.getSecond()); -} - -Pair readCommentsFromFile(std::ifstream& inFile) { - string fst = readString(inFile); - string snd = readString(inFile); - - return { fst, snd }; -} - -void writeRatesToFile(std::ofstream& outFile, const Pair& comments) { - writeString(outFile, comments.getFirst()); - outFile.write((const char*)&comments.getSecond(), sizeof(comments.getSecond())); -} - -Pair readRatesFromFile(std::ifstream& inFile) { - string fst = readString(inFile); - unsigned rate = 0; - inFile.read((char*)&rate, sizeof(rate)); - - return { fst, rate }; -} \ No newline at end of file diff --git a/Utills/Kindle/serialize.h b/Utills/Kindle/serialize.h deleted file mode 100644 index 02ebc3a..0000000 --- a/Utills/Kindle/serialize.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once -#include"string.h" -#include"vector.hpp" -#include"Pair.hpp" -#include - -void writeString(std::ofstream& outFile, const string& str); - -string readString(std::ifstream& inFile); - -void writeVector(std::ofstream& outFile, const Vector& v); - -Vector readVector(std::ifstream& inFile); -void writeCommentsToFile(std::ofstream& outFile, const Pair& p); - -Pair readCommentsFromFile(std::ifstream& inFile); - -void writeRatesToFile(std::ofstream& outFile, const Pair& comments); - -Pair readRatesFromFile(std::ifstream& inFile); \ No newline at end of file diff --git a/Utills/Kindle/string.cpp b/Utills/Kindle/string.cpp deleted file mode 100644 index cb79dfb..0000000 --- a/Utills/Kindle/string.cpp +++ /dev/null @@ -1,158 +0,0 @@ -#include "string.h" -#include -#include - -#pragma warning(disable : 4996) - -void string::copyFrom(const string& other) -{ - str = new char[strlen(other.str) + 1]; - strcpy(str, other.str); - size = other.size; -} -void string::free() -{ - delete[] str; -} - -string::string() -{ - str = new char[1]; - str[0] = '\0'; - size = 0; -} - -string::string(const char* data) -{ - if (data == nullptr) - { - str = new char[1]; - str[0] = '\0'; - size = 0; - } - else - { - size = strlen(data); - str = new char[size + 1]; - strcpy(str, data); - } -} - -string::string(const string& other) -{ - copyFrom(other); -} -string& string::operator=(const string& other) -{ - if (this != &other) - { - free(); - copyFrom(other); - } - return *this; -} -string::~string() -{ - free(); -} - - -size_t string::getSize() const -{ - return size; -} -void string::concat(const string& other) -{ - char* temp = new char[getSize() + other.getSize() + 1]; - strcpy(temp, str); - strcat(temp, other.str); - - delete[] str; - str = temp; - size = size + other.getSize(); -} - -const char* string::c_str() const -{ - return str; -} - -string& string::operator+=(const string& other) -{ - concat(other); - return *this; -} - -void string::getLine(std::istream& outFile) -{ - delete[] str; - char buff[1024]; - - outFile.getline(buff, 1024, '\n'); - size_t len = strlen(buff); - str = new char[len + 1]; - for (size_t i = 0; i < len; i++) - str[i] = buff[i]; - str[len] = '\0'; - size = len; -} - -string operator+(const string& lhs, const string& rhs) -{ - string copyOfLeft(lhs); - copyOfLeft += rhs; - return copyOfLeft; -} - -std::ostream& operator<<(std::ostream& stream, const string& str) -{ - stream << str.str; - return stream; -} - -std::istream& operator>>(std::istream& stream, string& str) -{ - delete[] str.str; - char buff[1024]; - stream >> buff; - - str.size = strlen(buff); - str.str = new char[str.size + 1]; - strcpy(str.str, buff); - - return stream; -} - -bool operator==(const string& lhs, const string& rhs) -{ - return strcmp(lhs.c_str(), rhs.c_str()) == 0; -} -bool operator<=(const string& lhs, const string& rhs) -{ - return strcmp(lhs.c_str(), rhs.c_str()) <= 0; - -} -bool operator<(const string& lhs, const string& rhs) -{ - return strcmp(lhs.c_str(), rhs.c_str()) < 0; - -} - -string::string(string&& otherString) -{ - str = otherString.str; - size = otherString.size; - otherString.str = nullptr; -} - -string& string::operator=(string&& otherString) -{ - if (this != &otherString) - { - free(); - str = otherString.str; - otherString.str = nullptr; - size = otherString.size; - } - return *this; -} \ No newline at end of file diff --git a/Utills/Kindle/string.h b/Utills/Kindle/string.h deleted file mode 100644 index d5a06be..0000000 --- a/Utills/Kindle/string.h +++ /dev/null @@ -1,42 +0,0 @@ -#pragma once - -#include -#include -class string -{ - char* str; - size_t size; - - void copyFrom(const string& other); - void free(); - -public: - string(); - string(const char*); - - string(const string&); - - string(string&&); //move constructor that accepts rvalue; - - string& operator=(const string& other); - string& operator=(string&& other); //move op= that accepts rvalue; - - ~string(); - - size_t getSize() const; - void concat(const string& other); - - const char* c_str() const; - - string& operator+=(const string& other); - - friend std::ostream& operator<<(std::ostream& stream, const string& str); - friend std::istream& operator>>(std::istream& stream, string& str); - void getLine(std::istream& out); -}; - -string operator+(const string& lhs, const string& rhs); - -bool operator==(const string& lhs, const string& rhs); -bool operator<=(const string& lhs, const string& rhs); -bool operator<(const string& lhs, const string& rhs); \ No newline at end of file diff --git a/Utills/Kindle/vector.hpp b/Utills/Kindle/vector.hpp deleted file mode 100644 index 1afb2a5..0000000 --- a/Utills/Kindle/vector.hpp +++ /dev/null @@ -1,239 +0,0 @@ -#pragma once -#include -const size_t DEFAULT_CAPACITY = 4; - -template -class Vector { -private: - T* data; - size_t size; - size_t capacity; -public: - Vector(); - Vector(const Vector&); - Vector(Vector&&); - Vector& operator=(const Vector&); - Vector& operator=(Vector&&); - ~Vector(); - - size_t getSize() const; - size_t getCapacity() const; - - void pushBack(const T&); - void pushBack(T&& n); - void pushAt(const T&, const size_t); - void pushAt(T&&, const size_t); - T& popBack(); - T& popAt(const size_t); - T& operator[](const size_t); - const T& operator[](const size_t) const; - bool empty() const; - void clear(); - void swap(const Vector&); -private: - void copy(const Vector&); - void free(); - void move(Vector&&); - - size_t calculateCapacity(const size_t) const; - void resize(const size_t); -}; - -template -Vector::Vector() { - data = nullptr; - capacity = size = 0; -} - -template -Vector::Vector(const Vector& other) { - copy(other); -} - -template -Vector::Vector(Vector&& other) { - move(std::move(other)); -} - -template -Vector& Vector::operator=(const Vector& other) { - if (this != &other) - { - free(); - copy(other); - } - - return *this; -} - -template -Vector& Vector::operator=(Vector&& other) { - if (this != &other) - { - free(); - move(std::move(other)); - } - - return *this; -} - -template -Vector::~Vector() { - free(); -} - -template -size_t Vector::getSize() const { - return size; -} - -template -size_t Vector::getCapacity() const { - return capacity; -} - -template -void Vector::pushBack(const T& element) { - if (size + 1 > capacity) - resize(size + 1); - - data[size++] = element; -} - - -template -void Vector::pushBack(T&& element) { - if (size + 1 > capacity) - resize(size + 1); - - data[size++] = element; -} - -template -void Vector::pushAt(const T& element, const size_t index) { - if (size + 1 > capacity) - resize(size + 1); - - for (size_t i = size; i > index; i--) - data[i] = data[i - 1]; - - data[index] = element; - size++; -} - -template -void Vector::pushAt(T&& element, const size_t index) { - if (size + 1 > capacity) - resize(size + 1); - - for (size_t i = size; i > index; i--) - data[i] = data[i - 1]; - - data[index] = element; - size++; -} - -template -T& Vector::popBack() { - if (empty()) - throw "Vector is empty"; - - return data[--size]; -} - -template -T& Vector::popAt(size_t index) { - if (index < 0 || index >= size) - throw "Invalid index"; - - T temp = data[index]; - for (size_t i = index; i < size - 1; i++) - data[i] = data[i + 1]; - - size--; - return temp; -} - -template -T& Vector::operator[](const size_t index) { - if (index < 0 || index >= size) - throw "Invalid index"; - - return data[index]; -} - -template -const T& Vector::operator[](const size_t index) const { - if (index < 0 || index >= size) - throw "Invalid index"; - - return data[index]; -} - -template -bool Vector::empty() const { - return size == 0; -} - -template -void Vector::clear() { - delete[] data; - capacity = DEFAULT_CAPACITY; - data = new T[capacity]; - size = 0; -} - -template -void Vector::swap(const Vector& other) { - Vector tempVector(std::move(*this)); - *this = std::move(other); - other = std::move(tempVector); -} - -template -void Vector::copy(const Vector& other) { - size = other.size; - capacity = other.capacity; - data = new T[capacity]; - - for (size_t i = 0; i < size; i++) - data[i] = other[i]; -} - -template -void Vector::free() { - delete[] data; - data = nullptr; - capacity = size = 0; -} - -template -void Vector::move(Vector&& other) -{ - data = other.data; - size = other.size; - capacity = other.capacity; - - other.data = nullptr; - other.capacity = other.size = 0; -} -template -size_t Vector::calculateCapacity(const size_t number) const { - size_t result = DEFAULT_CAPACITY; - while (number > result) - result *= 2; - - return result; -} - -template -void Vector::resize(const size_t expectedCapacityToFit) { - capacity = calculateCapacity(expectedCapacityToFit); - T* temp = new T[capacity]; - - for (size_t i = 0; i < size; i++) - temp[i] = data[i]; - - delete[] data; - data = temp; -} \ No newline at end of file diff --git "a/Utills/homework_1_SI/\320\224\320\276\320\274\320\260\321\210\320\275\320\260_\321\200\320\260\320\261\320\276\321\202\320\260_1.pdf" "b/Utills/homework_1_SI/\320\224\320\276\320\274\320\260\321\210\320\275\320\260_\321\200\320\260\320\261\320\276\321\202\320\260_1.pdf" deleted file mode 100644 index a7a27ba..0000000 Binary files "a/Utills/homework_1_SI/\320\224\320\276\320\274\320\260\321\210\320\275\320\260_\321\200\320\260\320\261\320\276\321\202\320\260_1.pdf" and /dev/null differ diff --git a/Utills/k_1_SI/task1.cpp b/Utills/k_1_SI/task1.cpp deleted file mode 100644 index 77ad5f5..0000000 --- a/Utills/k_1_SI/task1.cpp +++ /dev/null @@ -1,138 +0,0 @@ -#include -#include -#include - -using namespace std; - -struct Point -{ - int x; - int y; - Point() : Point(0,0){} - - Point(int x, int y) - { - this->x = x; - this->y = y; - } - - double getDistance(const Point& other) const - { - int dx = x - other.x; - int dy = y - other.y; - return sqrt(dx * dx + dy * dy); - } -}; - -void print(const Point& p) -{ - std::cout << "[ x: " << p.x << ", y: " << p.y <<" ]"; -} - -struct Rectangle -{ -private: - Point points[4]; - -public: - Rectangle() = default; //the same as Rectangle() {} - - void setPoint(size_t index, int x, int y) - { - if(index > 3) - return; - - points[index].x = x; - points[index].y = y; - - } - const Point& getPoint(size_t index) const - { - if(index > 3) - return {}; //some Error. This is a refference to a temporary memory, so a better solution would be to throw an exception. - return points[index]; - } - double getPer() const - { - return 2 * points[0].getDistance(points[1]) + 2 * points[1].getDistance(points[2]); - } -}; - -void print(const Rectangle& rect) -{ - for(int i = 0; i < 4; i++) - { - print(rect.getPoint(i)); - } -} - -void swap(Rectangle& tr1, Rectangle& tr2) -{ - Rectangle temp = tr1; - tr1 = tr2; - tr2 = temp; -} - -void selectionSort(Rectangle* triangles, double* perimeters, unsigned size) -{ - for (unsigned i = 0; i < size - 1; i++) - { - //findMin - int minElementIndex = i; - for (unsigned j = i + 1; j < size; j++) - { - if (perimeters[j] < perimeters[minElementIndex]) - minElementIndex = j; - } - - if (minElementIndex != i) - { - swap(perimeters[i], perimeters[minElementIndex]); - swap(triangles[i], triangles[minElementIndex]); - } - } -} - -int main() -{ - ifstream file("rects.txt"); - - if(!file.is_open()) - { - std::cout << "Error while opening the file!"; - return -1; - } - - int n; - file >> n; - - Rectangle* rects = new Rectangle[n]; - double* perimeters = new double[n]; //this should be size_t, but we are using a double returning function for getDist. - - for(size_t i = 0; i < n; i++) - { - int x1, y1, x3, y3; - file >> x1 >> y1 >> x3 >> y3; - - rects[i].setPoint(0, x1, y1); - rects[i].setPoint(1, x1, y3); - rects[i].setPoint(2, x3, y3); - rects[i].setPoint(3, x3, y1); - - perimeters[i] = rects[i].getPer(); - - } - - selectionSort(rects, perimeters, n); //selection sort, because we want min number of copies (or swaps) - - for(size_t i = 0; i < n; i++) - { - print(rects[i]); - std::cout <<", Per: " << perimeters[i] << std::endl; - } - - - delete[] rects, perimeters; - return 0; -} - diff --git a/Utills/k_1_SI/task2_read.cpp b/Utills/k_1_SI/task2_read.cpp deleted file mode 100644 index e6a8312..0000000 --- a/Utills/k_1_SI/task2_read.cpp +++ /dev/null @@ -1,55 +0,0 @@ -#include -#include -#include -using namespace std; - -const size_t MAX_NAME_SIZE = 22; -struct Student -{ - //gender should be BEFORE fn so the struct would be 28 bytes. - char name[MAX_NAME_SIZE + 1]; - bool isMale; - size_t fn; -}; - - -size_t getFileSize(ifstream& f) -{ - size_t currentPos = f.tellg(); - f.seekg(0, ios::end); - size_t size = f.tellg(); - - f.seekg(currentPos); - return size; -} - -void readFromFile(Student*& ptr, size_t& studentsCount, ifstream& f) -{ - size_t sizeOfFile = getFileSize(f); - studentsCount = sizeOfFile / sizeof(Student); - ptr = new Student[studentsCount]; - f.read((char*)ptr, sizeOfFile); -} - - -int main() -{ - Student* arr; - size_t count; - ifstream file("students.dat"); - - if(!file.is_open()) - { - std::cout << "Error while opening the file!" << std::endl; - return -1; - } - - readFromFile(arr, count, file); - - for (int i = 0; i < count; i++) - std::cout << "Name: " << arr[i].name << ", fn: " << arr[i].fn << ", is male: " << arr[i].isMale << std::endl; - - delete[] arr; - - return 0; -} diff --git a/Utills/k_1_SI/task2_write.cpp b/Utills/k_1_SI/task2_write.cpp deleted file mode 100644 index f320557..0000000 --- a/Utills/k_1_SI/task2_write.cpp +++ /dev/null @@ -1,84 +0,0 @@ -#include -#include -#include -using namespace std; - -const size_t MAX_NAME_SIZE = 22; -struct Student -{ - //gender should be BEFORE fn so the struct would be 28 bytes. - char name[MAX_NAME_SIZE + 1]; - bool isMale; - size_t fn; -}; - -bool isLower(char ch) -{ - return ch >= 'a' && ch <= 'z'; -} - -bool areAllLowerCase(const char* str) -{ - while(*str) - { - if(!isLower(*str)) - return false; - str++; - } - return true; -} - -bool isUpper(char ch) -{ - return ch >= 'A' && ch <= 'Z'; -} - -bool isNameValid(const char* name) -{ - size_t len = strlen(name); - if(len == 0 || len > MAX_NAME_SIZE) - return false; - return isUpper(*name) && areAllLowerCase(name + 1); -} - -void initStudent(Student& st, const char* name, size_t fn, bool isMale) -{ - if(!isNameValid(name)) - strcpy(st.name, "Unknown"); - else - strcpy(st.name, name); - - st.isMale = isMale; - st.fn = fn; -} - -void saveToFile(const Student* students, size_t count, ofstream& file) -{ - file.write((const char*)students, count * sizeof(Student)); -} - - -int main() -{ - const size_t studentsCount = 4; - Student* arr = new Student[studentsCount]; - initStudent(arr[0], "Ivan", 1, true); - initStudent(arr[1], "Petur", 2, true); - initStudent(arr[2], "Alex", 3, true); - initStudent(arr[3], "Katerina", 4, false); - - ofstream file("students.dat", ios::binary); - - if(!file.is_open()) - { - std::cout << "Error while opening the file!" << std::endl; - delete[] arr; //! - return -1; - } - - saveToFile(arr, studentsCount, file); - - delete[] arr; - - return 0; -} diff --git "a/Utills/\320\242\320\265\320\274\320\270 \320\267\320\260 \321\203\321\201\321\202\320\265\320\275 \320\270\320\267\320\277\320\270\321\202 - \320\236\320\236\320\237, \320\241\320\230, 2022" "b/Utills/\320\242\320\265\320\274\320\270 \320\267\320\260 \321\203\321\201\321\202\320\265\320\275 \320\270\320\267\320\277\320\270\321\202 - \320\236\320\236\320\237, \320\241\320\230, 2022" deleted file mode 100644 index b818c71..0000000 --- "a/Utills/\320\242\320\265\320\274\320\270 \320\267\320\260 \321\203\321\201\321\202\320\265\320\275 \320\270\320\267\320\277\320\270\321\202 - \320\236\320\236\320\237, \320\241\320\230, 2022" +++ /dev/null @@ -1,29 +0,0 @@ -Теми за устен изпит - ООП, СИ, 2022 - -Тема 1: Структури и обединения. Представяния в паметта. Размер на обекти/истанции. Подравняване. Подаване на обекти/истанции във функции. Създаване на обекти в динамичната памет. Пример с задачата за N тригъгълника. - -Тема 2: Текстови файлове. Йерархия на потоците. Потоци за вход/изход от файл. Режими на работа. Флагове на състоянията на потока. Позициониране във файл. Пример за функция, която връща големината на файл. Пример за функция, която връща брой редове в текстов файл. - -Тема 3: Двоични файлове. Big endian. Запазване на обекти в двоичен файл. Пример за запазване/четене на масив от обекти(от един тип) във файл. - -Тема 4: Член-функции. Конструктори и деструктор. Извикване на конструктори и деструктори. Конструктори и деструктор при композиция на обекти. Mодификатори за достъп. Капсулация. Пример за клас Person с име (низ с дължина най-много 20 символа) и години [5...90]. - -Тема 5: Разделна компилация. Копиращ конструктор и оператор=. - -Тема 6: Динамична памет в класовете. Голямата четворка. Пример за клас студент с име (с произволна дължина) и масив от оценки(с произволна дъжина) - -Тема 7: Предефиниране на оператори. Приятелски класове и функции. Пример за реализация на комплексно число и Nvector. - -Тема 8: Масиви от указатели към обекти. Изключения. Обработка на изключения. Проблеми при работа с потоци. Move семантики - ползи, lvalue, rvalue, move конструктор/оп=, std::move. - -Тема 9: Конвертиращи конструктори. Композиция и агрегация. Шаблони. Пример за шаблонна опашка. Необходими функции в шаблонен клас/шаблонна функция. - -Тема 10: Наследяване. Видове наследяване. Параметри на функции (указатели и референции). Конструктури и деструктори при наследяване. Копиране при наследяване. Пример с човек, студент и преподавател. - -Тема 11: Статично и динамично свързване. Виртуални функции. Полиморфизъм. Абстрактни класове. Пример за фигури. - -Тема 12: Колекции от обекти в полиморфна йерархия. Копиране и триене. Factory pattern. Пример с ферма. - -Тема 13: Множествено наследяване. Проблеми при множествено наследяване. Диамантен проблем. Пример с шах. - -Тема 14: Дървовидна структура от обекти от полиморфна йерархия. Пример с логически изрази. diff --git "a/Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Source.cpp" "b/Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Source.cpp" deleted file mode 100644 index 17e6f4e..0000000 --- "a/Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Source.cpp" +++ /dev/null @@ -1,12 +0,0 @@ -#include -#include"chatSystem.h" - -int main() { - chatSystem data; - - data.addUser({ "Ivan", "1234", "iv@abv.bg" }); - data.addUser({ "Qvor", "4321", "qv@abv.bg" }); - - data.sendMessage("last example", "Ivan", "Qvor"); - data.viewMessages("Qvor", "Ivan"); -} \ No newline at end of file diff --git "a/Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Task1/LogFile.cpp" "b/Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Task1/LogFile.cpp" deleted file mode 100644 index 7be397b..0000000 --- "a/Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Task1/LogFile.cpp" +++ /dev/null @@ -1,92 +0,0 @@ -#include "LogFile.h" - -void LogFile::readTime(std::ifstream& inFile, Timestamp& obj) const { - char isLogin; - - inFile >> isLogin; - - obj.isLogin = (isLogin == '+'); - - inFile >> obj.hour >> obj.minutes >> obj.seconds; -} - - -LogFile::LogFile() { - size = 0; -} - -LogFile::LogFile(const char* filePath) { - std::ifstream inFile(filePath); - - if (!inFile.is_open()) { - size = 0; - return; - } - - inFile >> size; - - for (int i = 0; i < size; i++) - readTime(inFile, data[i]); -} - - -int LogFile::getLoginsCountAfterHour(short hours, short minutes, short seconds) const { - int ctr = 0; - int totalSeconds = hours * 3600 + minutes * 60 + seconds; - for (int i = 0; i < size; i++) { - if (data[i].toSeconds() > totalSeconds) { - ctr = i + 1; - break; - } - } - - return size - ctr; -} - -int LogFile::getLoginsCountBetweenHours(short h1, short m1, short s1, short h2, short m2, short s2) const { - return getLoginsCountAfterHour(h1, m1, s1) - getLoginsCountAfterHour(h2, m2, s2); -} - -int LogFile::getLongestActivePeriod() const { - int max = 0; - bool isFirstLogOut = !data[0].isLogin; - bool isLastLogIn = data[size - 1].isLogin; - - if (isFirstLogOut) - max = data[0].toSeconds(); - - if (isLastLogIn) { - int lastTimeInterval = 23 * 3600 + 59 * 60 + 59 - data[size - 1].toSeconds(); - - if (max < lastTimeInterval) - max = lastTimeInterval; - } - - for (int i = isFirstLogOut; i < size - isLastLogIn; i += 2) { - int diff = data[i + 1].toSeconds() - data[i].toSeconds(); - if (diff > max) - max = diff; - } - - return max; -} - -bool LogFile::loggedInHour(int hour) const { - int left = 0; - int right = size-1; - - while (left <= right) { - int mid = left + (right - left) / 2; - if (hour == data[mid].hour) { - return true; - } - - if (hour < data[mid].hour) { - right = mid - 1; - } - else { - left = mid + 1; - } - } - return false; -} \ No newline at end of file diff --git "a/Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Task1/LogFile.h" "b/Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Task1/LogFile.h" deleted file mode 100644 index 258c7d5..0000000 --- "a/Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Task1/LogFile.h" +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once -#include -#include "Timestamp.h" -const int MAX_FILE_SIZE = 100; -class LogFile { -private: - size_t size; - Timestamp data[MAX_FILE_SIZE]; - - void readTime(std::ifstream& inFile, Timestamp& obj) const; - -public: - LogFile(); - - LogFile(const char* filePath); - - int getLoginsCountAfterHour(short hours, short minutes, short seconds) const; - - int getLoginsCountBetweenHours(short h1, short m1, short s1, short h2, short m2, short s2) const; - - int getLongestActivePeriod() const; - - bool loggedInHour(int hour) const; -}; \ No newline at end of file diff --git "a/Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Task1/Timestamp.cpp" "b/Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Task1/Timestamp.cpp" deleted file mode 100644 index 28ff933..0000000 --- "a/Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Task1/Timestamp.cpp" +++ /dev/null @@ -1,5 +0,0 @@ -#include "Timestamp.h" - -int Timestamp::toSeconds() const{ - return hour * 3600 + minutes * 60 + seconds; -} \ No newline at end of file diff --git "a/Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Task1/Timestamp.h" "b/Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Task1/Timestamp.h" deleted file mode 100644 index e437187..0000000 --- "a/Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Task1/Timestamp.h" +++ /dev/null @@ -1,9 +0,0 @@ -#pragma once -struct Timestamp { - bool isLogin; - unsigned short hour; - unsigned short minutes; - unsigned short seconds; - - int toSeconds() const; -}; \ No newline at end of file diff --git "a/Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/User.cpp" "b/Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/User.cpp" deleted file mode 100644 index 998b91f..0000000 --- "a/Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/User.cpp" +++ /dev/null @@ -1,97 +0,0 @@ -#include "User.h" -#include -#include -#include - -#pragma warning(disable : 4996) - -void generatePath(char* path, const char* bigger, const char* smaller) { - strcpy(path, bigger); - strcat(path, "-"); - strcat(path, smaller); - strcat(path, ".bat"); -} - -void User::createFileName(char* fileName, const User& other) const { - if (strcmp(name, other.name) == 1) { - generatePath(fileName, name, other.name); - } - else { - generatePath(fileName, other.name, name); - } -} - -User::User() : name(""), password(""), email(""){} - -User::User(const char* n, const char* pass, const char* mail) { - if (strlen(n) > NAME_LEN || strlen(pass) > PASS_LEN || strlen(mail) > MAIL_LEN) { - strcpy(name, ""); - strcpy(password, ""); - strcpy(email, ""); - - return; - } - - strcpy(name, n); - strcpy(password, pass); - strcpy(email, mail); -} - -void User::sendMessage(const char* message, const User& other) const { - char filePath[50]; - createFileName(filePath, other); - - std::ofstream outFile(filePath, std::ios::binary | std::ios::app); - - if (!outFile.is_open()) - return; - - outFile.write(name, sizeof(name)); - - int length = strlen(message); - - outFile.write((const char*)&length, sizeof(length)); - - outFile.write(message, length); - - outFile.close(); -} - -void User::viewMessage(const User& other) const { - char filePath[50]; - createFileName(filePath, other); - - std::ifstream inFile(filePath, std::ios::binary); - - if (!inFile.is_open()) - return; - - char buff[NAME_LEN + 1]; - - while (!inFile.eof()) { - inFile.read(buff, sizeof(buff)); - - if (inFile.eof()) - return; - - int length = 0; - - inFile.read((char*)&length, sizeof(length)); - - char* msg = new char[length + 1]; - - inFile.read(msg, length); - - msg[length] = '\0'; - - std::cout << buff << ": " << msg << std::endl; - - delete[] msg; - } - - inFile.close(); -} - -const char* User::getName() const { - return name; -} diff --git "a/Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/User.h" "b/Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/User.h" deleted file mode 100644 index 4f94c7f..0000000 --- "a/Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/User.h" +++ /dev/null @@ -1,26 +0,0 @@ -#pragma once - -const int NAME_LEN = 20; -const int MAIL_LEN = 12; -const int PASS_LEN = 8; - -class User { -private: - // N символа за име +1 за терминираща нула! - char name[NAME_LEN + 1]; - char password[PASS_LEN + 1]; - char email[MAIL_LEN + 1]; - - void createFileName(char* fileName, const User& other) const; -public: - User(); - - User(const char* n, const char* pass, const char* email); - - void sendMessage(const char* message, const User& u) const; - - void viewMessage(const User& u) const; - - const char* getName() const; -}; - diff --git "a/Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/chatSystem.cpp" "b/Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/chatSystem.cpp" deleted file mode 100644 index c982451..0000000 --- "a/Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/chatSystem.cpp" +++ /dev/null @@ -1,80 +0,0 @@ -#include "chatSystem.h" -#include -#include - -void chatSystem::save() const { - std::ofstream outFile(FILE_PATH, std::ios::binary); - - outFile.write((const char*)this, sizeof(chatSystem)); -} - -void chatSystem::read() { - std::ifstream inFile(FILE_PATH, std::ios::binary); - - inFile.read((char*)this, sizeof(chatSystem)); -} - -void chatSystem::searchIndexes(int& firstIndex, int& secondIndex, const char* fstName, const char* sndName) const { - for (int i = 0; i < size; i++) { - if (strcmp(fstName, data[i].getName()) == 0) { - firstIndex = i; - } - - if (strcmp(sndName, data[i].getName()) == 0) { - secondIndex = i; - } - - if (firstIndex != -1 && secondIndex != -1) - break; - } -} - -chatSystem::chatSystem() { - size = 0; - read(); -} - -void chatSystem::addUser(const User& arg) { - if (size > 99) - return; - - for (int i = 0; i < size; i++) { - if (strcmp(arg.getName(), data[i].getName()) == 0) { - return; - } - } - - data[size++] = arg; -} - -void chatSystem::sendMessage(const char* msg, const char* fstName, const char* sndName) const { - int firstIndex = -1; - int secondIndex = -1; - - searchIndexes(firstIndex, secondIndex, fstName, sndName); - - if (firstIndex == -1 || secondIndex == -1) - return; - - data[firstIndex].sendMessage(msg, data[secondIndex]); -} - -void chatSystem::viewMessages(const char* fstName, const char* sndName) const { - int firstIndex = -1; - int secondIndex = -1; - - searchIndexes(firstIndex, secondIndex, fstName, sndName); - - if (firstIndex == -1 || secondIndex == -1) - return; - - data[firstIndex].viewMessage(data[secondIndex]); -} - -int chatSystem::getSize() const { - return size; -} - -chatSystem::~chatSystem() { - save(); -} diff --git "a/Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/chatSystem.h" "b/Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/chatSystem.h" deleted file mode 100644 index 1f21bf3..0000000 --- "a/Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/chatSystem.h" +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once -#include"User.h" - -const char FILE_PATH[] = "database.bat"; - -class chatSystem { -private: - User data[100]; - size_t size; - - void save() const; - - void read(); - - void searchIndexes(int& firstIndex, int& secondIndex, const char* fstName, const char* sndName) const; - -public: - chatSystem(); - - void addUser(const User& arg); - - void sendMessage(const char* msg, const char* fstName, const char* sndName) const; - - void viewMessages(const char* sender, const char* reciever) const; - - int getSize() const; - - ~chatSystem(); - -}; - diff --git "a/Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/\320\267\320\260\320\264\320\260\321\207\320\270 \320\267\320\260 \320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265 \320\241\320\230.pdf" "b/Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/\320\267\320\260\320\264\320\260\321\207\320\270 \320\267\320\260 \320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265 \320\241\320\230.pdf" deleted file mode 100644 index 111878f..0000000 Binary files "a/Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/\320\267\320\260\320\264\320\260\321\207\320\270 \320\267\320\260 \320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265 \320\241\320\230.pdf" and /dev/null differ diff --git "a/Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/\321\204\321\203\320\275\320\272\321\206\320\270\320\270 \320\276\321\202 \320\277\320\276 - \320\262\320\270\321\201\320\276\320\272 \321\200\320\265\320\264/demo.cpp" "b/Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/\321\204\321\203\320\275\320\272\321\206\320\270\320\270 \320\276\321\202 \320\277\320\276 - \320\262\320\270\321\201\320\276\320\272 \321\200\320\265\320\264/demo.cpp" deleted file mode 100644 index 951b7d2..0000000 --- "a/Utills/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/\321\204\321\203\320\275\320\272\321\206\320\270\320\270 \320\276\321\202 \320\277\320\276 - \320\262\320\270\321\201\320\276\320\272 \321\200\320\265\320\264/demo.cpp" +++ /dev/null @@ -1,89 +0,0 @@ -#include -#include - -template -class Entity { -private: - int integerData; - char symbolData; - T abstractData; - -public: - Entity(int iArg, char cArg, const T& aArg) : integerData(iArg), symbolData(cArg), abstractData(aArg) {} - - int getIntegerData() const { - return integerData; - } - - char getCharData() const { - return symbolData; - } - - const T& getAbstractData() const { - return abstractData; - } - - void print() const { - std::cout << integerData << " " << symbolData << " " << abstractData << std::endl; - } -}; - -template -bool compareIntegerValues(const Entity& fst, const Entity& snd) { - return fst.getIntegerData() < snd.getIntegerData(); -} - -template -bool compareCharValues(const Entity& fst, const Entity& snd) { - return fst.getCharData() < snd.getCharData(); -} - -template -bool compareAbstractValues(const Entity& fst, const Entity& snd) { - return fst.getAbstractData() < snd.getAbstractData(); -} - -template -void sort(std::vector>& collection, bool (*lessThan)(const Entity&, const Entity&)) { - for (size_t i = 0; i < collection.size(); i++) { - size_t minElementIndex = i; - - for (size_t j = i + 1; j < collection.size(); j++) { - if (lessThan(collection[j], collection[minElementIndex])) { - minElementIndex = j; - } - } - - if (minElementIndex != i) - std::swap(collection[i], collection[minElementIndex]); - } -} - -char generateRandomLetter() { - return (char)(rand() % 26 + 'a'); -} - -double generateRandomDouble() { - return (double)rand() / RAND_MAX + rand() % 256; -} - -int main() { - std::vector> collection; - - for (size_t i = 0; i < 100; i++) - collection.push_back({ rand() % 10000, generateRandomLetter(), generateRandomDouble() }); - - - // Sort integer values - // sort(collection, compareIntegerValues); - - // Sort char values - // sort(collection, compareCharValues); - - // Sort abstract values - sort(collection, compareAbstractValues); - - - for (size_t i = 0; i < 100; i++) - collection[i].print(); -} diff --git a/Utils/BigFour.cpp b/Utils/BigFour.cpp new file mode 100644 index 0000000..383440d --- /dev/null +++ b/Utils/BigFour.cpp @@ -0,0 +1,89 @@ + +#include +#include + +using namespace std; + +class Student +{ + char* name; + int* grades; + size_t gradesSize; + + void free() + { + delete[] name, grades; + } + + void copyFrom(const Student& other) + { + setName(other.name); + setGrades(other.grades); + } + + public: + + Student() : name(nullptr), grades(nullptr) {} + + Student(const Student& other) + { + copyFrom(other); + } + + Student& operator=(const Student& other) + { + if (this != &other) + { + free(); + copyFrom(other); + } + return *this; + } + + ~Student() + { + free(); + } + + const char* getName() const + { + return name; + } + + const int* getGrades() const + { + return grades; + } + + void setName(const char* givenName) + { + if(givenName == nullptr || givenName == name) + return; + delete[] name; + name = new char[strlen(givenName) + 1]; + strcpy(name, givenName); + } + + void setGrades(const int* givenGrades, size_t size) + { + if(givenGrades == nullptr || givenGrades == grades) + return; + + delete[] grades; + + grades = new int[size]; + for(size_t i = 0; i< size; i++) + grades[i] = givenGrades[i]; + gradesSize = size; + } + + +}; + +int main() +{ + + + return 0; +} + diff --git a/Utils/Kindle/Book.cpp b/Utils/Kindle/Book.cpp new file mode 100644 index 0000000..96b718d --- /dev/null +++ b/Utils/Kindle/Book.cpp @@ -0,0 +1,174 @@ +#include "Book.h" +#include + +void Book::addRating(unsigned short r, const string& name) { + if (r > 10) + return; + + int raterIndex = -1; + + for (size_t i = 0; i < ratings.getSize(); i++) { + if (name == ratings[i].getFirst()) { + raterIndex = i; + break; + } + } + + if (raterIndex != -1) + ratings[raterIndex].setSecond(r); + else { + Pair toPush(name, r); + ratings.pushBack(std::move(toPush)); + } +} + +void Book::print() const { + std::cout << title << " by: " << author << std::endl; +} + +Book::Book(const string& pAuthor, const string& pTitle) { + author = pAuthor; + title = pTitle; +} + +void Book::writeToFile(std::ofstream& outFile) const { + writeString(outFile, author); // Author + writeString(outFile, title); // Title + + // Write pages to file + int len = data.getSize(); + outFile.write((const char*)&len, sizeof(len)); + + for (size_t i = 0; i < len; i++) + data[i].writeToFile(outFile); + + // Write comments to file: + int commentsLen = comments.getSize(); + outFile.write((const char*)&commentsLen, sizeof(commentsLen)); + for (size_t i = 0; i < commentsLen; i++) + writeCommentsToFile(outFile, comments[i]); + + // Write rates to file: + int ratesCount = this->ratings.getSize(); + outFile.write((const char*)&ratesCount, sizeof(ratesCount)); + for (size_t i = 0; i < ratesCount; i++) + writeRatesToFile(outFile, ratings[i]); +} + +void Book::readFromFile(std::ifstream& inFile) { + author = readString(inFile); // Author + title = readString(inFile); // Title + + // Read pages: + int len = 0; + inFile.read((char*)&len, sizeof(len)); + + for (size_t i = 0; i < len; i++) { + data.pushBack(Page()); + data[i].readFromFile(inFile); + } + + // Read comments + int commentsLen = 0; + inFile.read((char*)&commentsLen, sizeof(commentsLen)); + + for (size_t i = 0; i < commentsLen; i++) { + Pair toInsert = readCommentsFromFile(inFile); + comments.pushBack(std::move(toInsert)); + } + + // Read rates from file + int ratesCount = 0; + inFile.read((char*)&ratesCount, sizeof(ratesCount)); + for (size_t i = 0; i < ratesCount; i++) { + Pair toPush = readRatesFromFile(inFile); + ratings.pushBack(std::move(toPush)); + } +} + +double Book::getAvarageRating() const { + double sum = 0; + for (size_t i = 0; i < ratings.getSize(); i++) + sum += ratings[i].getSecond(); + + return sum / (double)(ratings.getSize()); +} + +void Book::write(unsigned pagesCount) { + unsigned short lines = 0; + + for (int i = 0; i < pagesCount; i++) { + std::cout << "Enter lines in page " << i + 1 << ": "; + std::cin >> lines; + std::cin.ignore(); + Page toInsert; + + toInsert.write(lines); + + data.pushBack(std::move(toInsert)); + } +} + +void Book::displayBook() const { + bool reading = true; + bool displayMenu = true; + unsigned pageNumber = 0; + + char cmd = '\0'; + unsigned pageIndex = 0; + + while (reading) { + system("cls"); + if (displayMenu) + displayHelpMenu(); + + data[pageIndex].displayPage(); + + std::cin.get(cmd); + + switch (cmd) { + case 'n': + if (pageIndex < data.getSize() - 1) + pageIndex++; + break; + case 'p': + if (pageIndex > 0) + pageIndex--; + break; + case 'h': + displayMenu = !displayMenu; + break; + case 'q': + reading = false; + break; + case '@': + std::cin >> pageNumber; + if (pageNumber >= 1 && pageNumber < data.getSize() + 1) + pageIndex = pageNumber - 1; + break; + default: + break; + } + } + system("cls"); +} + +void Book::showComments() const { + for (size_t i = 0; i < comments.getSize(); i++) + std::cout << comments[i].getFirst() << " wrote: " << comments[i].getSecond() << std::endl; +} + +void Book::showRates() const { + for (size_t i = 0; i < ratings.getSize(); i++) + std::cout << ratings[i].getFirst() << ": " << ratings[i].getSecond() << " start" << std::endl; + std::cout << std::endl; + + std::cout << "Avarage rate: " << getAvarageRating() << std::endl; +} + +void Book::displayHelpMenu() const { + std::cout << "Entered reader mode." << std::endl + << "Press n for next, p for prev." << std::endl << + "Press @ + to go to that page" << std::endl << + "Press h to hide or show this menu or q to exit" << std::endl; +} diff --git a/Utils/Kindle/Book.h b/Utils/Kindle/Book.h new file mode 100644 index 0000000..3a7f347 --- /dev/null +++ b/Utils/Kindle/Book.h @@ -0,0 +1,34 @@ +#pragma once +#include"vector.hpp" +#include"Page.h" +#include"Pair.hpp" +#include"serialize.h" + +class Book { +private: + string author; + string title; + Vector> ratings; // User name + rate + Vector data; // Pages + Vector> comments; // commenter's name + comment + + void addRating(unsigned short r, const string& name); + + void write(unsigned pagesCount); + void displayBook() const; + + void showComments() const; + void showRates() const; + void print() const; + void displayHelpMenu() const; +public: + Book() {} + Book(const string& author, const string& title); + + void writeToFile(std::ofstream& outFile) const; + void readFromFile(std::ifstream& inFile); + double getAvarageRating() const; + + friend class Kindle; +}; + diff --git a/Utils/Kindle/Kindle.cpp b/Utils/Kindle/Kindle.cpp new file mode 100644 index 0000000..063b329 --- /dev/null +++ b/Utils/Kindle/Kindle.cpp @@ -0,0 +1,354 @@ +#include "Kindle.h" + +void Kindle::displayUserDialog(User& currentUser) { + std::cout << "Wellcome, " << currentUser.name << std::endl; + string cmd; + + while (!(cmd == "exit")) { + std::cout << "> "; + std::cin >> cmd; + if (cmd == "read") { + readBookDialog(currentUser); + } + else if (cmd == "rate") { + rateBookDialog(currentUser); + } + else if (cmd == "comment") { + commentOnBookDialog(currentUser); + } + else if (cmd == "write") { + writeBookDialog(currentUser); + } + else if (cmd == "comments") { + displayCommentsDialog(); + } + else if (cmd == "view") { + viewBooks(); + } + else if (cmd == "rates") { + displayRatesDialog(); + } + } + + std::cout << "Exit user dialog" << std::endl; +} + +void Kindle::saveFileDialog() const { + string path; + std::cout << "Enter path: "; + std::cin >> path; + saveToFile(path.c_str()); +} + +void Kindle::readFileDialog() { + std::cout << "Enter path: "; + string path; + std::cin >> path; + readFromFile(path.c_str()); +} + +void Kindle::showHelpDialog() const { + std::cout << "Write one of the following commands and press enter: " << std::endl + << "| login | signup | load | saveas | view | exit" << std::endl << + "Press any key to exit" << std::endl; + std::cin.get(); + + std::cin.clear(); + std::cin.ignore(255, '\n'); +} + +void Kindle::saveToFile(const char* filePath) const { + std::ofstream outFile(filePath, std::ios::binary); + + if (!outFile) + return; + + outFile.write("#Ty", 4); + + size_t sizeOfLib = lib.getSize(); + size_t sizeOfUsers = users.getSize(); + // Write lib: + outFile.write((const char*)&sizeOfLib, sizeof(sizeOfLib)); + + for (size_t i = 0; i < sizeOfLib; i++) + lib[i].writeToFile(outFile); + + // Save users: + outFile.write((const char*)&sizeOfUsers, sizeof(sizeOfUsers)); + + for (size_t i = 0; i < sizeOfUsers; i++) + users[i].writeToFile(outFile); + + std::cout << "Saving success!" << std::endl; +} + +void Kindle::readFromFile(const char* filePath) { + std::ifstream inFile(filePath, std::ios::binary); + + if (!inFile) { + std::cout << "File does not exist" << std::endl; + return; + } + + char typeChecker[4]; + inFile.read(typeChecker, 4); + if (strcmp(typeChecker, "#Ty") != 0) { + std::cout << "Invalid file type" << std::endl; + return; + } + + size_t sizeOfLib = 0; + size_t sizeOfUsers = 0; + + // Read lib + inFile.read((char*)&sizeOfLib, sizeof(sizeOfLib)); + + for (size_t i = 0; i < sizeOfLib; i++) { + lib.pushBack(Book()); + lib[i].readFromFile(inFile); + } + + // Read users: + inFile.read((char*)&sizeOfUsers, sizeof(sizeOfUsers)); + + for (size_t i = 0; i < sizeOfUsers; i++) { + users.pushBack(User()); + users[i].readFromFile(inFile); + } + + std::cout << "Reading success!" << std::endl; +} + +int Kindle::findBookIndex(const string& name) const { + for (size_t i = 0; i < lib.getSize(); i++) + if (name == lib[i].title) + return i; + return -1; +} + +int Kindle::findUserIndex(const string& name) const { + for (size_t i = 0; i < users.getSize(); i++) + if (name == users[i].name) + return i; + return -1; +} + +bool Kindle::userReadTheBook(const User& currentUser, int bookIndex) const { + for (size_t i = 0; i < currentUser.indexesOfBooksRead.getSize(); i++) + if (currentUser.indexesOfBooksRead[i] == bookIndex) + return true; + return false; +} + +bool Kindle::existUser(const string& userName) const { + for (size_t i = 0; i < users.getSize(); i++) + if (userName == users[i].name) + return true; + return false; +} + +void Kindle::readBookDialog(User& reader) { + std::cout << "Which book would you like to read: "; + string bookName; + std::cin.ignore(); + bookName.getLine(std::cin); + + int indexOfBook = findBookIndex(bookName); + if (indexOfBook == -1) { + std::cout << "No such book" << std::endl; + return; + } + if (!(reader.name == lib[indexOfBook].author) && !userReadTheBook(reader, indexOfBook)) + reader.indexesOfBooksRead.pushBack(indexOfBook); + + lib[indexOfBook].displayBook(); +} + +void Kindle::rateBookDialog(const User& rater) { + std::cout << "Enter a book you'd line to rate: "; + string bookName; + std::cin.ignore(); + bookName.getLine(std::cin); + + int bookIndex = findBookIndex(bookName); + + if (bookIndex == -1) { + std::cout << "No such book" << std::endl; + return; + } + + if (rater.name == lib[bookIndex].author) { + std::cout << "You can't rate your own book" << std::endl; + return; + } + + unsigned short rate = 0; + std::cout << "Enter rate: "; + std::cin >> rate; + + lib[bookIndex].addRating(rate, rater.name); +} + +void Kindle::commentOnBookDialog(const User& commenter) { + std::cout << "Enter a book you would like to comment: "; + string bookName; + std::cin.ignore(); + bookName.getLine(std::cin);; + + int index = findBookIndex(bookName); + + if (index == -1) { + std::cout << "No such book"; + return; + } + + std::cout << "Enter comment: "; + string comment; + comment.getLine(std::cin); + if (commenter.name == lib[index].author || userReadTheBook(commenter, index)) { + Pair toAdd(commenter.name, std::move(comment)); + lib[index].comments.pushBack(std::move(toAdd)); + } + else { + std::cout << "You havent read the book" << std::endl; + return; + } +} + +void Kindle::writeBookDialog(User& writer) { + std::cout << "Enter title: "; + string title; + + std::cin.ignore(); + + title.getLine(std::cin); + + Book toAdd(writer.name, title); + + std::cout << "Enter pages count: "; + unsigned pagesCount = 0; + std::cin >> pagesCount; + + std::cin.ignore(); + + toAdd.write(pagesCount); + writer.indexesOfBooksWritten.pushBack(lib.getSize()); + lib.pushBack(std::move(toAdd)); +} + +void Kindle::displayCommentsDialog() const { + std::cout << "Enter book name: "; + string bookName; + std::cin.ignore(); + bookName.getLine(std::cin);; + + int indexOfBook = findBookIndex(bookName); + + if (indexOfBook == -1) { + std::cout << "No such book" << std::endl; + return; + } + + lib[indexOfBook].showComments(); +} + +void Kindle::displayRatesDialog() const { + std::cout << "Enter book name: "; + string bookName; + std::cin.ignore(); + bookName.getLine(std::cin); + + int indexOfBook = findBookIndex(bookName); + + if (indexOfBook == -1) { + std::cout << "No such book" << std::endl; + return; + } + + lib[indexOfBook].showRates(); +} + +void Kindle::viewBooks() const { + for (size_t i = 0; i < lib.getSize(); i++) + lib[i].print(); +} + +void Kindle::displayLoginDialog() { + std::cout << "Enter user name: "; + string userName; + + std::cin.ignore(); + + userName.getLine(std::cin); + + int userIndex = findUserIndex(userName); + + if (userIndex == -1) { + std::cout << "This user does not exist in our system\n"; + return; + } + string pwd; + std::cout << "Enter password: "; + + pwd.getLine(std::cin); + + if (!(pwd == users[userIndex].password)) { + std::cout << "Incorrect password.\n"; + return; + } + + displayUserDialog(users[userIndex]); +} + +void Kindle::displaySignupDialog() { + std::cout << "Enter name: "; + string name; + + std::cin.ignore(); + + name.getLine(std::cin); + + if (existUser(name)) { + std::cout << "User with that name already exist!" << std::endl; + return; + } + + std::cout << "Enter password: "; + string password; + password.getLine(std::cin); + + User toAdd(name, password); + users.pushBack(std::move(toAdd)); + std::cout << "Successful!" << std::endl; +} + + +void Kindle::display() { + string cmd; + while (!(cmd == "exit")) { + std::cout << "> "; + std::cin >> cmd; + + if (cmd == "login" || cmd == "log in") { + displayLoginDialog(); + } + else if (cmd == "signup" || cmd == "sign up") { + displaySignupDialog(); + } + else if (cmd == "view") { + viewBooks(); + } + else if (cmd == "load") { + readFileDialog(); + } + else if (cmd == "save") { + saveFileDialog(); + } + else if (cmd == "help") { + showHelpDialog(); + } + else { + std::cout << "Invalid command!" << std::endl; + } + } +} diff --git a/Utils/Kindle/Kindle.h b/Utils/Kindle/Kindle.h new file mode 100644 index 0000000..f610972 --- /dev/null +++ b/Utils/Kindle/Kindle.h @@ -0,0 +1,55 @@ +#pragma once +#include"vector.hpp" +#include"Book.h" +#include"User.h" +#include"Pair.hpp" +#include +#include +#include + +class Kindle { +private: + Vector lib; + Vector users; + + // Helper functions + int findBookIndex(const string& name) const; + int findUserIndex(const string& name) const; + + // did user read the book? + bool userReadTheBook(const User& currentUser, int bookIndex) const; + + // does user exist? + bool existUser(const string& userName) const; + + // Functions used by user + void readBookDialog(User& reader); + void writeBookDialog(User& writer); + + void rateBookDialog(const User& rater); + void commentOnBookDialog(const User& commenter); + + void displayCommentsDialog() const; + void displayRatesDialog() const; + + // TODO: Change book (add or remove page etc.) + + // Functions used by main dialog + void displayLoginDialog(); + void displaySignupDialog(); + void displayUserDialog(User& currentUser); + + void saveFileDialog() const; + void readFileDialog(); + + void viewBooks() const; + void showHelpDialog() const; + + // read && write + void saveToFile(const char* filePath) const; + void readFromFile(const char* filePath); +public: + // The only function used by our Kindle class + void display(); +}; + diff --git a/Utils/Kindle/Page.cpp b/Utils/Kindle/Page.cpp new file mode 100644 index 0000000..b663f4c --- /dev/null +++ b/Utils/Kindle/Page.cpp @@ -0,0 +1,37 @@ +#include "Page.h" + +void Page::write(unsigned linesCount) { + if (linesCount > MAX_LINES_IN_PAGE) + linesCount = MAX_LINES_IN_PAGE; + + + for (size_t i = 0; i < linesCount; i++) { + std::cout << i + 1 << " "; + lines.pushBack(string()); + + lines[i].getLine(std::cin); + } +} + +void Page::displayPage() const { + for (size_t i = 0; i < lines.getSize(); i++) + std::cout << lines[i] << std::endl; +} + +void Page::writeToFile(std::ofstream& outFile) const { + int len = lines.getSize(); + outFile.write((const char*)&len, sizeof(len)); + + for (size_t i = 0; i < len; i++) + writeString(outFile, lines[i]); +} + +void Page::readFromFile(std::ifstream& inFile) { + int len = 0; + inFile.read((char*)&len, sizeof(len)); + + for (size_t i = 0; i < len; i++) { + string s = readString(inFile); + lines.pushBack(std::move(s)); + } +} diff --git a/Utils/Kindle/Page.h b/Utils/Kindle/Page.h new file mode 100644 index 0000000..b184da8 --- /dev/null +++ b/Utils/Kindle/Page.h @@ -0,0 +1,21 @@ +#pragma once +#include"vector.hpp" +#include"string.h" +#include +#include"serialize.h" + +const short MAX_LINES_IN_PAGE = 26; + +class Page { +private: + Vector lines; + + void write(unsigned linesCount); + void displayPage() const; + + void writeToFile(std::ofstream& outFile) const; + void readFromFile(std::ifstream& inFile); + + friend class Book; +}; + diff --git a/Utils/Kindle/Pair.hpp b/Utils/Kindle/Pair.hpp new file mode 100644 index 0000000..caf7fe2 --- /dev/null +++ b/Utils/Kindle/Pair.hpp @@ -0,0 +1,29 @@ +#pragma once + +template +class Pair { + T first; + U second; +public: + Pair() { + first = T(); + second = U(); + } + Pair(const T& fst, const U& snd) : first(fst), second(snd) {} + + const T& getFirst() const { + return first; + } + + const U& getSecond() const { + return second; + } + + void setFirst(const T& arg) { + first = arg; + } + + void setSecond(const U& arg) { + second = arg; + } +}; \ No newline at end of file diff --git a/Utils/Kindle/Source.cpp b/Utils/Kindle/Source.cpp new file mode 100644 index 0000000..c876e4f --- /dev/null +++ b/Utils/Kindle/Source.cpp @@ -0,0 +1,6 @@ +#include"Kindle.h" + +int main() { + Kindle env; + env.display(); +} \ No newline at end of file diff --git a/Utils/Kindle/User.cpp b/Utils/Kindle/User.cpp new file mode 100644 index 0000000..bb9f045 --- /dev/null +++ b/Utils/Kindle/User.cpp @@ -0,0 +1,22 @@ +#include "User.h" + +User::User(const string& pName, const string& pPassword) { + name = pName; + password = pPassword; +} + +void User::writeToFile(std::ofstream& outFile) const { + writeString(outFile, name); + writeString(outFile, password); + + writeVector(outFile, indexesOfBooksRead); + writeVector(outFile, indexesOfBooksWritten); +} + +void User::readFromFile(std::ifstream& inFile) { + name = readString(inFile); + password = readString(inFile); + + indexesOfBooksRead = readVector(inFile); + indexesOfBooksWritten = readVector(inFile); +} diff --git a/Utils/Kindle/User.h b/Utils/Kindle/User.h new file mode 100644 index 0000000..97d3a4b --- /dev/null +++ b/Utils/Kindle/User.h @@ -0,0 +1,22 @@ +#pragma once +#include"string.h" +#include"vector.hpp" +#include"Book.h" +#include"serialize.h" + +class User { +private: + string name; + string password; + Vector indexesOfBooksRead; + Vector indexesOfBooksWritten; + + friend class Kindle; +public: + User() {} + User(const string& pName, const string& pPassword); + + void writeToFile(std::ofstream& outFile) const; + void readFromFile(std::ifstream& inFile); +}; + diff --git a/Utils/Kindle/readme.md b/Utils/Kindle/readme.md new file mode 100644 index 0000000..b1eddc9 --- /dev/null +++ b/Utils/Kindle/readme.md @@ -0,0 +1,66 @@ +# Kindle + +## Помощни средства които използвахме +За решението на тази задача използваме клас string, клас vector и клас pair. String е взет директно от семинарите на първа група, с добавена функция getLine(), която използваме подобно на std::getline(); +Вектора е взет от семинарите на втора група. +Класът Pair е единствено с цел улеснение. Той представлява наредена двойка от два темплейтни типа. +Всяко едно нещо което сме направили с тези помощни средства може да се направи и без тях - просто кодът става по - дълъг. + +## Използване на командите +### Команди, които поддържаме преди да се логне потребител: +* login - влизаме в системата +* signup - регистрираме се в системата +* view - преглеждаме какви книги имаме +* save - запазваме текущия Kindle във файл +* load - зареждаме Kindle от файл +* exit - излизаме от системата +### Команди, които има потребител: +* read - прочита книга +* write - пише книга +* rate - оценява книга +* comment - коментира под книга +* rates - проверява рейтинга на книгата +* comments - проверява коментарите под книгата +* view - преглежда какви книги има +* exit - излиза от профила си +### Команди които имаме докато четем книга: +* n - следваща страница +* p - предишна страница +* @ + [number] - отива на страница, която е подадена +* h - показва/скрива help меню +* q - излиза от режим на четене + +Въвеждаме команда и натискаме Enter. След това програмата ни пита ако има нужда от допълнителна информация. Пример +``` +> login +> Enter user name: [Name] +> Enter user password: [Password] +> Success! +> +``` + +## Накратко за запазването във файлове +Имаме да запазваме сложна структура във файл. Това което можем да направим е да я разбием на по - прости. В Kindle имаме два вектора, които представляват книгите и потребителите. Ако измислим метод да запазим книга и потребител другото е лесно. Можете да видите, че в класовете представляващи книга и потребител имаме отделни функции, които се грижат за работата със запазването. +Логиката за тях е аналогична - разбиваме структурата на по - малки структурки, които стават все по - лесни и по - лесни за запазване. + +## Допълнителни бележки +В решението сме използвали friend класове. Това не винаги е лоша идея, но внимавайте с тях - възможно е да доведат до логически грешки, тоест на един клас да се дадат твърде много права над друг. + +При запазването на класа ще видите следния код +```cpp +outFile.write("#Ty", 4); +``` +При четенето на класа ще видите следния код +```cpp +char typeChecker[4]; +inFile.read(typeChecker, 4); +if (strcmp(typeChecker, "#Ty") != 0) { + std::cout << "Invalid file type" << std::endl; + return; +} +``` +Реално, няма как да гарантираме, че подадения файл ни е коректен. Потребителя винаги може да подаде некоректен файл, което може да счупи нашата система. За това правим следното: в началото на файла, който запазваме, записваме някаква последователност от n символа. Когато четем, прочитаме първите n (в случая 4) байта от файла и казваме - ако това е "тайният" низ, то значи този файл е писан от системата, тоест се очаква да е коректен. В противен случай приключваме изпълнението и не четем излишни данни, които могат да счупят системата ни. + +Също така, функционалността за промяна на книга оставяме на Вас. Чувствайте се свободни да експериментирате и pull-request вате. + +При каквито и да е въпроси екипът по ООП е на линия. \ No newline at end of file diff --git a/Utils/Kindle/serialize.cpp b/Utils/Kindle/serialize.cpp new file mode 100644 index 0000000..bd75872 --- /dev/null +++ b/Utils/Kindle/serialize.cpp @@ -0,0 +1,71 @@ +#include"serialize.h" + +void writeString(std::ofstream& outFile, const string& str) { + int len = str.getSize(); + outFile.write((const char*)&len, sizeof(int)); + + outFile.write(str.c_str(), sizeof(char) * len); +} + +string readString(std::ifstream& inFile) { + int len = 0; + inFile.read((char*)&len, sizeof(len)); + + char* buff = new char[len + 1]; + inFile.read(buff, sizeof(char) * len); + + buff[len] = '\0'; + + string toReturn(buff); + + delete[] buff; + + return toReturn; +} + +void writeVector(std::ofstream& outFile, const Vector& v) { + int len = v.getSize(); + outFile.write((const char*)&len, sizeof(int)); + + for (size_t i = 0; i < v.getSize(); i++) + outFile.write((const char*)&v[i], sizeof(size_t)); +} + +Vector readVector(std::ifstream& inFile) { + int len = 0; + inFile.read((char*)&len, sizeof(int)); + Vector toReturn; + size_t read = 0; + + for (size_t i = 0; i < len; i++) { + inFile.read((char*)&read, sizeof(size_t)); + toReturn.pushBack(read); + } + + return toReturn; +} + +void writeCommentsToFile(std::ofstream& outFile, const Pair& p) { + writeString(outFile, p.getFirst()); + writeString(outFile, p.getSecond()); +} + +Pair readCommentsFromFile(std::ifstream& inFile) { + string fst = readString(inFile); + string snd = readString(inFile); + + return { fst, snd }; +} + +void writeRatesToFile(std::ofstream& outFile, const Pair& comments) { + writeString(outFile, comments.getFirst()); + outFile.write((const char*)&comments.getSecond(), sizeof(comments.getSecond())); +} + +Pair readRatesFromFile(std::ifstream& inFile) { + string fst = readString(inFile); + unsigned rate = 0; + inFile.read((char*)&rate, sizeof(rate)); + + return { fst, rate }; +} \ No newline at end of file diff --git a/Utils/Kindle/serialize.h b/Utils/Kindle/serialize.h new file mode 100644 index 0000000..242549f --- /dev/null +++ b/Utils/Kindle/serialize.h @@ -0,0 +1,20 @@ +#pragma once +#include"string.h" +#include"vector.hpp" +#include"Pair.hpp" +#include + +void writeString(std::ofstream& outFile, const string& str); + +string readString(std::ifstream& inFile); + +void writeVector(std::ofstream& outFile, const Vector& v); + +Vector readVector(std::ifstream& inFile); +void writeCommentsToFile(std::ofstream& outFile, const Pair& p); + +Pair readCommentsFromFile(std::ifstream& inFile); + +void writeRatesToFile(std::ofstream& outFile, const Pair& comments); + +Pair readRatesFromFile(std::ifstream& inFile); \ No newline at end of file diff --git a/Utils/Kindle/string.cpp b/Utils/Kindle/string.cpp new file mode 100644 index 0000000..083ce9c --- /dev/null +++ b/Utils/Kindle/string.cpp @@ -0,0 +1,158 @@ +#include "string.h" +#include +#include + +#pragma warning(disable : 4996) + +void string::copyFrom(const string& other) +{ + str = new char[strlen(other.str) + 1]; + strcpy(str, other.str); + size = other.size; +} +void string::free() +{ + delete[] str; +} + +string::string() +{ + str = new char[1]; + str[0] = '\0'; + size = 0; +} + +string::string(const char* data) +{ + if (data == nullptr) + { + str = new char[1]; + str[0] = '\0'; + size = 0; + } + else + { + size = strlen(data); + str = new char[size + 1]; + strcpy(str, data); + } +} + +string::string(const string& other) +{ + copyFrom(other); +} +string& string::operator=(const string& other) +{ + if (this != &other) + { + free(); + copyFrom(other); + } + return *this; +} +string::~string() +{ + free(); +} + + +size_t string::getSize() const +{ + return size; +} +void string::concat(const string& other) +{ + char* temp = new char[getSize() + other.getSize() + 1]; + strcpy(temp, str); + strcat(temp, other.str); + + delete[] str; + str = temp; + size = size + other.getSize(); +} + +const char* string::c_str() const +{ + return str; +} + +string& string::operator+=(const string& other) +{ + concat(other); + return *this; +} + +void string::getLine(std::istream& outFile) +{ + delete[] str; + char buff[1024]; + + outFile.getline(buff, 1024, '\n'); + size_t len = strlen(buff); + str = new char[len + 1]; + for (size_t i = 0; i < len; i++) + str[i] = buff[i]; + str[len] = '\0'; + size = len; +} + +string operator+(const string& lhs, const string& rhs) +{ + string copyOfLeft(lhs); + copyOfLeft += rhs; + return copyOfLeft; +} + +std::ostream& operator<<(std::ostream& stream, const string& str) +{ + stream << str.str; + return stream; +} + +std::istream& operator>>(std::istream& stream, string& str) +{ + delete[] str.str; + char buff[1024]; + stream >> buff; + + str.size = strlen(buff); + str.str = new char[str.size + 1]; + strcpy(str.str, buff); + + return stream; +} + +bool operator==(const string& lhs, const string& rhs) +{ + return strcmp(lhs.c_str(), rhs.c_str()) == 0; +} +bool operator<=(const string& lhs, const string& rhs) +{ + return strcmp(lhs.c_str(), rhs.c_str()) <= 0; + +} +bool operator<(const string& lhs, const string& rhs) +{ + return strcmp(lhs.c_str(), rhs.c_str()) < 0; + +} + +string::string(string&& otherString) +{ + str = otherString.str; + size = otherString.size; + otherString.str = nullptr; +} + +string& string::operator=(string&& otherString) +{ + if (this != &otherString) + { + free(); + str = otherString.str; + otherString.str = nullptr; + size = otherString.size; + } + return *this; +} \ No newline at end of file diff --git a/Utils/Kindle/string.h b/Utils/Kindle/string.h new file mode 100644 index 0000000..48742b1 --- /dev/null +++ b/Utils/Kindle/string.h @@ -0,0 +1,42 @@ +#pragma once + +#include +#include +class string +{ + char* str; + size_t size; + + void copyFrom(const string& other); + void free(); + +public: + string(); + string(const char*); + + string(const string&); + + string(string&&); //move constructor that accepts rvalue; + + string& operator=(const string& other); + string& operator=(string&& other); //move op= that accepts rvalue; + + ~string(); + + size_t getSize() const; + void concat(const string& other); + + const char* c_str() const; + + string& operator+=(const string& other); + + friend std::ostream& operator<<(std::ostream& stream, const string& str); + friend std::istream& operator>>(std::istream& stream, string& str); + void getLine(std::istream& out); +}; + +string operator+(const string& lhs, const string& rhs); + +bool operator==(const string& lhs, const string& rhs); +bool operator<=(const string& lhs, const string& rhs); +bool operator<(const string& lhs, const string& rhs); \ No newline at end of file diff --git a/Utils/Kindle/vector.hpp b/Utils/Kindle/vector.hpp new file mode 100644 index 0000000..9937765 --- /dev/null +++ b/Utils/Kindle/vector.hpp @@ -0,0 +1,239 @@ +#pragma once +#include +const size_t DEFAULT_CAPACITY = 4; + +template +class Vector { +private: + T* data; + size_t size; + size_t capacity; +public: + Vector(); + Vector(const Vector&); + Vector(Vector&&); + Vector& operator=(const Vector&); + Vector& operator=(Vector&&); + ~Vector(); + + size_t getSize() const; + size_t getCapacity() const; + + void pushBack(const T&); + void pushBack(T&& n); + void pushAt(const T&, const size_t); + void pushAt(T&&, const size_t); + T& popBack(); + T& popAt(const size_t); + T& operator[](const size_t); + const T& operator[](const size_t) const; + bool empty() const; + void clear(); + void swap(const Vector&); +private: + void copy(const Vector&); + void free(); + void move(Vector&&); + + size_t calculateCapacity(const size_t) const; + void resize(const size_t); +}; + +template +Vector::Vector() { + data = nullptr; + capacity = size = 0; +} + +template +Vector::Vector(const Vector& other) { + copy(other); +} + +template +Vector::Vector(Vector&& other) { + move(std::move(other)); +} + +template +Vector& Vector::operator=(const Vector& other) { + if (this != &other) + { + free(); + copy(other); + } + + return *this; +} + +template +Vector& Vector::operator=(Vector&& other) { + if (this != &other) + { + free(); + move(std::move(other)); + } + + return *this; +} + +template +Vector::~Vector() { + free(); +} + +template +size_t Vector::getSize() const { + return size; +} + +template +size_t Vector::getCapacity() const { + return capacity; +} + +template +void Vector::pushBack(const T& element) { + if (size + 1 > capacity) + resize(size + 1); + + data[size++] = element; +} + + +template +void Vector::pushBack(T&& element) { + if (size + 1 > capacity) + resize(size + 1); + + data[size++] = element; +} + +template +void Vector::pushAt(const T& element, const size_t index) { + if (size + 1 > capacity) + resize(size + 1); + + for (size_t i = size; i > index; i--) + data[i] = data[i - 1]; + + data[index] = element; + size++; +} + +template +void Vector::pushAt(T&& element, const size_t index) { + if (size + 1 > capacity) + resize(size + 1); + + for (size_t i = size; i > index; i--) + data[i] = data[i - 1]; + + data[index] = element; + size++; +} + +template +T& Vector::popBack() { + if (empty()) + throw "Vector is empty"; + + return data[--size]; +} + +template +T& Vector::popAt(size_t index) { + if (index < 0 || index >= size) + throw "Invalid index"; + + T temp = data[index]; + for (size_t i = index; i < size - 1; i++) + data[i] = data[i + 1]; + + size--; + return temp; +} + +template +T& Vector::operator[](const size_t index) { + if (index < 0 || index >= size) + throw "Invalid index"; + + return data[index]; +} + +template +const T& Vector::operator[](const size_t index) const { + if (index < 0 || index >= size) + throw "Invalid index"; + + return data[index]; +} + +template +bool Vector::empty() const { + return size == 0; +} + +template +void Vector::clear() { + delete[] data; + capacity = DEFAULT_CAPACITY; + data = new T[capacity]; + size = 0; +} + +template +void Vector::swap(const Vector& other) { + Vector tempVector(std::move(*this)); + *this = std::move(other); + other = std::move(tempVector); +} + +template +void Vector::copy(const Vector& other) { + size = other.size; + capacity = other.capacity; + data = new T[capacity]; + + for (size_t i = 0; i < size; i++) + data[i] = other[i]; +} + +template +void Vector::free() { + delete[] data; + data = nullptr; + capacity = size = 0; +} + +template +void Vector::move(Vector&& other) +{ + data = other.data; + size = other.size; + capacity = other.capacity; + + other.data = nullptr; + other.capacity = other.size = 0; +} +template +size_t Vector::calculateCapacity(const size_t number) const { + size_t result = DEFAULT_CAPACITY; + while (number > result) + result *= 2; + + return result; +} + +template +void Vector::resize(const size_t expectedCapacityToFit) { + capacity = calculateCapacity(expectedCapacityToFit); + T* temp = new T[capacity]; + + for (size_t i = 0; i < size; i++) + temp[i] = data[i]; + + delete[] data; + data = temp; +} \ No newline at end of file diff --git "a/Utils/homework_1_SI/\320\224\320\276\320\274\320\260\321\210\320\275\320\260_\321\200\320\260\320\261\320\276\321\202\320\260_1.pdf" "b/Utils/homework_1_SI/\320\224\320\276\320\274\320\260\321\210\320\275\320\260_\321\200\320\260\320\261\320\276\321\202\320\260_1.pdf" new file mode 100644 index 0000000..a7a27ba Binary files /dev/null and "b/Utils/homework_1_SI/\320\224\320\276\320\274\320\260\321\210\320\275\320\260_\321\200\320\260\320\261\320\276\321\202\320\260_1.pdf" differ diff --git a/Utils/k_1_SI/task1.cpp b/Utils/k_1_SI/task1.cpp new file mode 100644 index 0000000..77ad5f5 --- /dev/null +++ b/Utils/k_1_SI/task1.cpp @@ -0,0 +1,138 @@ +#include +#include +#include + +using namespace std; + +struct Point +{ + int x; + int y; + Point() : Point(0,0){} + + Point(int x, int y) + { + this->x = x; + this->y = y; + } + + double getDistance(const Point& other) const + { + int dx = x - other.x; + int dy = y - other.y; + return sqrt(dx * dx + dy * dy); + } +}; + +void print(const Point& p) +{ + std::cout << "[ x: " << p.x << ", y: " << p.y <<" ]"; +} + +struct Rectangle +{ +private: + Point points[4]; + +public: + Rectangle() = default; //the same as Rectangle() {} + + void setPoint(size_t index, int x, int y) + { + if(index > 3) + return; + + points[index].x = x; + points[index].y = y; + + } + const Point& getPoint(size_t index) const + { + if(index > 3) + return {}; //some Error. This is a refference to a temporary memory, so a better solution would be to throw an exception. + return points[index]; + } + double getPer() const + { + return 2 * points[0].getDistance(points[1]) + 2 * points[1].getDistance(points[2]); + } +}; + +void print(const Rectangle& rect) +{ + for(int i = 0; i < 4; i++) + { + print(rect.getPoint(i)); + } +} + +void swap(Rectangle& tr1, Rectangle& tr2) +{ + Rectangle temp = tr1; + tr1 = tr2; + tr2 = temp; +} + +void selectionSort(Rectangle* triangles, double* perimeters, unsigned size) +{ + for (unsigned i = 0; i < size - 1; i++) + { + //findMin + int minElementIndex = i; + for (unsigned j = i + 1; j < size; j++) + { + if (perimeters[j] < perimeters[minElementIndex]) + minElementIndex = j; + } + + if (minElementIndex != i) + { + swap(perimeters[i], perimeters[minElementIndex]); + swap(triangles[i], triangles[minElementIndex]); + } + } +} + +int main() +{ + ifstream file("rects.txt"); + + if(!file.is_open()) + { + std::cout << "Error while opening the file!"; + return -1; + } + + int n; + file >> n; + + Rectangle* rects = new Rectangle[n]; + double* perimeters = new double[n]; //this should be size_t, but we are using a double returning function for getDist. + + for(size_t i = 0; i < n; i++) + { + int x1, y1, x3, y3; + file >> x1 >> y1 >> x3 >> y3; + + rects[i].setPoint(0, x1, y1); + rects[i].setPoint(1, x1, y3); + rects[i].setPoint(2, x3, y3); + rects[i].setPoint(3, x3, y1); + + perimeters[i] = rects[i].getPer(); + + } + + selectionSort(rects, perimeters, n); //selection sort, because we want min number of copies (or swaps) + + for(size_t i = 0; i < n; i++) + { + print(rects[i]); + std::cout <<", Per: " << perimeters[i] << std::endl; + } + + + delete[] rects, perimeters; + return 0; +} + diff --git a/Utils/k_1_SI/task2_read.cpp b/Utils/k_1_SI/task2_read.cpp new file mode 100644 index 0000000..e6a8312 --- /dev/null +++ b/Utils/k_1_SI/task2_read.cpp @@ -0,0 +1,55 @@ +#include +#include +#include +using namespace std; + +const size_t MAX_NAME_SIZE = 22; +struct Student +{ + //gender should be BEFORE fn so the struct would be 28 bytes. + char name[MAX_NAME_SIZE + 1]; + bool isMale; + size_t fn; +}; + + +size_t getFileSize(ifstream& f) +{ + size_t currentPos = f.tellg(); + f.seekg(0, ios::end); + size_t size = f.tellg(); + + f.seekg(currentPos); + return size; +} + +void readFromFile(Student*& ptr, size_t& studentsCount, ifstream& f) +{ + size_t sizeOfFile = getFileSize(f); + studentsCount = sizeOfFile / sizeof(Student); + ptr = new Student[studentsCount]; + f.read((char*)ptr, sizeOfFile); +} + + +int main() +{ + Student* arr; + size_t count; + ifstream file("students.dat"); + + if(!file.is_open()) + { + std::cout << "Error while opening the file!" << std::endl; + return -1; + } + + readFromFile(arr, count, file); + + for (int i = 0; i < count; i++) + std::cout << "Name: " << arr[i].name << ", fn: " << arr[i].fn << ", is male: " << arr[i].isMale << std::endl; + + delete[] arr; + + return 0; +} diff --git a/Utils/k_1_SI/task2_write.cpp b/Utils/k_1_SI/task2_write.cpp new file mode 100644 index 0000000..f320557 --- /dev/null +++ b/Utils/k_1_SI/task2_write.cpp @@ -0,0 +1,84 @@ +#include +#include +#include +using namespace std; + +const size_t MAX_NAME_SIZE = 22; +struct Student +{ + //gender should be BEFORE fn so the struct would be 28 bytes. + char name[MAX_NAME_SIZE + 1]; + bool isMale; + size_t fn; +}; + +bool isLower(char ch) +{ + return ch >= 'a' && ch <= 'z'; +} + +bool areAllLowerCase(const char* str) +{ + while(*str) + { + if(!isLower(*str)) + return false; + str++; + } + return true; +} + +bool isUpper(char ch) +{ + return ch >= 'A' && ch <= 'Z'; +} + +bool isNameValid(const char* name) +{ + size_t len = strlen(name); + if(len == 0 || len > MAX_NAME_SIZE) + return false; + return isUpper(*name) && areAllLowerCase(name + 1); +} + +void initStudent(Student& st, const char* name, size_t fn, bool isMale) +{ + if(!isNameValid(name)) + strcpy(st.name, "Unknown"); + else + strcpy(st.name, name); + + st.isMale = isMale; + st.fn = fn; +} + +void saveToFile(const Student* students, size_t count, ofstream& file) +{ + file.write((const char*)students, count * sizeof(Student)); +} + + +int main() +{ + const size_t studentsCount = 4; + Student* arr = new Student[studentsCount]; + initStudent(arr[0], "Ivan", 1, true); + initStudent(arr[1], "Petur", 2, true); + initStudent(arr[2], "Alex", 3, true); + initStudent(arr[3], "Katerina", 4, false); + + ofstream file("students.dat", ios::binary); + + if(!file.is_open()) + { + std::cout << "Error while opening the file!" << std::endl; + delete[] arr; //! + return -1; + } + + saveToFile(arr, studentsCount, file); + + delete[] arr; + + return 0; +} diff --git "a/Utils/\320\242\320\265\320\274\320\270 \320\267\320\260 \321\203\321\201\321\202\320\265\320\275 \320\270\320\267\320\277\320\270\321\202 - \320\236\320\236\320\237, \320\241\320\230, 2022" "b/Utils/\320\242\320\265\320\274\320\270 \320\267\320\260 \321\203\321\201\321\202\320\265\320\275 \320\270\320\267\320\277\320\270\321\202 - \320\236\320\236\320\237, \320\241\320\230, 2022" new file mode 100644 index 0000000..b818c71 --- /dev/null +++ "b/Utils/\320\242\320\265\320\274\320\270 \320\267\320\260 \321\203\321\201\321\202\320\265\320\275 \320\270\320\267\320\277\320\270\321\202 - \320\236\320\236\320\237, \320\241\320\230, 2022" @@ -0,0 +1,29 @@ +Теми за устен изпит - ООП, СИ, 2022 + +Тема 1: Структури и обединения. Представяния в паметта. Размер на обекти/истанции. Подравняване. Подаване на обекти/истанции във функции. Създаване на обекти в динамичната памет. Пример с задачата за N тригъгълника. + +Тема 2: Текстови файлове. Йерархия на потоците. Потоци за вход/изход от файл. Режими на работа. Флагове на състоянията на потока. Позициониране във файл. Пример за функция, която връща големината на файл. Пример за функция, която връща брой редове в текстов файл. + +Тема 3: Двоични файлове. Big endian. Запазване на обекти в двоичен файл. Пример за запазване/четене на масив от обекти(от един тип) във файл. + +Тема 4: Член-функции. Конструктори и деструктор. Извикване на конструктори и деструктори. Конструктори и деструктор при композиция на обекти. Mодификатори за достъп. Капсулация. Пример за клас Person с име (низ с дължина най-много 20 символа) и години [5...90]. + +Тема 5: Разделна компилация. Копиращ конструктор и оператор=. + +Тема 6: Динамична памет в класовете. Голямата четворка. Пример за клас студент с име (с произволна дължина) и масив от оценки(с произволна дъжина) + +Тема 7: Предефиниране на оператори. Приятелски класове и функции. Пример за реализация на комплексно число и Nvector. + +Тема 8: Масиви от указатели към обекти. Изключения. Обработка на изключения. Проблеми при работа с потоци. Move семантики - ползи, lvalue, rvalue, move конструктор/оп=, std::move. + +Тема 9: Конвертиращи конструктори. Композиция и агрегация. Шаблони. Пример за шаблонна опашка. Необходими функции в шаблонен клас/шаблонна функция. + +Тема 10: Наследяване. Видове наследяване. Параметри на функции (указатели и референции). Конструктури и деструктори при наследяване. Копиране при наследяване. Пример с човек, студент и преподавател. + +Тема 11: Статично и динамично свързване. Виртуални функции. Полиморфизъм. Абстрактни класове. Пример за фигури. + +Тема 12: Колекции от обекти в полиморфна йерархия. Копиране и триене. Factory pattern. Пример с ферма. + +Тема 13: Множествено наследяване. Проблеми при множествено наследяване. Диамантен проблем. Пример с шах. + +Тема 14: Дървовидна структура от обекти от полиморфна йерархия. Пример с логически изрази. diff --git "a/Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Source.cpp" "b/Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Source.cpp" new file mode 100644 index 0000000..17e6f4e --- /dev/null +++ "b/Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Source.cpp" @@ -0,0 +1,12 @@ +#include +#include"chatSystem.h" + +int main() { + chatSystem data; + + data.addUser({ "Ivan", "1234", "iv@abv.bg" }); + data.addUser({ "Qvor", "4321", "qv@abv.bg" }); + + data.sendMessage("last example", "Ivan", "Qvor"); + data.viewMessages("Qvor", "Ivan"); +} \ No newline at end of file diff --git "a/Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Task1/LogFile.cpp" "b/Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Task1/LogFile.cpp" new file mode 100644 index 0000000..7be397b --- /dev/null +++ "b/Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Task1/LogFile.cpp" @@ -0,0 +1,92 @@ +#include "LogFile.h" + +void LogFile::readTime(std::ifstream& inFile, Timestamp& obj) const { + char isLogin; + + inFile >> isLogin; + + obj.isLogin = (isLogin == '+'); + + inFile >> obj.hour >> obj.minutes >> obj.seconds; +} + + +LogFile::LogFile() { + size = 0; +} + +LogFile::LogFile(const char* filePath) { + std::ifstream inFile(filePath); + + if (!inFile.is_open()) { + size = 0; + return; + } + + inFile >> size; + + for (int i = 0; i < size; i++) + readTime(inFile, data[i]); +} + + +int LogFile::getLoginsCountAfterHour(short hours, short minutes, short seconds) const { + int ctr = 0; + int totalSeconds = hours * 3600 + minutes * 60 + seconds; + for (int i = 0; i < size; i++) { + if (data[i].toSeconds() > totalSeconds) { + ctr = i + 1; + break; + } + } + + return size - ctr; +} + +int LogFile::getLoginsCountBetweenHours(short h1, short m1, short s1, short h2, short m2, short s2) const { + return getLoginsCountAfterHour(h1, m1, s1) - getLoginsCountAfterHour(h2, m2, s2); +} + +int LogFile::getLongestActivePeriod() const { + int max = 0; + bool isFirstLogOut = !data[0].isLogin; + bool isLastLogIn = data[size - 1].isLogin; + + if (isFirstLogOut) + max = data[0].toSeconds(); + + if (isLastLogIn) { + int lastTimeInterval = 23 * 3600 + 59 * 60 + 59 - data[size - 1].toSeconds(); + + if (max < lastTimeInterval) + max = lastTimeInterval; + } + + for (int i = isFirstLogOut; i < size - isLastLogIn; i += 2) { + int diff = data[i + 1].toSeconds() - data[i].toSeconds(); + if (diff > max) + max = diff; + } + + return max; +} + +bool LogFile::loggedInHour(int hour) const { + int left = 0; + int right = size-1; + + while (left <= right) { + int mid = left + (right - left) / 2; + if (hour == data[mid].hour) { + return true; + } + + if (hour < data[mid].hour) { + right = mid - 1; + } + else { + left = mid + 1; + } + } + return false; +} \ No newline at end of file diff --git "a/Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Task1/LogFile.h" "b/Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Task1/LogFile.h" new file mode 100644 index 0000000..258c7d5 --- /dev/null +++ "b/Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Task1/LogFile.h" @@ -0,0 +1,24 @@ +#pragma once +#include +#include "Timestamp.h" +const int MAX_FILE_SIZE = 100; +class LogFile { +private: + size_t size; + Timestamp data[MAX_FILE_SIZE]; + + void readTime(std::ifstream& inFile, Timestamp& obj) const; + +public: + LogFile(); + + LogFile(const char* filePath); + + int getLoginsCountAfterHour(short hours, short minutes, short seconds) const; + + int getLoginsCountBetweenHours(short h1, short m1, short s1, short h2, short m2, short s2) const; + + int getLongestActivePeriod() const; + + bool loggedInHour(int hour) const; +}; \ No newline at end of file diff --git "a/Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Task1/Timestamp.cpp" "b/Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Task1/Timestamp.cpp" new file mode 100644 index 0000000..28ff933 --- /dev/null +++ "b/Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Task1/Timestamp.cpp" @@ -0,0 +1,5 @@ +#include "Timestamp.h" + +int Timestamp::toSeconds() const{ + return hour * 3600 + minutes * 60 + seconds; +} \ No newline at end of file diff --git "a/Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Task1/Timestamp.h" "b/Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Task1/Timestamp.h" new file mode 100644 index 0000000..e437187 --- /dev/null +++ "b/Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/Task1/Timestamp.h" @@ -0,0 +1,9 @@ +#pragma once +struct Timestamp { + bool isLogin; + unsigned short hour; + unsigned short minutes; + unsigned short seconds; + + int toSeconds() const; +}; \ No newline at end of file diff --git "a/Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/User.cpp" "b/Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/User.cpp" new file mode 100644 index 0000000..998b91f --- /dev/null +++ "b/Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/User.cpp" @@ -0,0 +1,97 @@ +#include "User.h" +#include +#include +#include + +#pragma warning(disable : 4996) + +void generatePath(char* path, const char* bigger, const char* smaller) { + strcpy(path, bigger); + strcat(path, "-"); + strcat(path, smaller); + strcat(path, ".bat"); +} + +void User::createFileName(char* fileName, const User& other) const { + if (strcmp(name, other.name) == 1) { + generatePath(fileName, name, other.name); + } + else { + generatePath(fileName, other.name, name); + } +} + +User::User() : name(""), password(""), email(""){} + +User::User(const char* n, const char* pass, const char* mail) { + if (strlen(n) > NAME_LEN || strlen(pass) > PASS_LEN || strlen(mail) > MAIL_LEN) { + strcpy(name, ""); + strcpy(password, ""); + strcpy(email, ""); + + return; + } + + strcpy(name, n); + strcpy(password, pass); + strcpy(email, mail); +} + +void User::sendMessage(const char* message, const User& other) const { + char filePath[50]; + createFileName(filePath, other); + + std::ofstream outFile(filePath, std::ios::binary | std::ios::app); + + if (!outFile.is_open()) + return; + + outFile.write(name, sizeof(name)); + + int length = strlen(message); + + outFile.write((const char*)&length, sizeof(length)); + + outFile.write(message, length); + + outFile.close(); +} + +void User::viewMessage(const User& other) const { + char filePath[50]; + createFileName(filePath, other); + + std::ifstream inFile(filePath, std::ios::binary); + + if (!inFile.is_open()) + return; + + char buff[NAME_LEN + 1]; + + while (!inFile.eof()) { + inFile.read(buff, sizeof(buff)); + + if (inFile.eof()) + return; + + int length = 0; + + inFile.read((char*)&length, sizeof(length)); + + char* msg = new char[length + 1]; + + inFile.read(msg, length); + + msg[length] = '\0'; + + std::cout << buff << ": " << msg << std::endl; + + delete[] msg; + } + + inFile.close(); +} + +const char* User::getName() const { + return name; +} diff --git "a/Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/User.h" "b/Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/User.h" new file mode 100644 index 0000000..4f94c7f --- /dev/null +++ "b/Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/User.h" @@ -0,0 +1,26 @@ +#pragma once + +const int NAME_LEN = 20; +const int MAIL_LEN = 12; +const int PASS_LEN = 8; + +class User { +private: + // N символа за име +1 за терминираща нула! + char name[NAME_LEN + 1]; + char password[PASS_LEN + 1]; + char email[MAIL_LEN + 1]; + + void createFileName(char* fileName, const User& other) const; +public: + User(); + + User(const char* n, const char* pass, const char* email); + + void sendMessage(const char* message, const User& u) const; + + void viewMessage(const User& u) const; + + const char* getName() const; +}; + diff --git "a/Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/chatSystem.cpp" "b/Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/chatSystem.cpp" new file mode 100644 index 0000000..c982451 --- /dev/null +++ "b/Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/chatSystem.cpp" @@ -0,0 +1,80 @@ +#include "chatSystem.h" +#include +#include + +void chatSystem::save() const { + std::ofstream outFile(FILE_PATH, std::ios::binary); + + outFile.write((const char*)this, sizeof(chatSystem)); +} + +void chatSystem::read() { + std::ifstream inFile(FILE_PATH, std::ios::binary); + + inFile.read((char*)this, sizeof(chatSystem)); +} + +void chatSystem::searchIndexes(int& firstIndex, int& secondIndex, const char* fstName, const char* sndName) const { + for (int i = 0; i < size; i++) { + if (strcmp(fstName, data[i].getName()) == 0) { + firstIndex = i; + } + + if (strcmp(sndName, data[i].getName()) == 0) { + secondIndex = i; + } + + if (firstIndex != -1 && secondIndex != -1) + break; + } +} + +chatSystem::chatSystem() { + size = 0; + read(); +} + +void chatSystem::addUser(const User& arg) { + if (size > 99) + return; + + for (int i = 0; i < size; i++) { + if (strcmp(arg.getName(), data[i].getName()) == 0) { + return; + } + } + + data[size++] = arg; +} + +void chatSystem::sendMessage(const char* msg, const char* fstName, const char* sndName) const { + int firstIndex = -1; + int secondIndex = -1; + + searchIndexes(firstIndex, secondIndex, fstName, sndName); + + if (firstIndex == -1 || secondIndex == -1) + return; + + data[firstIndex].sendMessage(msg, data[secondIndex]); +} + +void chatSystem::viewMessages(const char* fstName, const char* sndName) const { + int firstIndex = -1; + int secondIndex = -1; + + searchIndexes(firstIndex, secondIndex, fstName, sndName); + + if (firstIndex == -1 || secondIndex == -1) + return; + + data[firstIndex].viewMessage(data[secondIndex]); +} + +int chatSystem::getSize() const { + return size; +} + +chatSystem::~chatSystem() { + save(); +} diff --git "a/Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/chatSystem.h" "b/Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/chatSystem.h" new file mode 100644 index 0000000..1f21bf3 --- /dev/null +++ "b/Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/chatSystem.h" @@ -0,0 +1,31 @@ +#pragma once +#include"User.h" + +const char FILE_PATH[] = "database.bat"; + +class chatSystem { +private: + User data[100]; + size_t size; + + void save() const; + + void read(); + + void searchIndexes(int& firstIndex, int& secondIndex, const char* fstName, const char* sndName) const; + +public: + chatSystem(); + + void addUser(const User& arg); + + void sendMessage(const char* msg, const char* fstName, const char* sndName) const; + + void viewMessages(const char* sender, const char* reciever) const; + + int getSize() const; + + ~chatSystem(); + +}; + diff --git "a/Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/\320\267\320\260\320\264\320\260\321\207\320\270 \320\267\320\260 \320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265 \320\241\320\230.pdf" "b/Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/\320\267\320\260\320\264\320\260\321\207\320\270 \320\267\320\260 \320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265 \320\241\320\230.pdf" new file mode 100644 index 0000000..111878f Binary files /dev/null and "b/Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/\320\267\320\260\320\264\320\260\321\207\320\270 \320\267\320\260 \320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265 \320\241\320\230.pdf" differ diff --git "a/Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/\321\204\321\203\320\275\320\272\321\206\320\270\320\270 \320\276\321\202 \320\277\320\276 - \320\262\320\270\321\201\320\276\320\272 \321\200\320\265\320\264/demo.cpp" "b/Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/\321\204\321\203\320\275\320\272\321\206\320\270\320\270 \320\276\321\202 \320\277\320\276 - \320\262\320\270\321\201\320\276\320\272 \321\200\320\265\320\264/demo.cpp" new file mode 100644 index 0000000..951b7d2 --- /dev/null +++ "b/Utils/\320\264\320\276\320\277\321\212\320\273\320\275\320\270\321\202\320\265\320\273\320\275\320\276 \321\203\320\277\321\200\320\260\320\266\320\275\320\265\320\275\320\270\320\265/\321\204\321\203\320\275\320\272\321\206\320\270\320\270 \320\276\321\202 \320\277\320\276 - \320\262\320\270\321\201\320\276\320\272 \321\200\320\265\320\264/demo.cpp" @@ -0,0 +1,89 @@ +#include +#include + +template +class Entity { +private: + int integerData; + char symbolData; + T abstractData; + +public: + Entity(int iArg, char cArg, const T& aArg) : integerData(iArg), symbolData(cArg), abstractData(aArg) {} + + int getIntegerData() const { + return integerData; + } + + char getCharData() const { + return symbolData; + } + + const T& getAbstractData() const { + return abstractData; + } + + void print() const { + std::cout << integerData << " " << symbolData << " " << abstractData << std::endl; + } +}; + +template +bool compareIntegerValues(const Entity& fst, const Entity& snd) { + return fst.getIntegerData() < snd.getIntegerData(); +} + +template +bool compareCharValues(const Entity& fst, const Entity& snd) { + return fst.getCharData() < snd.getCharData(); +} + +template +bool compareAbstractValues(const Entity& fst, const Entity& snd) { + return fst.getAbstractData() < snd.getAbstractData(); +} + +template +void sort(std::vector>& collection, bool (*lessThan)(const Entity&, const Entity&)) { + for (size_t i = 0; i < collection.size(); i++) { + size_t minElementIndex = i; + + for (size_t j = i + 1; j < collection.size(); j++) { + if (lessThan(collection[j], collection[minElementIndex])) { + minElementIndex = j; + } + } + + if (minElementIndex != i) + std::swap(collection[i], collection[minElementIndex]); + } +} + +char generateRandomLetter() { + return (char)(rand() % 26 + 'a'); +} + +double generateRandomDouble() { + return (double)rand() / RAND_MAX + rand() % 256; +} + +int main() { + std::vector> collection; + + for (size_t i = 0; i < 100; i++) + collection.push_back({ rand() % 10000, generateRandomLetter(), generateRandomDouble() }); + + + // Sort integer values + // sort(collection, compareIntegerValues); + + // Sort char values + // sort(collection, compareCharValues); + + // Sort abstract values + sort(collection, compareAbstractValues); + + + for (size_t i = 0; i < 100; i++) + collection[i].print(); +} -- cgit v1.3.1-23-gd82d