diff options
fixed typo in folder name
33 files changed, 2210 insertions, 0 deletions
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 <iostream> +#include <cstring> + +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<iostream> + +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<string, unsigned> 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<string, string> 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<string, unsigned> 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 @ + <number> 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<Pair<string, unsigned>> ratings; // User name + rate + Vector<Page> data; // Pages + Vector<Pair<string, string>> 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<string, string> 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<iostream> +#include<cstring> +#include<fstream> + +class Kindle { +private: + Vector<Book> lib; + Vector<User> 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<iostream> +#include"serialize.h" + +const short MAX_LINES_IN_PAGE = 26; + +class Page { +private: + Vector<string> 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 T, class U> +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<size_t> indexesOfBooksRead; + Vector<size_t> 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 вате. + +<b>При каквито и да е въпроси екипът по ООП е на линия.</b>
\ 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<size_t>& 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<size_t> readVector(std::ifstream& inFile) { + int len = 0; + inFile.read((char*)&len, sizeof(int)); + Vector<size_t> 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<string, string>& p) { + writeString(outFile, p.getFirst()); + writeString(outFile, p.getSecond()); +} + +Pair<string, string> readCommentsFromFile(std::ifstream& inFile) { + string fst = readString(inFile); + string snd = readString(inFile); + + return { fst, snd }; +} + +void writeRatesToFile(std::ofstream& outFile, const Pair<string, unsigned>& comments) { + writeString(outFile, comments.getFirst()); + outFile.write((const char*)&comments.getSecond(), sizeof(comments.getSecond())); +} + +Pair<string, unsigned> 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<fstream> + +void writeString(std::ofstream& outFile, const string& str); + +string readString(std::ifstream& inFile); + +void writeVector(std::ofstream& outFile, const Vector<size_t>& v); + +Vector<size_t> readVector(std::ifstream& inFile); +void writeCommentsToFile(std::ofstream& outFile, const Pair<string, string>& p); + +Pair<string, string> readCommentsFromFile(std::ifstream& inFile); + +void writeRatesToFile(std::ofstream& outFile, const Pair<string, unsigned>& comments); + +Pair<string, unsigned> 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 <cstring> +#include <iostream> + +#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 <fstream> +#include <iostream> +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<iostream> +const size_t DEFAULT_CAPACITY = 4; + +template <typename T> +class Vector { +private: + T* data; + size_t size; + size_t capacity; +public: + Vector(); + Vector(const Vector<T>&); + Vector(Vector<T>&&); + Vector<T>& operator=(const Vector<T>&); + Vector<T>& operator=(Vector<T>&&); + ~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<T>&); +private: + void copy(const Vector&); + void free(); + void move(Vector&&); + + size_t calculateCapacity(const size_t) const; + void resize(const size_t); +}; + +template <typename T> +Vector<T>::Vector() { + data = nullptr; + capacity = size = 0; +} + +template <typename T> +Vector<T>::Vector(const Vector<T>& other) { + copy(other); +} + +template <typename T> +Vector<T>::Vector(Vector<T>&& other) { + move(std::move(other)); +} + +template <typename T> +Vector<T>& Vector<T>::operator=(const Vector<T>& other) { + if (this != &other) + { + free(); + copy(other); + } + + return *this; +} + +template <typename T> +Vector<T>& Vector<T>::operator=(Vector<T>&& other) { + if (this != &other) + { + free(); + move(std::move(other)); + } + + return *this; +} + +template <typename T> +Vector<T>::~Vector() { + free(); +} + +template <typename T> +size_t Vector<T>::getSize() const { + return size; +} + +template <typename T> +size_t Vector<T>::getCapacity() const { + return capacity; +} + +template <typename T> +void Vector<T>::pushBack(const T& element) { + if (size + 1 > capacity) + resize(size + 1); + + data[size++] = element; +} + + +template <typename T> +void Vector<T>::pushBack(T&& element) { + if (size + 1 > capacity) + resize(size + 1); + + data[size++] = element; +} + +template <typename T> +void Vector<T>::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 <typename T> +void Vector<T>::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 <typename T> +T& Vector<T>::popBack() { + if (empty()) + throw "Vector is empty"; + + return data[--size]; +} + +template <typename T> +T& Vector<T>::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 <typename T> +T& Vector<T>::operator[](const size_t index) { + if (index < 0 || index >= size) + throw "Invalid index"; + + return data[index]; +} + +template <typename T> +const T& Vector<T>::operator[](const size_t index) const { + if (index < 0 || index >= size) + throw "Invalid index"; + + return data[index]; +} + +template <typename T> +bool Vector<T>::empty() const { + return size == 0; +} + +template <typename T> +void Vector<T>::clear() { + delete[] data; + capacity = DEFAULT_CAPACITY; + data = new T[capacity]; + size = 0; +} + +template <typename T> +void Vector<T>::swap(const Vector<T>& other) { + Vector<T> tempVector(std::move(*this)); + *this = std::move(other); + other = std::move(tempVector); +} + +template <typename T> +void Vector<T>::copy(const Vector<T>& other) { + size = other.size; + capacity = other.capacity; + data = new T[capacity]; + + for (size_t i = 0; i < size; i++) + data[i] = other[i]; +} + +template <typename T> +void Vector<T>::free() { + delete[] data; + data = nullptr; + capacity = size = 0; +} + +template <typename T> +void Vector<T>::move(Vector&& other) +{ + data = other.data; + size = other.size; + capacity = other.capacity; + + other.data = nullptr; + other.capacity = other.size = 0; +} +template <typename T> +size_t Vector<T>::calculateCapacity(const size_t number) const { + size_t result = DEFAULT_CAPACITY; + while (number > result) + result *= 2; + + return result; +} + +template <typename T> +void Vector<T>::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/Домашна_работа_1.pdf b/Utils/homework_1_SI/Домашна_работа_1.pdf Binary files differnew file mode 100644 index 0000000..a7a27ba --- /dev/null +++ b/Utils/homework_1_SI/Домашна_работа_1.pdf 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 <iostream> +#include <fstream> +#include <cmath> + +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 <iostream> +#include <fstream> +#include <cstring> +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 <iostream> +#include <fstream> +#include <cstring> +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/Теми за устен изпит - ООП, СИ, 2022 b/Utils/Теми за устен изпит - ООП, СИ, 2022 new file mode 100644 index 0000000..b818c71 --- /dev/null +++ b/Utils/Теми за устен изпит - ООП, СИ, 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/допълнително упражнение/Source.cpp b/Utils/допълнително упражнение/Source.cpp new file mode 100644 index 0000000..17e6f4e --- /dev/null +++ b/Utils/допълнително упражнение/Source.cpp @@ -0,0 +1,12 @@ +#include<iostream> +#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/допълнително упражнение/Task1/LogFile.cpp b/Utils/допълнително упражнение/Task1/LogFile.cpp new file mode 100644 index 0000000..7be397b --- /dev/null +++ b/Utils/допълнително упражнение/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/допълнително упражнение/Task1/LogFile.h b/Utils/допълнително упражнение/Task1/LogFile.h new file mode 100644 index 0000000..258c7d5 --- /dev/null +++ b/Utils/допълнително упражнение/Task1/LogFile.h @@ -0,0 +1,24 @@ +#pragma once +#include<fstream> +#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/допълнително упражнение/Task1/Timestamp.cpp b/Utils/допълнително упражнение/Task1/Timestamp.cpp new file mode 100644 index 0000000..28ff933 --- /dev/null +++ b/Utils/допълнително упражнение/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/допълнително упражнение/Task1/Timestamp.h b/Utils/допълнително упражнение/Task1/Timestamp.h new file mode 100644 index 0000000..e437187 --- /dev/null +++ b/Utils/допълнително упражнение/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/допълнително упражнение/User.cpp b/Utils/допълнително упражнение/User.cpp new file mode 100644 index 0000000..998b91f --- /dev/null +++ b/Utils/допълнително упражнение/User.cpp @@ -0,0 +1,97 @@ +#include "User.h" +#include<cstring> +#include<fstream> +#include<iostream> + +#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/допълнително упражнение/User.h b/Utils/допълнително упражнение/User.h new file mode 100644 index 0000000..4f94c7f --- /dev/null +++ b/Utils/допълнително упражнение/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/допълнително упражнение/chatSystem.cpp b/Utils/допълнително упражнение/chatSystem.cpp new file mode 100644 index 0000000..c982451 --- /dev/null +++ b/Utils/допълнително упражнение/chatSystem.cpp @@ -0,0 +1,80 @@ +#include "chatSystem.h" +#include<cstring> +#include<fstream> + +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/допълнително упражнение/chatSystem.h b/Utils/допълнително упражнение/chatSystem.h new file mode 100644 index 0000000..1f21bf3 --- /dev/null +++ b/Utils/допълнително упражнение/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/допълнително упражнение/задачи за допълнително упражнение СИ.pdf b/Utils/допълнително упражнение/задачи за допълнително упражнение СИ.pdf Binary files differnew file mode 100644 index 0000000..111878f --- /dev/null +++ b/Utils/допълнително упражнение/задачи за допълнително упражнение СИ.pdf diff --git a/Utils/допълнително упражнение/функции от по - висок ред/demo.cpp b/Utils/допълнително упражнение/функции от по - висок ред/demo.cpp new file mode 100644 index 0000000..951b7d2 --- /dev/null +++ b/Utils/допълнително упражнение/функции от по - висок ред/demo.cpp @@ -0,0 +1,89 @@ +#include<iostream> +#include<vector> + +template<class T> +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<class T> +bool compareIntegerValues(const Entity<T>& fst, const Entity<T>& snd) { + return fst.getIntegerData() < snd.getIntegerData(); +} + +template<class T> +bool compareCharValues(const Entity<T>& fst, const Entity<T>& snd) { + return fst.getCharData() < snd.getCharData(); +} + +template<class T> +bool compareAbstractValues(const Entity<T>& fst, const Entity<T>& snd) { + return fst.getAbstractData() < snd.getAbstractData(); +} + +template<class T> +void sort(std::vector<Entity<T>>& collection, bool (*lessThan)(const Entity<T>&, const Entity<T>&)) { + 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<Entity<double>> 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(); +} |
