├── .gitignore ├── Utils ├── ExamSI │ ├── Utils.h │ └── source.cpp ├── H2_Solution │ ├── MaximumPartialFunction.cpp │ ├── MaximumPartialFunction.h │ ├── MinimumPartialFunction.cpp │ ├── MinimumPartialFunction.h │ ├── MyVector.cpp │ ├── MyVector.h │ ├── Pair.h │ ├── PartialFunction.h │ ├── PartialFunctionByCriteria.hpp │ ├── PartialFunctionFactory.cpp │ ├── PartialFunctionFactory.h │ ├── PartialFunctionOperation.cpp │ ├── PartialFunctionOperation.h │ ├── Runner.cpp │ ├── Runner.h │ ├── TypeOneFunction.cpp │ ├── TypeOneFunction.h │ ├── TypeTwoFunction.cpp │ ├── TypeTwoFunction.h │ ├── TypeZeroFunction.cpp │ ├── TypeZeroFunction.h │ └── main.cpp ├── IS_2025_cons │ ├── README.md │ ├── SerializableStringАrray.cpp │ ├── SerializableStringАrray.h │ └── Source.cpp ├── IS_Exam_solution │ ├── exclude.txt │ ├── include.txt │ └── main.cpp ├── Pract_is_3 │ ├── Kontrolno_Solution │ │ ├── FileSystem.cpp │ │ ├── FileSystem.h │ │ ├── Files │ │ │ ├── Directory.cpp │ │ │ ├── Directory.h │ │ │ ├── File.cpp │ │ │ ├── File.h │ │ │ ├── TextFile.cpp │ │ │ └── TextFile.h │ │ ├── README.md │ │ └── main.cpp │ ├── Pract01 │ │ ├── README.md │ │ └── Task3_Solution.cpp │ ├── Pract02 │ │ ├── README.md │ │ ├── StructureSize │ │ │ ├── README.md │ │ │ └── img │ │ │ │ ├── structC.jpg │ │ │ │ ├── structD.jpg │ │ │ │ └── transpose.png │ │ └── student_data.txt │ ├── Pract03 │ │ ├── README.md │ │ ├── Task2_Solution.cpp │ │ └── people.dat │ ├── Pract04 │ │ ├── ConstructorsCallOrderExamples │ │ │ └── README.md │ │ └── README.md │ ├── Pract05 │ │ ├── Interval │ │ │ ├── HelperFunctions.cpp │ │ │ ├── HelperFunctions.h │ │ │ ├── Interval.cpp │ │ │ └── Interval.h │ │ └── README.md │ ├── Pract06 │ │ ├── README.md │ │ └── SubjectDiaryExample.cpp │ ├── Pract07 │ │ ├── README.md │ │ └── ShoppingCartOperators │ │ │ ├── Product.cpp │ │ │ ├── Product.h │ │ │ ├── ShoppingCart.cpp │ │ │ └── ShoppingCart.h │ ├── Pract08 │ │ └── README.md │ ├── Pract09 │ │ └── README.md │ ├── Pract10 │ │ ├── Lexicon │ │ │ └── README.md │ │ └── README.md │ ├── Pract11 │ │ └── README.md │ ├── Pract12 │ │ └── README.md │ ├── Pract13 │ │ └── README.md │ └── Pract14 │ │ └── README.md ├── Pract_si_3 │ ├── Pract01 │ │ ├── Pract01.md │ │ └── snippets.cpp │ ├── Pract02 │ │ ├── README.md │ │ ├── notANumber.txt │ │ ├── numbers.txt │ │ └── snippets.cpp │ ├── Pract03 │ │ └── README.md │ ├── Pract04 │ │ ├── README.md │ │ └── blitz_test.md │ ├── Pract05 │ │ ├── README.md │ │ └── blitz_test02.md │ ├── Pract06 │ │ └── README.md │ ├── Pract07 │ │ ├── README.md │ │ ├── blitz_test_03.md │ │ └── snippets.md │ ├── Pract08 │ │ └── readme.md │ ├── Pract09 │ │ ├── blitz_test_04.md │ │ └── readme.md │ ├── Pract10 │ │ ├── readme.md │ │ └── snippets │ │ │ ├── inheritancePrinting.cpp │ │ │ ├── passingToFunctions.cpp │ │ │ └── placementNewExample.cpp │ ├── Pract11 │ │ ├── README.md │ │ └── blitz_test_5.md │ ├── Pract12 │ │ ├── blitz_test_6.md │ │ └── readme.md │ ├── Pract13-14 │ │ ├── README.md │ │ └── blitz_test_7.md │ └── Pract15 │ │ ├── README.md │ │ └── blitz_test_8.md └── SI_K1_Solutions │ ├── HexModifier │ ├── HexModifier.cpp │ └── HexModifier.h │ └── ThreeNumbersWrapperCondition │ ├── ThreeNumbersWrapperCondition.cpp │ └── ThreeNumbersWrapperCondition.h ├── Week 01 ├── Rational.cpp ├── StudentDatabase.cpp ├── convertStringToInt.cpp ├── enum_example_1.cpp ├── ipAddress.cpp ├── isLittleEndian.cpp ├── nTriangles.cpp ├── readme.md └── struct_example_1.cpp ├── Week 02 ├── 1. newLinesCount.cpp ├── 2. selfPrinting.cpp ├── 3. copyFile.cpp ├── 4. struct_from_to_file.cpp ├── 5. merge_sorted_text_files.cpp ├── 6. csv_parser.cpp ├── img │ ├── hierarchy.png │ ├── stream-flags.png │ └── streams.png ├── readme.md └── students.csv ├── Week 03 ├── arrayStudentsDynamicName_write_read.cpp ├── arrayStudentsStaticName_read.cpp ├── arrayStudentsStaticName_write.cpp ├── hexViewer.cpp ├── numToAndFromBinary.cpp ├── readme.md ├── replaceInTextFile.cpp ├── studentToBinary.cpp └── writeAndReadArrayOfInts.cpp ├── Week 04 ├── Interval │ ├── Interval.cpp │ ├── Interval.h │ └── main.cpp ├── Student (namelen [2..20], age [5..90].cpp ├── StudentDynanamicName.cpp ├── Time.cpp └── readme.md ├── Week 05 ├── ConsolePrinter (aggregation example).cpp ├── Date, Time, Event │ ├── Date │ │ ├── BulgarianDate.cpp │ │ ├── BulgarianDate.h │ │ └── main.cpp │ ├── Event │ │ ├── Event.cpp │ │ └── Event.h │ ├── Time │ │ ├── Time.cpp │ │ └── Time.h │ └── main.cpp ├── Preprocessor │ ├── Example1 │ │ └── FuncVsMacro.cpp │ └── Example2 │ │ ├── main.cpp │ │ └── nz.txt └── readme.md ├── Week 06 ├── Bitsets │ ├── DynamicSet │ │ ├── DynamicSet.cpp │ │ ├── DynamicSet.h │ │ └── main.cpp │ └── StaticSet │ │ ├── StaticSet.cpp │ │ ├── StaticSet.h │ │ └── main.cpp ├── GraduatedStudent │ ├── GraduatedStudent.cpp │ ├── GraduatedStudent.h │ └── main.cpp ├── Quiz (not finished) │ ├── Question.cpp │ ├── Question.h │ ├── Quiz.cpp │ ├── Quiz.h │ └── Source.cpp └── README.md ├── Week 07 ├── Complex │ ├── Complex.cpp │ ├── Complex.h │ └── main.cpp ├── MyString │ ├── MyString.cpp │ ├── MyString.h │ └── main.cpp ├── NVector │ ├── NVector.cpp │ ├── NVector.h │ └── main.cpp └── readme.md ├── Week 08 ├── Fibb_static_cache │ ├── MapKeys0toN.cpp │ ├── MapKeys0toN.h │ └── main.cpp ├── FlightsScanner - Exception handling task │ ├── FlightsScanner.cpp │ ├── FlightsScanner.h │ ├── Utills.cpp │ ├── Utills.h │ ├── inputFlights.txt │ └── source.cpp ├── ImmutableString │ ├── ImmutableString.cpp │ ├── ImmutableString.h │ ├── StringPool.cpp │ ├── StringPool.h │ └── test2.cpp ├── Readme.md ├── SelfCounting │ ├── SelfCounting.cpp │ ├── SelfCounting.h │ └── main.cpp └── SwapsCounter │ └── swapsCounter.cpp ├── Week 09 ├── DynamicArrayOfA (with move) │ ├── DynamicArrayOfA.cpp │ ├── DynamicArrayOfA.h │ └── main.cpp ├── DynamicArrayOfPointers (with move) │ ├── DynamicArrayOfPointers.cpp │ ├── DynamicArrayOfPointers.h │ └── main.cpp ├── GraduatedStudent (with move) │ ├── GraduatedStudent.cpp │ ├── GraduatedStudent.h │ └── main.cpp ├── MyString (with move) │ ├── MyString.cpp │ ├── MyString.h │ └── main.cpp └── readme.md ├── Week 10 ├── Person, Student, Teacher │ ├── Person │ │ ├── Person.cpp │ │ └── Person.h │ ├── Source.cpp │ ├── Student │ │ ├── Student.cpp │ │ └── Student.h │ └── Teacher │ │ ├── Teacher.cpp │ │ └── Teacher.h ├── Sets │ ├── DynamicSet │ │ ├── DynamicSet.cpp │ │ ├── DynamicSet.h │ │ └── main.cpp │ ├── SetByCriteria │ │ ├── SetByCriteria.cpp │ │ └── SetByCriteria.h │ ├── SetByString │ │ ├── SetByString.cpp │ │ └── SetByString.h │ └── source.cpp ├── String and StringView │ ├── MyString.cpp │ ├── MyString.h │ ├── StringView.cpp │ ├── StringView.h │ └── main.cpp └── readme.md ├── Week 11 ├── Collections │ ├── Collection.h │ ├── DynamicCollection.cpp │ ├── DynamicCollection.h │ ├── IntervalCollection.cpp │ ├── IntervalCollection.h │ ├── NormalCollection.cpp │ ├── NormalCollection.h │ ├── PureNumbersCollection.cpp │ ├── PureNumbersCollection.h │ ├── Set.cpp │ ├── Set.h │ ├── SortedCollection.cpp │ ├── SortedCollection.h │ └── Source.cpp ├── Example_polymorphism │ ├── Circle.cpp │ ├── Circle.h │ ├── Rectangle.cpp │ ├── Rectangle.h │ ├── Shape.cpp │ ├── Shape.h │ ├── ShapeFactory.cpp │ ├── ShapeFactory.h │ ├── Triangle.cpp │ ├── Triangle.h │ └── main.cpp ├── File Readers and Writers │ ├── ArrFileReader.cpp │ ├── ArrFileReader.h │ ├── ArrFileWriter.cpp │ ├── ArrFileWriter.h │ ├── BinaryFileReader.cpp │ ├── BinaryFileReader.h │ ├── BinaryFileWriter.cpp │ ├── BinaryFileWriter.h │ ├── CSVFileReader.cpp │ ├── CSVFileReader.h │ ├── CSVFileWriter.cpp │ ├── CSVFileWriter.h │ ├── FilePath.cpp │ ├── FilePath.h │ ├── FileReader.cpp │ ├── FileReader.h │ ├── FileWriter.cpp │ ├── FileWriter.h │ ├── MyString.cpp │ ├── MyString.h │ ├── Source.cpp │ ├── StringView.cpp │ ├── StringView.h │ ├── numbers.arr │ ├── numbers.csv │ ├── numbers.dat │ └── numbers2.arr ├── README.md └── virtual_functions_playground.cpp ├── Week 12 ├── Example_visitor │ ├── Circle.cpp │ ├── Circle.h │ ├── Rectangle.cpp │ ├── Rectangle.h │ ├── Shape.cpp │ ├── Shape.h │ ├── Triangle.cpp │ ├── Triangle.h │ └── main.cpp ├── FixedCapacityStack │ ├── MyStack.hpp │ └── main.cpp ├── FunctionAverage │ ├── FunctionAverage.hpp │ ├── numbers.dat │ └── src.cpp ├── Polymorphic containters │ ├── Farm │ │ ├── Animal.cpp │ │ ├── Animal.h │ │ ├── Cat.cpp │ │ ├── Cat.h │ │ ├── Cow.cpp │ │ ├── Cow.h │ │ ├── Dog.cpp │ │ ├── Dog.h │ │ ├── Factory.cpp │ │ ├── Factory.h │ │ ├── Farm.cpp │ │ ├── Farm.h │ │ └── source.cpp │ └── ShapeCollection │ │ ├── Circle.cpp │ │ ├── Circle.h │ │ ├── Rectangle.cpp │ │ ├── Rectangle.h │ │ ├── Shape.cpp │ │ ├── Shape.h │ │ ├── ShapeCollection.cpp │ │ ├── ShapeCollection.h │ │ ├── ShapeFactory.cpp │ │ ├── ShapeFactory.h │ │ ├── Triangle.cpp │ │ ├── Triangle.h │ │ └── main.cpp ├── README.md ├── Templates │ ├── FixedCapacityStack │ │ ├── MyStack.hpp │ │ └── main.cpp │ ├── Queue │ │ ├── Queue.hpp │ │ └── main.cpp │ ├── Template instantiation │ │ ├── Sorts.cpp │ │ ├── Sorts.h │ │ └── source.cpp │ └── main.cpp └── UniquePointer │ ├── UniquePointer.hpp │ └── main.cpp ├── Week 13 ├── Chess_basic_prototype │ ├── ChessBoard │ │ ├── ChessBoard.cpp │ │ └── ChessBoard.h │ ├── ConfigEnums │ │ └── ConfigEnums.h │ ├── FigureFactory │ │ ├── FigureFactory.cpp │ │ └── FigureFactory.h │ ├── Figures │ │ ├── Bishop │ │ │ ├── Bishop.cpp │ │ │ └── Bishop.h │ │ ├── FigureBase │ │ │ ├── Figure.cpp │ │ │ └── Figure.h │ │ ├── King │ │ │ ├── King.cpp │ │ │ └── King.h │ │ ├── Knight │ │ │ ├── Knight.cpp │ │ │ └── Knight.h │ │ ├── Pawn │ │ │ ├── Pawn.cpp │ │ │ └── Pawn.h │ │ ├── Queen │ │ │ ├── Queen.cpp │ │ │ └── Queen.h │ │ └── Rook │ │ │ ├── Rook.cpp │ │ │ └── Rook.h │ └── main.cpp ├── SmartPointers │ ├── SharedAndWeak │ │ ├── SharedPtr.hpp │ │ ├── WeakPtr.hpp │ │ └── main.cpp │ └── UniquePointer │ │ ├── UniquePointer.hpp │ │ └── main.cpp └── readme.md ├── Week 14 ├── ExpressionCalculator │ ├── ExpressonCalucator.cpp │ └── String and StringView │ │ ├── MyString.cpp │ │ ├── MyString.h │ │ ├── StringView.cpp │ │ ├── StringView.h │ │ └── main.cpp └── README.md ├── Week 15 ├── DesignPatterns │ ├── Creational │ │ ├── AbstractFactory.cpp │ │ ├── FactoryAndFactoryMethod.cpp │ │ └── Singleton.cpp │ └── Structural │ │ └── Composite.cpp ├── README.md └── SingletonFactory │ ├── data.txt │ └── main.cpp └── readme.md /.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore IDE folders 2 | .idea/* 3 | .vs/* 4 | .vscode/* 5 | 6 | # Prerequisites 7 | *.d 8 | 9 | # Compiled Object files 10 | *.slo 11 | *.lo 12 | *.o 13 | *.obj 14 | 15 | # Precompiled Headers 16 | *.gch 17 | *.pch 18 | 19 | # Compiled Dynamic libraries 20 | *.so 21 | *.dylib 22 | *.dll 23 | 24 | # Fortran module files 25 | *.mod 26 | *.smod 27 | 28 | # Compiled Static libraries 29 | *.lai 30 | *.la 31 | *.a 32 | *.lib 33 | 34 | # Executables 35 | *.exe 36 | *.out 37 | *.app 38 | -------------------------------------------------------------------------------- /Utils/ExamSI/Utils.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | static bool isValidSymbol(unsigned char ch) 4 | { 5 | return ch >= 32; 6 | } 7 | static unsigned char* createAndFillByteArray(size_t destSize, const unsigned char* source, size_t sourceSize) 8 | { 9 | unsigned char* dest = new unsigned char[destSize]; 10 | //you could use a loop here. 11 | memcpy(dest, source, sourceSize); //NO STRCPY!!! This is not a null terminated string 12 | return dest; 13 | } 14 | static const char* getFileExtension(const char* str) 15 | { 16 | while (*str && *str != '.') str++; 17 | return str; //'.' included in factory, if not str + 1 18 | } 19 | 20 | int getCharCount(std::ifstream& ifs, char ch) { 21 | 22 | if (!ifs.is_open()) { 23 | return -1; 24 | } 25 | 26 | int count = 0; 27 | while (true) { 28 | char current = ifs.get(); 29 | 30 | if (ifs.eof()) { 31 | return count; 32 | } 33 | 34 | if (current == ch) { 35 | count++; 36 | } 37 | } 38 | return 0; 39 | } 40 | 41 | static size_t getFileSize(std::ifstream& file) 42 | { 43 | size_t currentPos = file.tellg(); 44 | file.seekg(0, std::ios::end); 45 | size_t fileSize = file.tellg(); 46 | file.seekg(currentPos); 47 | return fileSize; 48 | } 49 | -------------------------------------------------------------------------------- /Utils/H2_Solution/MaximumPartialFunction.cpp: -------------------------------------------------------------------------------- 1 | #include "MaximumPartialFunction.h" 2 | #include 3 | 4 | MaximumPartialFunction::MaximumPartialFunction(PartialFunction**&& functions, uint16_t size) : PartialFunctionOperation(std::move(functions), size) 5 | { 6 | } 7 | 8 | int32_t MaximumPartialFunction::operator()(int32_t value) const 9 | { 10 | int32_t max = (*(functions[0]))(value); 11 | int32_t curr; 12 | for (uint16_t i = 1; i < size; i++) 13 | { 14 | curr = (*(functions[i]))(value); 15 | if (curr > max) 16 | { 17 | max = curr; 18 | } 19 | } 20 | 21 | return max; 22 | } 23 | 24 | PartialFunction* MaximumPartialFunction::clone() const 25 | { 26 | return new MaximumPartialFunction(*this); 27 | } 28 | -------------------------------------------------------------------------------- /Utils/H2_Solution/MaximumPartialFunction.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "PartialFunctionOperation.h" 3 | 4 | class MaximumPartialFunction : public PartialFunctionOperation 5 | { 6 | public: 7 | MaximumPartialFunction(PartialFunction**&& functions, uint16_t size); 8 | 9 | int32_t operator()(int32_t value) const override; 10 | PartialFunction* clone() const override; 11 | 12 | }; 13 | -------------------------------------------------------------------------------- /Utils/H2_Solution/MinimumPartialFunction.cpp: -------------------------------------------------------------------------------- 1 | #include "MinimumPartialFunction.h" 2 | #include 3 | 4 | MinimumPartialFunction::MinimumPartialFunction(PartialFunction**&& functions, uint16_t size) : PartialFunctionOperation(std::move(functions), size) 5 | { 6 | } 7 | 8 | int32_t MinimumPartialFunction::operator()(int32_t value) const 9 | { 10 | 11 | int32_t min = (*(functions[0]))(value); 12 | int32_t currVal; 13 | for (uint16_t i = 1; i < size; i++) 14 | { 15 | currVal = (*(functions[i]))(value); 16 | if (currVal < min) 17 | { 18 | min = currVal; 19 | } 20 | } 21 | 22 | return min; 23 | } 24 | 25 | PartialFunction* MinimumPartialFunction::clone() const 26 | { 27 | return new MinimumPartialFunction(*this); 28 | } 29 | -------------------------------------------------------------------------------- /Utils/H2_Solution/MinimumPartialFunction.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "PartialFunctionOperation.h" 3 | 4 | class MinimumPartialFunction : public PartialFunctionOperation 5 | { 6 | public: 7 | MinimumPartialFunction(PartialFunction**&& functions, uint16_t size); 8 | 9 | int32_t operator()(int32_t value) const override; 10 | PartialFunction* clone() const override; 11 | 12 | }; 13 | -------------------------------------------------------------------------------- /Utils/H2_Solution/MyVector.cpp: -------------------------------------------------------------------------------- 1 | #include "MyVector.h" 2 | #include 3 | 4 | void MyVector::free() 5 | { 6 | delete[] data; 7 | } 8 | void MyVector::copyFrom(const MyVector& other) 9 | { 10 | data = new int[other.size]; 11 | for (int i = 0; i < other.size; i++) 12 | data[i] = other.data[i]; 13 | size = other.size; 14 | } 15 | MyVector::MyVector(int size) : size(size) 16 | { 17 | data = new int32_t[size]; 18 | } 19 | 20 | MyVector::MyVector(int32_t* data, int size) 21 | { 22 | if (!data) { 23 | throw std::exception("data cannot be nullptr"); 24 | } 25 | this->data = new int32_t[size]; 26 | for (int i = 0; i < size; i++) { 27 | this->data[i] = data[i]; 28 | } 29 | this->size = size; 30 | } 31 | 32 | MyVector::~MyVector() 33 | { 34 | free(); 35 | } 36 | 37 | MyVector& MyVector::operator=(const MyVector& other) 38 | { 39 | if (this != &other) { 40 | free(); 41 | copyFrom(other); 42 | } 43 | return *this; 44 | } 45 | 46 | MyVector::MyVector(const MyVector& other) 47 | { 48 | copyFrom(other); 49 | } 50 | 51 | int MyVector::operator[](int index) const 52 | { 53 | return data[index]; 54 | } 55 | 56 | void MyVector::readFromFile(std::istream& file, unsigned count) 57 | { 58 | file.read((char*)data, count * sizeof(int32_t)); 59 | } 60 | 61 | int MyVector::getSize() const 62 | { 63 | return size; 64 | } -------------------------------------------------------------------------------- /Utils/H2_Solution/MyVector.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | 5 | class MyVector { 6 | private: 7 | int32_t* data; 8 | int size; 9 | 10 | void free(); 11 | void copyFrom(const MyVector& other); 12 | public: 13 | MyVector(int size); 14 | MyVector(int32_t* data, int size); 15 | ~MyVector(); 16 | 17 | MyVector& operator=(const MyVector& other); 18 | MyVector(const MyVector& other); 19 | int operator[](int index) const; 20 | 21 | void readFromFile(std::istream& file, unsigned count); 22 | 23 | int getSize() const; 24 | }; -------------------------------------------------------------------------------- /Utils/H2_Solution/Pair.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | struct Pair 5 | { 6 | bool first; 7 | int32_t second; 8 | 9 | }; -------------------------------------------------------------------------------- /Utils/H2_Solution/PartialFunction.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | class PartialFunction 5 | { 6 | public: 7 | PartialFunction() = default; 8 | 9 | virtual bool isDefined(int32_t value) const = 0; 10 | virtual int32_t operator()(int32_t value) const = 0; 11 | virtual PartialFunction* clone() const = 0; 12 | 13 | virtual ~PartialFunction() = default; 14 | 15 | }; -------------------------------------------------------------------------------- /Utils/H2_Solution/PartialFunctionByCriteria.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "PartialFunction.h" 3 | 4 | template 5 | class PartialFunctionByCriteria : public PartialFunction 6 | { 7 | private: 8 | T data; 9 | public: 10 | PartialFunctionByCriteria(const T& data); 11 | 12 | bool isDefined(int32_t val) const override; 13 | int32_t operator()(int32_t val) const override; 14 | PartialFunction* clone() const override; 15 | }; 16 | 17 | template 18 | inline PartialFunctionByCriteria::PartialFunctionByCriteria(const T& data) : data(data) 19 | { 20 | } 21 | 22 | template 23 | inline bool PartialFunctionByCriteria::isDefined(int32_t val) const 24 | { 25 | return data(val).first; 26 | } 27 | 28 | template 29 | inline int32_t PartialFunctionByCriteria::operator()(int32_t val) const 30 | { 31 | return data(val).second; 32 | } 33 | 34 | template 35 | inline PartialFunction* PartialFunctionByCriteria::clone() const 36 | { 37 | return new PartialFunctionByCriteria(*this); 38 | } 39 | -------------------------------------------------------------------------------- /Utils/H2_Solution/PartialFunctionFactory.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "PartialFunction.h" 3 | #include 4 | 5 | class PartialFunctionFactory 6 | { 7 | public: 8 | static PartialFunction* create(const char* fileName); 9 | static PartialFunction* create(std::istream& file); 10 | static PartialFunction** createArr(std::istream& file, uint16_t size); 11 | }; -------------------------------------------------------------------------------- /Utils/H2_Solution/PartialFunctionOperation.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "PartialFunction.h" 3 | 4 | class PartialFunctionOperation : public PartialFunction 5 | { 6 | private: 7 | void free(); 8 | void copyFrom(const PartialFunctionOperation& other); 9 | void moveFrom(PartialFunctionOperation&& other); 10 | protected: 11 | PartialFunction** functions = nullptr; 12 | uint16_t size = 0; 13 | public: 14 | PartialFunctionOperation(PartialFunction**&& functions, uint16_t size); 15 | PartialFunctionOperation(const PartialFunctionOperation& other); 16 | PartialFunctionOperation(PartialFunctionOperation&& other) noexcept; 17 | PartialFunctionOperation& operator=(const PartialFunctionOperation& other); 18 | PartialFunctionOperation& operator=(PartialFunctionOperation&& other) noexcept; 19 | ~PartialFunctionOperation() noexcept; 20 | 21 | bool isDefined(int32_t val) const override; 22 | }; 23 | -------------------------------------------------------------------------------- /Utils/H2_Solution/Runner.cpp: -------------------------------------------------------------------------------- 1 | #include "Runner.h" 2 | #include "PartialFunctionFactory.h" 3 | #include 4 | 5 | 6 | void chosenValues(const PartialFunction* func) 7 | { 8 | int32_t a, b; 9 | std::cout << "Enter a: "; 10 | std::cin >> a; 11 | std::cout << "Enter b: "; 12 | std::cin >> b; 13 | 14 | if (a > b) 15 | { 16 | throw std::invalid_argument("Error."); 17 | } 18 | 19 | for (int64_t i = a; i <= b; i++) 20 | { 21 | if (func->isDefined(i)) 22 | { 23 | std::cout << "f(" << i << ") = " << func->operator()(i) << std::endl; 24 | } 25 | } 26 | } 27 | 28 | void allValues(const PartialFunction* func) 29 | { 30 | std::cin.ignore(); 31 | std::cout << "Press enter to output one defined value:"; 32 | for (int64_t i = INT32_MIN; i <= INT32_MAX; i++) 33 | { 34 | if (func->isDefined(i)) 35 | { 36 | std::cin.ignore(); 37 | std::cout << "f(" << i << ") = " << func->operator()(i) << std::endl; 38 | } 39 | } 40 | 41 | } 42 | 43 | 44 | void run(const char* fileName) 45 | { 46 | PartialFunction* function = PartialFunctionFactory::create(fileName); 47 | 48 | uint16_t n; 49 | std::cout << "Write 1 to print chosen values in [a;b] or 2 fto print all defined values: "; 50 | std::cin >> n; 51 | 52 | switch (n) 53 | { 54 | case 1: 55 | chosenValues(function); 56 | break; 57 | case 2: 58 | allValues(function); 59 | break; 60 | default: 61 | std::cout << "Error." << std::endl; 62 | break; 63 | } 64 | } -------------------------------------------------------------------------------- /Utils/H2_Solution/Runner.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "PartialFunction.h" 3 | 4 | void run(const char* fileName); 5 | void chosenValues(const PartialFunction* function); 6 | void allValues(const PartialFunction* function); 7 | 8 | -------------------------------------------------------------------------------- /Utils/H2_Solution/TypeOneFunction.cpp: -------------------------------------------------------------------------------- 1 | #include "TypeOneFunction.h" 2 | 3 | TypeOneFunction::TypeOneFunction(int16_t n, std::istream& is) : size(n), undefValues(n) 4 | { 5 | undefValues.readFromFile(is, n); 6 | } 7 | 8 | 9 | Pair TypeOneFunction::operator()(int32_t value) const 10 | { 11 | for (unsigned i = 0; i < size; i++) 12 | { 13 | if (undefValues[i] == value) 14 | { 15 | return Pair{ false, 0}; 16 | } 17 | } 18 | 19 | return Pair{ true, value }; 20 | } 21 | 22 | -------------------------------------------------------------------------------- /Utils/H2_Solution/TypeOneFunction.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "Pair.h" 3 | #include "MyVector.h" 4 | #include 5 | #include 6 | 7 | class TypeOneFunction 8 | { 9 | private: 10 | MyVector undefValues; 11 | int16_t size = 0; 12 | public: 13 | TypeOneFunction(int16_t size, std::istream& file); 14 | 15 | Pair operator()(int32_t value) const; 16 | 17 | }; -------------------------------------------------------------------------------- /Utils/H2_Solution/TypeTwoFunction.cpp: -------------------------------------------------------------------------------- 1 | #include "TypeTwoFunction.h" 2 | 3 | TypeTwoFunction::TypeTwoFunction(int16_t n, std::istream& is) : size(n), oneValues(n) 4 | { 5 | oneValues.readFromFile(is, n); 6 | } 7 | 8 | 9 | Pair TypeTwoFunction::operator()(int32_t value) const 10 | { 11 | for (unsigned i = 0; i < size; i++) 12 | { 13 | if (oneValues[i] == value) 14 | { 15 | return Pair{ true, 1 }; 16 | } 17 | } 18 | 19 | return Pair{ true, 0 }; 20 | } 21 | 22 | -------------------------------------------------------------------------------- /Utils/H2_Solution/TypeTwoFunction.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "Pair.h" 3 | #include "MyVector.h" 4 | #include 5 | #include 6 | 7 | class TypeTwoFunction 8 | { 9 | private: 10 | MyVector oneValues; 11 | int16_t size = 0; 12 | public: 13 | TypeTwoFunction(int16_t size, std::istream& file); 14 | 15 | Pair operator()(int32_t value) const; 16 | }; -------------------------------------------------------------------------------- /Utils/H2_Solution/TypeZeroFunction.cpp: -------------------------------------------------------------------------------- 1 | #include "TypeZeroFunction.h" 2 | 3 | TypeZeroFunction::TypeZeroFunction(uint16_t n, std::istream& is) : size(n), args(n), res(n) 4 | { 5 | args.readFromFile(is, n); 6 | res.readFromFile(is, n); 7 | } 8 | 9 | 10 | Pair TypeZeroFunction::operator()(int32_t value) const 11 | { 12 | int ind = -1; 13 | for (unsigned i = 0; i < size; i++) 14 | { 15 | if (args[i] == value) 16 | { 17 | ind = i; 18 | break; 19 | } 20 | } 21 | 22 | if (ind != -1) 23 | { 24 | return Pair{ true, res[ind] }; 25 | } 26 | 27 | return Pair{ false, 0 }; 28 | } 29 | 30 | -------------------------------------------------------------------------------- /Utils/H2_Solution/TypeZeroFunction.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "MyVector.h" 3 | #include "Pair.h" 4 | #include 5 | #include 6 | 7 | class TypeZeroFunction 8 | { 9 | private: 10 | MyVector args; 11 | MyVector res; 12 | int16_t size = 0; 13 | public: 14 | TypeZeroFunction(uint16_t size, std::istream& file); 15 | 16 | Pair operator()(int32_t value) const; 17 | 18 | }; 19 | -------------------------------------------------------------------------------- /Utils/H2_Solution/main.cpp: -------------------------------------------------------------------------------- 1 | #include "Runner.h" 2 | 3 | int main() 4 | { 5 | run("func.dat"); 6 | } 7 | 8 | 9 | -------------------------------------------------------------------------------- /Utils/IS_2025_cons/README.md: -------------------------------------------------------------------------------- 1 | SerializableStringАrray 2 | Масив от стрингове, който може да се сериализира в двоичен файл. 3 | 4 | 5 | Трябва да имате следния интерфейс: 6 | 7 | - Конструктор, в който приемате макс брой стрингове и 8 | макс дължина на стринг, който да може да се добави. 9 | 10 | - Конструктор, който приема име на файл и десериализира от файл. 11 | - addString(Стринг) 12 | - get(индекс) 13 | - Функция, която приема име на файл и сериализира масива във файл. 14 | 15 | Линк към другата задача: https://github.com/IvanMakaveev/FMI-Education/tree/main/OOP%20IS%202024-2025/Consultation%201/Task%201 16 | -------------------------------------------------------------------------------- /Utils/IS_2025_cons/SerializableStringАrray.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Angeld55/Object-oriented_programming_FMI/56245c795618b1b575e2c63963773ae0d4f66ace/Utils/IS_2025_cons/SerializableStringАrray.cpp -------------------------------------------------------------------------------- /Utils/IS_2025_cons/SerializableStringАrray.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Angeld55/Object-oriented_programming_FMI/56245c795618b1b575e2c63963773ae0d4f66ace/Utils/IS_2025_cons/SerializableStringАrray.h -------------------------------------------------------------------------------- /Utils/IS_2025_cons/Source.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Angeld55/Object-oriented_programming_FMI/56245c795618b1b575e2c63963773ae0d4f66ace/Utils/IS_2025_cons/Source.cpp -------------------------------------------------------------------------------- /Utils/IS_Exam_solution/exclude.txt: -------------------------------------------------------------------------------- 1 | 2 3 4 5 -------------------------------------------------------------------------------- /Utils/IS_Exam_solution/include.txt: -------------------------------------------------------------------------------- 1 | 0 2 | 6 3 | 7 -------------------------------------------------------------------------------- /Utils/Pract_is_3/Kontrolno_Solution/FileSystem.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "Files/Directory.h" 3 | #include "Files/TextFile.h" 4 | 5 | class FileSystem 6 | { 7 | Directory* root; 8 | 9 | char* getNextFilename(const char* path) const; 10 | char* getPrevFilename(const char* path) const; 11 | File* getFileFromSubfolder(const Directory* subfolder, const char* path) const; 12 | void createSubfolderInFolder(Directory* folder, const char* path); 13 | 14 | void copyFrom(const FileSystem& other); 15 | void moveFrom(FileSystem&& other); 16 | void free(); 17 | public: 18 | FileSystem(); 19 | ~FileSystem(); 20 | FileSystem(const FileSystem& other); 21 | FileSystem(FileSystem&& other); 22 | FileSystem& operator=(const FileSystem& other); 23 | FileSystem& operator=(FileSystem&& other); 24 | 25 | void createTextFile(const char* path, const char* content); 26 | void createDirectory(const char* path); 27 | File* getFile(const char* path) const; 28 | void printFile(const char* path) const; 29 | }; 30 | 31 | -------------------------------------------------------------------------------- /Utils/Pract_is_3/Kontrolno_Solution/Files/Directory.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "File.h" 3 | 4 | const int DEFAULT_CAPACITY = 8; 5 | 6 | class Directory : public File { 7 | File** files; 8 | size_t fileCount; 9 | size_t capacity; 10 | 11 | void resize(unsigned newCap); 12 | void free(); 13 | void copyFrom(const Directory& other); 14 | void moveFrom(Directory&& other); 15 | 16 | void printInDir(unsigned depth) const override; 17 | public: 18 | Directory(const Directory& other); 19 | Directory(const char* filename); 20 | Directory(Directory&& other); 21 | ~Directory(); 22 | 23 | void printContent() const override; 24 | File* clone() const override; 25 | 26 | Directory& operator=(const Directory& other); 27 | Directory& operator=(Directory&& other); 28 | 29 | void add(const File& file); 30 | void add(File* file); 31 | bool contains(const char* filename) const; 32 | File* getFileByName(const char* name) const; 33 | }; -------------------------------------------------------------------------------- /Utils/Pract_is_3/Kontrolno_Solution/Files/File.cpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "File.h" 3 | #pragma warning (disable : 4996) 4 | 5 | 6 | File::File(const char* filename) { 7 | strncpy(this->filename, filename, NAME_LEN); 8 | } 9 | 10 | const char* File::getName() const { 11 | return filename; 12 | } 13 | 14 | void File::printInDir(unsigned depth) const { 15 | for (int i = 0; i < depth; i++) { 16 | std::cout << "\t"; 17 | } 18 | std::cout << filename << std::endl; 19 | } 20 | -------------------------------------------------------------------------------- /Utils/Pract_is_3/Kontrolno_Solution/Files/File.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | const int NAME_LEN = 32 + 1; 5 | class File { 6 | char filename[NAME_LEN]; 7 | public: 8 | File(const char* filename); 9 | 10 | // !!! 11 | virtual File* clone() const = 0; 12 | virtual ~File() = default; 13 | 14 | virtual void printContent() const = 0; 15 | virtual void printInDir(unsigned depth) const; 16 | 17 | const char* getName() const; 18 | }; -------------------------------------------------------------------------------- /Utils/Pract_is_3/Kontrolno_Solution/Files/TextFile.cpp: -------------------------------------------------------------------------------- 1 | #include "TextFile.h" 2 | #pragma warning (disable : 4996) 3 | 4 | 5 | TextFile::TextFile(const char* filename) : File(filename) {} 6 | TextFile::TextFile(const char* filename, const char* content) : File(filename) { 7 | strncpy(this->content, content, CONTENT_LENGTH); 8 | } 9 | 10 | File* TextFile::clone() const { 11 | return new TextFile(*this); 12 | } 13 | 14 | void TextFile::printContent() const { 15 | std::cout << getName() << std::endl << "-----------" << std::endl << content << std::endl; 16 | } 17 | 18 | const char* TextFile::getContent() const { 19 | return content; 20 | } -------------------------------------------------------------------------------- /Utils/Pract_is_3/Kontrolno_Solution/Files/TextFile.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "File.h" 3 | 4 | const unsigned CONTENT_LENGTH = 1024 + 1; 5 | 6 | class TextFile : public File { 7 | char content[CONTENT_LENGTH] {0}; 8 | public: 9 | TextFile(const char* filename); 10 | TextFile(const char* filename, const char* content); 11 | 12 | File* clone() const override; 13 | 14 | void printContent() const override; 15 | 16 | const char* getContent() const; 17 | }; 18 | 19 | -------------------------------------------------------------------------------- /Utils/Pract_is_3/Kontrolno_Solution/README.md: -------------------------------------------------------------------------------- 1 | ## Примерно решение на задачите от контролното по ООП Практикум на 3та група 2 | 3 | Първата част от задачата е идентична със задачата от Практикум 14 4 | 5 | FileManager класът съдържа указател към директорията root, за да може методите getFile и printFile да са константни, в противен случай можем да сложим член данната да е просто 6 | 7 | `Directory root`, без да трябва да пишем голяма четворка 8 | 9 | Забележки: приемат се и решения, които използват enum с типа на файла в базовия клас, тук е показан вариант, при който това не е необходимо 10 | -------------------------------------------------------------------------------- /Utils/Pract_is_3/Kontrolno_Solution/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "FileSystem.h" 3 | 4 | int main() { 5 | FileSystem fs; 6 | fs.getFile("root")->printContent(); 7 | fs.createTextFile("root/file.txt", "samplecontent"); 8 | fs.createTextFile("root/dir1/dir2/random", "randomcontent"); 9 | fs.createTextFile("root/dir1/dir2/random2", "randomcontent"); 10 | fs.getFile("root")->printContent(); 11 | 12 | } -------------------------------------------------------------------------------- /Utils/Pract_is_3/Pract02/StructureSize/img/structC.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Angeld55/Object-oriented_programming_FMI/56245c795618b1b575e2c63963773ae0d4f66ace/Utils/Pract_is_3/Pract02/StructureSize/img/structC.jpg -------------------------------------------------------------------------------- /Utils/Pract_is_3/Pract02/StructureSize/img/structD.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Angeld55/Object-oriented_programming_FMI/56245c795618b1b575e2c63963773ae0d4f66ace/Utils/Pract_is_3/Pract02/StructureSize/img/structD.jpg -------------------------------------------------------------------------------- /Utils/Pract_is_3/Pract02/StructureSize/img/transpose.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Angeld55/Object-oriented_programming_FMI/56245c795618b1b575e2c63963773ae0d4f66ace/Utils/Pract_is_3/Pract02/StructureSize/img/transpose.png -------------------------------------------------------------------------------- /Utils/Pract_is_3/Pract02/student_data.txt: -------------------------------------------------------------------------------- 1 | FN12345678;Иван Иванов;SI;4.82 2 | FN23456789;Петър Петров;IS;5.67 3 | FN34567890;Георги Георгиев;KN;3.45 4 | FN45678901;Мария Маринова;IN;5.12 5 | FN56789012;Ирина Димитрова;SI;4.25 6 | FN67890123;Анна Николова;IN;3.98 7 | FN78901234;Николай Станимиров;KN;4.75 8 | FN89012345;Димитър Теодоров;IS;5.33 9 | FN90123456;Станимир Ангелов;SI;4.65 10 | FN01234567;Теодора Илиева;KN;4.88 -------------------------------------------------------------------------------- /Utils/Pract_is_3/Pract03/Task2_Solution.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void writeInBinFile(std::ofstream& ofs, const int* arr, unsigned size) 5 | { 6 | ofs.write((const char*)arr, size * sizeof(int)); 7 | } 8 | 9 | void writeInBinFile(const char* fileName, const int* arr, unsigned size) 10 | { 11 | std::ofstream ofs(fileName, std::ios::binary); 12 | if (!ofs.is_open()) 13 | { 14 | return; 15 | } 16 | 17 | writeInBinFile(ofs, arr, size); 18 | } 19 | 20 | unsigned fileSize(std::ifstream& ifs) 21 | { 22 | unsigned curr = ifs.tellg(); 23 | ifs.seekg(0, std::ios::end); 24 | unsigned res = ifs.tellg(); 25 | ifs.seekg(curr, std::ios::beg); 26 | ifs.clear(); 27 | return res; 28 | } 29 | 30 | int* readFromBinFile(std::ifstream& ifs, unsigned& size) 31 | { 32 | unsigned sizeOfFile = fileSize(ifs); 33 | size = sizeOfFile / sizeof(int); 34 | 35 | int* arr = new int[size]; 36 | ifs.read((char*)arr, sizeOfFile); 37 | return arr; 38 | } 39 | 40 | int* readFromBinFile(const char* fileName, unsigned& size) 41 | { 42 | std::ifstream ifs(fileName, std::ios::binary); 43 | if (!ifs.is_open()) 44 | { 45 | return nullptr; 46 | } 47 | 48 | return readFromBinFile(ifs, size); 49 | } 50 | 51 | int main() 52 | { 53 | int arr[5] = { 1,2,3,4,5 }; 54 | writeInBinFile("number.dat", arr, 5); 55 | 56 | unsigned size; 57 | int* arr1 = readFromBinFile("number.dat", size); 58 | 59 | for (size_t i = 0; i < size; i++) 60 | { 61 | std::cout << arr1[i] << ' '; 62 | } 63 | 64 | delete[] arr1; 65 | } 66 | -------------------------------------------------------------------------------- /Utils/Pract_is_3/Pract03/people.dat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Angeld55/Object-oriented_programming_FMI/56245c795618b1b575e2c63963773ae0d4f66ace/Utils/Pract_is_3/Pract03/people.dat -------------------------------------------------------------------------------- /Utils/Pract_is_3/Pract04/README.md: -------------------------------------------------------------------------------- 1 | # Week 04 - Член функции, конструктур и дестурктор 2 | 3 | 4 | ## Задача 1 5 | 6 | Напишете програма, в която се поддържа дневник с оценки на различни предмети. 7 | 8 | Предметът съдържа: 9 | * име с произволна дължина 10 | * масив от тип `unsigned`, който държи произволно на брой оценки за предмета 11 | 12 | Дневникът съдържа: 13 | * произволно на брой предмети 14 | 15 | Реализирайте следните функции за програмата: 16 | * да се поддържа записване в двоичен файл 17 | * да се поддържа четене от двоичен файл 18 | * да се намери средната оценка в дневника, като оценките от предметите бъдат закгръгляни 19 | 20 | ## Задача 2 21 | 22 | Напишете програма, описваща магазин с продукти. 23 | 24 | Магазинът има: 25 | * име (низ с дължина до 30 символа) 26 | * адрес (низ с дължина до 50 символа) 27 | * списък с продукти (броят им е не повече от 100). 28 | * оборот (число, показващо сумата от цените на продадените продукти)
29 | 30 | Продуктът има: 31 | * баркод (уникално число от 0 до 255) 32 | * име (низ с произволна дължина) 33 | * количество (цяло, положително число) 34 | * цена (положително число) 35 | 36 | Реализирайте следните функции за магазина: 37 | - функция, която зарежда продукт в магазина 38 | - функция, която проверява дали има продукт в наличност 39 | - функция, която продава продукт 40 | - функция, която принтира информация за магазин
41 | Помислете какви параметри е удачно да подавате на тези функции и какви помощни функции е необходимо да направите. 42 | 43 | Реализирайте следните функции за продукта: 44 | - функция, която увеличава количеството на продукта 45 | - функция, която принтира информацията за даден продукт 46 | 47 | -------------------------------------------------------------------------------- /Utils/Pract_is_3/Pract05/Interval/HelperFunctions.cpp: -------------------------------------------------------------------------------- 1 | #include "HelperFunctions.h" 2 | #include 3 | 4 | namespace 5 | { 6 | const size_t DIGITS_COUNT = 10; 7 | } 8 | 9 | bool HelperFunctions::isPrime(int num) 10 | { 11 | if (num < 2) 12 | return false; 13 | 14 | if (num == 2) 15 | return true; 16 | 17 | 18 | double sqrtN = sqrt(num); 19 | 20 | 21 | for (int i = 2; i <= sqrtN; i++) 22 | { 23 | if (num % i == 0) 24 | return false; 25 | } 26 | 27 | return true; 28 | } 29 | 30 | int HelperFunctions::reverseNumber(int num) 31 | { 32 | int res = 0; 33 | 34 | while (num != 0) 35 | { 36 | (res *= 10) += num % 10; 37 | num /= 10; 38 | } 39 | 40 | return res; 41 | } 42 | 43 | bool HelperFunctions::isPalindrome(int num) 44 | { 45 | return num == reverseNumber(num); 46 | } 47 | 48 | bool HelperFunctions::isPowOfTwo(int n) 49 | { 50 | if (n < 0) 51 | return false; 52 | 53 | return n == 0 || (n & n - 1) == 0; 54 | } 55 | 56 | bool HelperFunctions::hasOnlyUniqueDigits(int num) 57 | { 58 | bool flags[DIGITS_COUNT] = {}; 59 | 60 | num = num > 0 ? num : -num; 61 | 62 | while (num != 0) 63 | { 64 | int digit = num % 10; 65 | 66 | if (flags[digit]) 67 | return false; 68 | 69 | flags[digit] = true; 70 | 71 | num /= 10; 72 | } 73 | 74 | return true; 75 | } -------------------------------------------------------------------------------- /Utils/Pract_is_3/Pract05/Interval/HelperFunctions.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | namespace HelperFunctions 4 | { 5 | bool isPrime(int num); 6 | int reverseNumber(int num); 7 | bool isPalindrome(int num); 8 | bool isPowOfTwo(int num); 9 | bool hasOnlyUniqueDigits(int num); 10 | } -------------------------------------------------------------------------------- /Utils/Pract_is_3/Pract05/Interval/Interval.cpp: -------------------------------------------------------------------------------- 1 | #include "Interval.h" 2 | #include "HelperFunctions.h" 3 | 4 | unsigned Interval::countCriteria(bool(*pred)(int)) const 5 | { 6 | unsigned count = 0; 7 | for (int i = start; i <= end; i++) 8 | { 9 | if (pred(i)) 10 | count++; 11 | } 12 | 13 | return count; 14 | } 15 | 16 | Interval::Interval(int start, int end) 17 | { 18 | if (start <= end) 19 | { 20 | this->start = start; 21 | this->end = end; 22 | } 23 | } 24 | 25 | unsigned Interval::length() const 26 | { 27 | return end - start + 1; 28 | } 29 | 30 | bool Interval::isInterval(int num) const 31 | { 32 | return start <= num && num <= end; 33 | } 34 | 35 | unsigned Interval::countPrime() const 36 | { 37 | return countCriteria(HelperFunctions::isPrime); 38 | } 39 | 40 | unsigned Interval::countPalindrome() const 41 | { 42 | return countCriteria(HelperFunctions::isPalindrome); 43 | } 44 | 45 | unsigned Interval::countUniqueDigits() const 46 | { 47 | return countCriteria(HelperFunctions::hasOnlyUniqueDigits); 48 | } 49 | 50 | bool Interval::isPowOfTwo() const 51 | { 52 | return HelperFunctions::isPowOfTwo(start) && HelperFunctions::isPowOfTwo(end); 53 | } 54 | 55 | Interval Interval::intersect(const Interval& other) const 56 | { 57 | int start = this->start > other.start ? other.start : this->start; 58 | int end = this->end < other.end ? other.end : this->end; 59 | } 60 | 61 | bool Interval::isSub(const Interval& other) const 62 | { 63 | return start >= other.start && end <= other.end; 64 | } 65 | -------------------------------------------------------------------------------- /Utils/Pract_is_3/Pract05/Interval/Interval.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | class Interval 4 | { 5 | private: 6 | int start = 0; 7 | int end = 0; 8 | 9 | unsigned countCriteria(bool (*pred)(int)) const; 10 | 11 | public: 12 | Interval() = default; 13 | Interval(int start, int end); 14 | 15 | unsigned length() const; 16 | bool isInterval(int num) const; 17 | unsigned countPrime() const; 18 | unsigned countPalindrome() const; 19 | unsigned countUniqueDigits() const; 20 | bool isPowOfTwo() const; 21 | Interval intersect(const Interval& other) const; 22 | bool isSub(const Interval& other) const; 23 | }; -------------------------------------------------------------------------------- /Utils/Pract_is_3/Pract07/ShoppingCartOperators/Product.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | class Product { 5 | char* name = nullptr; 6 | double price = 0; 7 | unsigned quantity = 0; 8 | 9 | void copyFrom(const Product& other); 10 | void free(); 11 | 12 | public: 13 | Product() = default; 14 | Product(const char* name, double price, unsigned quantity); 15 | Product(const Product& other); 16 | Product& operator=(const Product& other); 17 | ~Product(); 18 | 19 | Product& operator++(); 20 | Product operator++(int); 21 | 22 | void setName(const char* name); 23 | void setPrice(double price); 24 | void setQuantity(unsigned quantity); 25 | 26 | const char* getName() const; 27 | double getPrice() const; 28 | unsigned getQuantity() const; 29 | 30 | 31 | friend std::istream& operator>>(std::istream& is, Product& product); 32 | }; 33 | 34 | std::ostream& operator<<(std::ostream& os, const Product& product); -------------------------------------------------------------------------------- /Utils/Pract_is_3/Pract07/ShoppingCartOperators/ShoppingCart.cpp: -------------------------------------------------------------------------------- 1 | #include "ShoppingCart.h" 2 | 3 | void ShoppingCart::resize(unsigned newCapacity) 4 | { 5 | Product* newProducts = new Product[newCapacity]; 6 | 7 | for (size_t i = 0; i < count; i++) 8 | { 9 | newProducts[i] = products[i]; 10 | } 11 | 12 | delete[] products; 13 | products = newProducts; 14 | } 15 | 16 | ShoppingCart::ShoppingCart() 17 | { 18 | products = new Product[capacity]; 19 | } 20 | 21 | ShoppingCart& ShoppingCart::operator+=(const Product& product) 22 | { 23 | if (count >= capacity) 24 | { 25 | resize(capacity * 2); 26 | } 27 | 28 | products[count++] = product; 29 | } 30 | 31 | ShoppingCart& ShoppingCart::operator-=(const Product& product) 32 | { 33 | // TODO: insert return statement here 34 | } 35 | 36 | const Product& ShoppingCart::operator[](size_t index) const 37 | { 38 | return products[index]; 39 | } 40 | 41 | Product& ShoppingCart::operator[](size_t index) 42 | { 43 | return products[index]; 44 | } 45 | -------------------------------------------------------------------------------- /Utils/Pract_is_3/Pract07/ShoppingCartOperators/ShoppingCart.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "Product.h" 3 | 4 | class ShoppingCart { 5 | private: 6 | Product* products = nullptr; 7 | unsigned count = 0; 8 | unsigned capacity = 16; 9 | 10 | void free(); 11 | void copyFrom(const ShoppingCart& other); 12 | void resize(unsigned newCapacity); 13 | 14 | public: 15 | ShoppingCart(); 16 | ShoppingCart(const ShoppingCart& other); 17 | ShoppingCart& operator=(const ShoppingCart& other); 18 | ~ShoppingCart(); 19 | 20 | ShoppingCart& operator+=(const Product& product); 21 | ShoppingCart& operator-=(const Product& product); 22 | 23 | const Product& operator[](size_t index) const; 24 | Product& operator[](size_t index); 25 | }; -------------------------------------------------------------------------------- /Utils/Pract_is_3/Pract08/README.md: -------------------------------------------------------------------------------- 1 | # Тема 8: Статик. 2 | 3 | ## Задача 4 | 5 | Реализирайте клас `Dictionary`. Класът представлява колекция от думи (стринг) и описания (стринг) поддържа следните операции: 6 | 7 | * add(word, description) - добавя думата в речника. Ако думата вече присъства, да се добави новото описание към старото 8 | * remove(word, description) - премахва думата от речника 9 | * print() - отпечатва съдържанието на речника 10 | * оператор (word) - връща описанието на думата. Ако тя не присъства, програмата хвърля грешка 11 | * оператор += - добавя съдържанието на десния речник към левия 12 | * оператор + - връща нов речник, съставен от думите на двата речника 13 | 14 | Класът трябва да осигурява логаритмично време за намиране на дума. 15 | 16 | *Пояснение: думите трябва да се съхраняват в сортиран ред* -------------------------------------------------------------------------------- /Utils/Pract_is_3/Pract09/README.md: -------------------------------------------------------------------------------- 1 | # Week 09 2 | 3 | ## Задача 1. Foodpanda 4 | Създайте система за обработка на поръчки на храна за вкъщи. 5 | 6 | `Restaurant`
7 | Клас, описващ ресторант. Всеки ресторант има име до 25 символа. Също така има и списък от продукти (с произволна дължина, която се подава в конструктора).
8 | Всеки продукт е низ с прозволна дължина. Поддържаме следните функционалности: 9 | - добавяне на продукт 10 | - получаване на поръчка 11 | 12 | `Order`
13 | Клас, описващ поръчка. Всяка поръчка има:
14 | - **име** на ресторанта, за който е
15 | - брой продукти
16 | - списък с продуктите
17 | 18 | Ако в поръчката има продукт, който ресторантът не предлага, той хвърля грешка. В противен случай връща времето за доставка (времето е в минути, изберете и реализирайте начин за пресмятане на времето за доставка). 19 | 20 | `Foodpanda`
21 | Създаите клас `Foodpanda`, който има списък с ресторанти (отново с произволна дължина, която се задава в конструктора)
22 | Класът трябва да прочита поръчки **от конзолата**.
23 | Класът намира за кой ресторант е поръчката, ако има такъв, в противен случай изписва, че поръчката е невалидна, понеже такъв ресторант не съществува.
24 | Ако ресторантът съществува, му я изпраща. Ако той хвърли грешка, Foodpanda я хваща и изписва съобщение, че даденият ресторант не предалага някой продукт от тези в поръчката. 25 | 26 | За всеки клас реализирайте нужните конструктори. Реализирайте move семантики. Бонус: Направете метод за добавяне на нови ресторанти в Foodpanda 27 | 28 | -------------------------------------------------------------------------------- /Utils/Pract_is_3/Pract13/README.md: -------------------------------------------------------------------------------- 1 | # Седмица 13 - Темплейт 2 | 3 | ## Задача 1 4 | Направете тепмлейтен клас `MyVector`, който има в себе си нужните данни за един оразмеряващ се масив. Направете следните методи за класа. 5 | 6 | * ``void pushBack (...)`` - добавя елемент в края на масива 7 | * ``void popBack()`` - премахва елемент от края на масива 8 | * ``void insert(size_t ind, ...)`` - вмъква елемент на даден индекс 9 | * `void remove(size_t ind)` - премахва елемент от даден индекс 10 | * `size_t count()` - връща броя на елементите 11 | * `bool isEmpty()` - връща дали има елементи 12 | * `... back()` - връща последния елемент 13 | * `... operator[](size_t ind)` - връща елемент на даден индекс 14 | * `void clear()` - премахва всички елементи от масива 15 | 16 | Помислете какво трябва да се постави на мястото `...` 17 | 18 | ### Бонус 19 | Направете темплейтна специлизация за типа ``bool`` 20 | 21 | ## Задача 2 22 | `ArrayView` 23 | 24 | Реализирайте клас, който да представя частичен изглед за масив от обекти. 25 | 26 | Класът трябва да поддържа операции за: 27 | - Взимане на подмасив (приема начало и дължина) - връща нов обект 28 | - Отпечатване на съдържанието 29 | - Извеждане на броя елементи в изгледа 30 | - **Константен** оператор за достъп до елемент 31 | -------------------------------------------------------------------------------- /Utils/Pract_is_3/Pract14/README.md: -------------------------------------------------------------------------------- 1 | # Week 14 - Дървовидна структура. Множествено наследяване 2 | 3 | 4 | ## Задача 1 5 | Реализирайте файлова система в стил Linux 6 | 7 | Файловата система е съставена от файлове. Всеки файл има: 8 | - име (не по-дълго от 32 символа) 9 | - метод, който да принтира съдържанието му 10 | 11 | Двата вида файлове, които трябва да се поддържат са: 12 | 13 | **Текстов файл** - съдържа масив от символи, представляващи съдържанието му. Методът за принтиране на съдържание да отпечатва на конзолата текстовото съдържание на файла в следния вид: 14 | 15 | ``` 16 | <име на файл>: 17 | ------------- 18 | <съдържание на файла> 19 | ``` 20 | 21 | **Директория** - съдържа неограничен брой файлове (може да съдържа и директории). Методът ѝ за принтиране отпечатва името на директорията, както и **имената** на всички файлове в нея. Ако някой от файловете е директория, освен името ѝ, отпечатва и съдържанието ѝ. 22 |
23 | Да се добави метод за добавяне на файл към директория. 24 | 25 | Пример за отпечатване на съдържанието на директория 26 | ``` 27 | - root 28 | - Folder1 29 | - file1.txt 30 | - file2.txt 31 | - Folder2 32 | - file3.txt 33 | 34 | ``` -------------------------------------------------------------------------------- /Utils/Pract_si_3/Pract01/snippets.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | //Initialization of enum class 3 | 4 | namespace day { 5 | enum class Day 6 | { 7 | MONDAY, //0 8 | TUESDAY, //1 9 | WEDNESDAY, //2 10 | THURSDAY, //3 11 | FRIDAY, //4 12 | SATURDAY, //5 13 | SUNDAY, //6 14 | UNKNOWN //default case 15 | }; 16 | 17 | Day initDay(int num) { 18 | switch (num) { 19 | case 0: return Day::MONDAY; 20 | case 1: return Day::TUESDAY; 21 | case 2: return Day::WEDNESDAY; 22 | case 3: return Day::THURSDAY; 23 | case 4: return Day::FRIDAY; 24 | case 5: return Day::SATURDAY; 25 | case 6: return Day::SUNDAY; 26 | default: return Day::UNKNOWN; 27 | } 28 | } 29 | 30 | void printDay(Day day) { 31 | using std::cout; 32 | using std::endl; 33 | switch (day) { 34 | case Day::MONDAY: cout << "Monday" << endl; break; 35 | case Day::TUESDAY: cout << "Tuesday" << endl; break; 36 | case Day::WEDNESDAY: cout << "Wednesday" << endl; break; 37 | case Day::THURSDAY: cout << "Thursday" << endl; break; 38 | case Day::FRIDAY: cout << "Friday" << endl; break; 39 | case Day::SATURDAY: cout << "Saturday" << endl; break; 40 | case Day::SUNDAY: cout << "Sunday" << endl; break; 41 | default: cout << "Unknown day" << endl; break; 42 | } 43 | } 44 | } 45 | 46 | int main() 47 | { 48 | using namespace day; 49 | 50 | int n; 51 | std::cin >> n; 52 | Day d = initDay(n); 53 | printDay(d); 54 | } 55 | -------------------------------------------------------------------------------- /Utils/Pract_si_3/Pract02/notANumber.txt: -------------------------------------------------------------------------------- 1 | ab -------------------------------------------------------------------------------- /Utils/Pract_si_3/Pract02/numbers.txt: -------------------------------------------------------------------------------- 1 | 1 2 | 2 -------------------------------------------------------------------------------- /Utils/Pract_si_3/Pract03/README.md: -------------------------------------------------------------------------------- 1 | ## Задачи 2 | 3 | **1.** Да се напише програма, която прочита две матрици от два различни файла, умножава ги и записва резултата в нов отделен файл. Матриците се съхраняват в отделни файлове в следния формат: 4 | 5 | Пример за матрица 3х3 : 6 | ```3,3,1|1,1,3|3,3,1``` 7 | 8 | 9 | **2.** Да се създаде структура `Product`, която се описва със следните характеристики: 10 | - име на продукта (до 100 символа); 11 | - количество в наличност (цяло число); 12 | - цена на продукта (дробно число); 13 | - категория на продукта - `ELECTRONICS`, `CLOTHING`, `BOOKS`, `FOOD` или `BEAUTY`; 14 | - доставчик на продукта (до 100 символа); 15 | 16 | Да се създаде програма, която управлява склад от продукти, като информацията се съхранява в двоичен файл. 17 | Нека програмата поддържа следните функционалности: 18 | - Зареждане на продуктите от двоичен файл в паметта; 19 | - По подаден двоичен файл да се вкарат n продукта, като информация за тях се чете от конзолата. Ако информацията, въведена за някой продукт, е валидна, и ако няма вече такова име на продукт във файла, продуктът се запазва в двоичния файл. 20 | - Промяна на информацията за наличното количество от даден продукт и записване на новите данни във файла. 21 | - Извеждане на информация за всички продукти от склада; 22 | - Извеждане на информация за конкретен продукт по подадено име; 23 | - По подадено име на друг файл и категория да се запишат всички продукти от дадената категория в съответния файл; 24 | -------------------------------------------------------------------------------- /Utils/Pract_si_3/Pract05/blitz_test02.md: -------------------------------------------------------------------------------- 1 | ## Задачи Blitz Test №2 2 | 3 | **1.** Ще се компилира ли следният код? Ако не, защо? 4 | ```c++ 5 | #include 6 | 7 | class A { 8 | public: 9 | void f() const 10 | { 11 | g(); 12 | } 13 | void g() const{} 14 | }; 15 | ``` 16 | 17 | **2.** Ще се компилира ли следният код? Ако не, защо? 18 | ```c++ 19 | #include 20 | 21 | class A { 22 | public: 23 | void t() {} 24 | void foo() const 25 | { 26 | t(); 27 | } 28 | }; 29 | ``` 30 | 31 | **3.** Кои от следните твърдения са верни (отбележете с **да** или **не** за всяко едно): 32 | - Можем да викаме в конструктор друг конструктор на същия клас; 33 | - Можем да имаме няколко деструктора и няколко конструктора; 34 | - Можем да имаме няколко деструктора, но само един конструктор; 35 | - Можем да имаме няколко конструктора, но само един деструктор; 36 | - Можем да имаме само един конструктор и само един деструктор; 37 | - Задължително трябва да имаме конструктор и деструктор в класа; 38 | - Ако си напишем конструктор с параметри, то дефолтния конструктор се запазва; 39 | - Ако си напишем конструктор с параметри, то за да ползваме дефолтния конструктор трябва да напишем и него. 40 | 41 | 42 | 43 | **4.** Реализирайте конструктор с параметри, мутатори (сетъри) и селектори (гетъри) за следния клас: 44 | ```c++ 45 | class Book { 46 | double price; 47 | unsigned pageCount; 48 | char name[128]; 49 | }; 50 | ``` 51 | 52 | **5.** Посочете грешките в кода: 53 | ```c++ 54 | #include 55 | class Point { 56 | int x; 57 | int y; 58 | 59 | Point(int x, int y) { 60 | x = x; 61 | y = y; 62 | } 63 | }; 64 | int main() 65 | { 66 | Point p1; 67 | } 68 | ``` 69 | -------------------------------------------------------------------------------- /Utils/Pract_si_3/Pract07/README.md: -------------------------------------------------------------------------------- 1 | ## Задачи 2 | 3 | **1.** Реализирайте клас **Матрица** с *произволни размери*. Реализирайте: 4 | - конструктор с параметри - 2 числа, които да определят размера на матрицата 5 | - конструктор по подразбиране (по default размерите са 2х2) 6 | 7 | Оператори: 8 | - `+=` - за събиране на матрици 9 | - `+` 10 | - `-=` - за изваждане на матрици 11 | - `-` 12 | - `*=` - за умножаване на матрици (стига да е възможно) 13 | - `*` 14 | - `*=` - за умножаване на матрица с число 15 | - `*` 16 | - `==` - 2 матрици са равни, ако всичките им елементи са равни 17 | - `!=` 18 | - `[]` - връща реда от матрицата на съответния индекс (за константен и неконстантен достъп) 19 | - `operator bool` - връща `false`, ако матрицата е нулевата. В противен случай връща `true`. Помислете за оптимизация на този оператор. *Hint: mutable* 20 | -------------------------------------------------------------------------------- /Utils/Pract_si_3/Pract07/blitz_test_03.md: -------------------------------------------------------------------------------- 1 | # Блиц тест №3 2 | 3 | **1.** Какво ще изкара следният код? 4 | ```c++ 5 | #include 6 | 7 | class A { 8 | public: 9 | A() { 10 | std::cout << "A()"; 11 | } 12 | A(const A& other) { 13 | std::cout << "CC of A()"; 14 | } 15 | A& operator=(const A& other) { 16 | std::cout << "OP= of A()"; 17 | return *this; 18 | } 19 | ~A() { 20 | std::cout << "~A()"; 21 | } 22 | }; 23 | 24 | class B { 25 | public: 26 | B() { 27 | std::cout << "B()"; 28 | } 29 | B(const B& other) { 30 | std::cout << "CC of B()"; 31 | } 32 | B& operator=(const B& other) { 33 | std::cout << "OP= of B()"; 34 | return *this; 35 | } 36 | ~B() { 37 | std::cout << "~B()"; 38 | } 39 | }; 40 | 41 | class X { 42 | A obj1; 43 | B obj2; 44 | public: 45 | X(const A& a, const B& b) { 46 | obj1 = a; 47 | obj2 = b; 48 | std::cout << "X()"; 49 | } 50 | 51 | ~X() { 52 | std::cout << "~X()"; 53 | } 54 | }; 55 | 56 | int main() { 57 | A obj1; 58 | B obj2; 59 | X obj(obj1, obj2); 60 | } 61 | ``` 62 | 63 | **2.** Разпишете голяма четворка на следния клас: 64 | ```c++ 65 | class Student { 66 | char* name = nullptr; 67 | int* grades = nullptr; 68 | size_t gradesCount; 69 | int fn; 70 | 71 | public: 72 | /*...*/ 73 | }; 74 | ``` 75 | -------------------------------------------------------------------------------- /Utils/Pract_si_3/Pract08/readme.md: -------------------------------------------------------------------------------- 1 | ## Задачи 2 | 3 | **Задача 1.** Реализирайте клас **StringVector**, който представлява динамична колекция от `String` обекти и има минимум следните функции: 4 | 5 | * [**push_back**](https://cplusplus.com/reference/vector/vector/push_back/) - добавя елемент в края на вектора 6 | * [**pop_back**](https://cplusplus.com/reference/vector/vector/pop_back/) - премахва последния елемент на вектора 7 | * [**insert**](https://cplusplus.com/reference/vector/vector/insert/) - добавя елемент на даден индекс във вектора 8 | * [**erase**](https://cplusplus.com/reference/vector/vector/erase/) - изтрива елемент на даден индекс във вектора 9 | * [**clear**](https://cplusplus.com/reference/vector/vector/clear/) - изчиства данните във вектора 10 | * [**operator[]**](https://cplusplus.com/reference/vector/vector/operator[]/) - позволява индексация на елементите във вектора (работи в константно и неконстантно) 11 | * [**empty**](https://cplusplus.com/reference/vector/vector/empty/) - връща дали векторът е празен 12 | * [**size**](https://cplusplus.com/reference/vector/vector/size/) - връща броя на елементите във вектора 13 | 14 | *Bonus:* добавете каквито прецените други фунцкии и оператори, които биха били смислени и полезни. (Пр: оператори за вход и изход от поток) 15 | 16 | За реализацията на класа използвайте предоставения клас String и неговите методи. При невалидни входни данни, погрижете се класът да сигнализира с подходящи изключения. 17 | -------------------------------------------------------------------------------- /Utils/Pract_si_3/Pract10/readme.md: -------------------------------------------------------------------------------- 1 | # Задачи 2 | 3 | **1.** Реализирайте клас `Ticket`, който описва билет за театрална постановка. Всеки билет има име на постановката от тип `MyString` и цена от тип `double`. Направете подходящи конструктори. 4 | 5 | Реализирайте клас `Student Ticket`, който е 2 пъти по-евтин. В конструктора си приема име и оригинална цена за постановката. 6 | Реализирайте клас `Group Ticket`, който е с 20% по-евтин от нормалния. 7 | Направете подходящи функции за принтиране на информацията за билетите. 8 | 9 | **2.** Създайте клас `Student`, който съдържа следната информация: 10 | * име (от тип *MyString*); 11 | * факултетен номер (от тип *unsigned*); 12 | * курс, в който учи (от тип *unsigned*). 13 | 14 | Да се реализира клас `StudentDB`, който представлява база от данни за съхранение на информацията за студенти. Класът да поддържа следните функционалности: 15 | * `add` - добавяне студент в базата; 16 | * `remove` - премахване на студент от базата по подаден факултетен номер; 17 | * `find` - търсене на студент в базата по подаден факултетен номер; 18 | * `display` - визуализира информация за базата данни. 19 | 20 | Да се реализира клас `SortedStudentDB`, който наследява `StudentDB` и поддържа следната допълнителна функционалност: 21 | * `sortBy` - запазва студентите сортирани по подаден критерий; 22 | 23 | Да се реализира клас `FilteredStudentDB`, който наследява `StudentDB` и поддържа следните допълнителни функционалности: 24 | * `filter` - по подаден критерий запазва в базата данни само студентите, които го изпълняват; 25 | * `limit` - по подаден брой **N** запазва само първите **N** студенти в базата. 26 | -------------------------------------------------------------------------------- /Utils/Pract_si_3/Pract10/snippets/inheritancePrinting.cpp: -------------------------------------------------------------------------------- 1 | //#include 2 | // 3 | //class User { 4 | //public: 5 | // User() { 6 | // std::cout << "User()" << std::endl; 7 | // } 8 | // User(const User& other) { 9 | // std::cout << "CC of User()" << std::endl; 10 | // } 11 | // User(User&& other) noexcept { 12 | // std::cout << "MC of User()" << std::endl; 13 | // } 14 | // User& operator=(const User& other) { 15 | // std::cout << "OP= of User()" << std::endl; 16 | // return *this; 17 | // } 18 | // User& operator=(User&& other) noexcept { 19 | // std::cout << "MOP= of User()" << std::endl; 20 | // return *this; 21 | // } 22 | // ~User() { 23 | // std::cout << "~User()" << std::endl; 24 | // } 25 | //}; 26 | // 27 | //class PremiumUser : public User { 28 | //public: 29 | // PremiumUser() { 30 | // std::cout << "PremiumUser()" << std::endl; 31 | // } 32 | // PremiumUser(const PremiumUser& other) : User(other) { 33 | // std::cout << "CC of PremiumUser()" << std::endl; 34 | // } 35 | // PremiumUser(PremiumUser&& other) noexcept : User(std::move(other)) { 36 | // std::cout << "MC of PremiumUser()" << std::endl; 37 | // } 38 | // PremiumUser& operator=(const PremiumUser& other) { 39 | // User::operator=(other); 40 | // std::cout << "OP= of PremiumUser()" << std::endl; 41 | // return *this; 42 | // } 43 | // PremiumUser& operator=(PremiumUser&& other) noexcept { 44 | // User::operator=(std::move(other)); 45 | // std::cout << "MOP= of PremiumUser()" << std::endl; 46 | // return *this; 47 | // } 48 | // ~PremiumUser() { 49 | // std::cout << "~PremiumUser()" << std::endl; 50 | // } 51 | //}; 52 | // 53 | //int main() 54 | //{ 55 | // PremiumUser p1; 56 | // PremiumUser p2 = p1; 57 | // PremiumUser p3; 58 | // p3 = p2; 59 | // p3 = std::move(p1); 60 | //} 61 | -------------------------------------------------------------------------------- /Utils/Pract_si_3/Pract10/snippets/passingToFunctions.cpp: -------------------------------------------------------------------------------- 1 | //#include 2 | // 3 | //class A { 4 | //public: 5 | // int x; 6 | //}; 7 | //class B : public A { 8 | //public: 9 | // int y; 10 | //}; 11 | // 12 | //void acceptCopyOfA(A obj) {} 13 | //void acceptCopyOfB(B obj) {} 14 | //void acceptRefOfA(A& ref) {} 15 | //void acceptRefOfB(B& ref) {} 16 | //void acceptPtrOfA(A* ptr) {} 17 | //void acceptPtrOfB(B* ptr) {} 18 | //void acceptRvalueRefOfA(A&& ptr) {} 19 | //void acceptRvalueRefOfB(B&& ptr) {} 20 | // 21 | //int main() 22 | //{ 23 | // A a; 24 | // B b; 25 | // acceptCopyOfA(a); 26 | // acceptCopyOfA(b); //only if b has inherited a as public 27 | // acceptCopyOfB(a); //not allowed 28 | // acceptCopyOfB(b); 29 | // acceptRefOfA(a); 30 | // acceptRefOfA(b); //only if b has inherited a as public 31 | // acceptRefOfB(a); //not allowed 32 | // acceptRefOfB(b); 33 | // acceptRvalueRefOfA(std::move(a)); 34 | // acceptRvalueRefOfA(std::move(b)); //only if b has inherited a as public 35 | // acceptRvalueRefOfB(std::move(a)); //not allowed 36 | // acceptRvalueRefOfB(std::move(b)); 37 | // acceptPtrOfA(&a); 38 | // acceptPtrOfA(&b); //only if b has inherited a as public 39 | // acceptPtrOfB(&a); //not allowed 40 | // acceptPtrOfB(&b); 41 | //} 42 | -------------------------------------------------------------------------------- /Utils/Pract_si_3/Pract10/snippets/placementNewExample.cpp: -------------------------------------------------------------------------------- 1 | //#include 2 | // 3 | //class Example { 4 | // int a; 5 | // 6 | //public: 7 | // int getA() const{ 8 | // return a; 9 | // } 10 | // 11 | // void setA(int a) { 12 | // this->a = a; 13 | // } 14 | //}; 15 | // 16 | //int main() 17 | //{ 18 | // //allocates memory for 3 Example objects 19 | // Example* ptr = (Example*) new char[3 * sizeof(Example)]; 20 | // 21 | // //allocates ex1 at the address of ptr[0] 22 | // Example* ex1 = new (&ptr[0]) Example; 23 | // 24 | // //allocates ex2 at the address of ptr[1] 25 | // Example* ex2 = new (&ptr[1]) Example; 26 | // 27 | // ex1->setA(3); 28 | // ex2->setA(42); 29 | // 30 | // std::cout << ex1->getA() << std::endl; 31 | // std::cout << ex2->getA() << std::endl; 32 | // 33 | // //we should always call the destructors explicitly!!! 34 | // ex1->~Example(); 35 | // ex2->~Example(); 36 | // 37 | // delete[]((char*)ptr); 38 | //} 39 | -------------------------------------------------------------------------------- /Utils/Pract_si_3/Pract13-14/blitz_test_7.md: -------------------------------------------------------------------------------- 1 | # Blitz Test №7 2 | **1.** Кои са необходимите функции, които типа `T` трябва да притежава, за да бъде приложима шаблонната функция `areEqual`? 3 | ```c++ 4 | template 5 | bool areEqual(const T& lhs, const T& rhs) 6 | { 7 | if (lhs.size() != rhs.size()) 8 | { 9 | return false; 10 | } 11 | 12 | for (size_t i = 0; i < lhs.size(); i++) 13 | { 14 | if (lhs[i] != rhs[i]) 15 | { 16 | return false; 17 | } 18 | } 19 | 20 | return true; 21 | } 22 | ``` 23 | 24 | **2.** Напишете **шаблонна** функция `linearSearch`, която извършва линейно търсене измежду елементите на подаден `Vector` от обекти. Функцията приема вектор от обекти от шаблонен тип, както и търсения обект. Резултатът от функцията е индекса на намерения елемент, а ако него го няма - връща `-1`. 25 | -------------------------------------------------------------------------------- /Utils/SI_K1_Solutions/HexModifier/HexModifier.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | class HexModifier 5 | { 6 | char* destPath = nullptr; 7 | unsigned char* data = nullptr; 8 | size_t dataSize = 0; 9 | 10 | mutable bool isChanged = false; 11 | 12 | void free(); 13 | void copyFrom(const HexModifier& other); 14 | public: 15 | HexModifier(const char* srcPath); 16 | HexModifier(const char* srcPath, const char* destPath); 17 | 18 | HexModifier(const HexModifier& other); 19 | HexModifier& operator=(const HexModifier& other); 20 | ~HexModifier(); 21 | 22 | void changeByte(unsigned int index, const char* newByte); 23 | void save() const; 24 | 25 | friend std::ostream& operator<<(std::ostream& os, const HexModifier& modifier); 26 | friend std::istream& operator>>(std::istream& is, HexModifier& modifier); 27 | }; -------------------------------------------------------------------------------- /Utils/SI_K1_Solutions/ThreeNumbersWrapperCondition/ThreeNumbersWrapperCondition.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | namespace CustomPredicates { 4 | bool allValid(int, int, int); 5 | } 6 | 7 | class ThreeNumbersWrapperCondition 8 | { 9 | int a = 0, b = 0, c = 0; 10 | bool (*predicate) (int, int, int) = CustomPredicates::allValid; 11 | 12 | bool good = true; 13 | 14 | mutable bool isModified = true; 15 | mutable size_t elementsBeforeCount = 0; 16 | 17 | bool isValidValue(int value) const; 18 | bool goToNextElement(); 19 | void validateState(); 20 | public: 21 | ThreeNumbersWrapperCondition() = default; 22 | ThreeNumbersWrapperCondition(bool (*predicate) (int, int, int)); 23 | ThreeNumbersWrapperCondition(int newA, int newB, int newC, bool (*predicate) (int, int, int)); 24 | 25 | void setVector(int newA, int newB, int newC); 26 | void setA(int newA); 27 | void setB(int newB); 28 | void setC(int newC); 29 | 30 | int getA() const; 31 | int getB() const; 32 | int getC() const; 33 | 34 | void goToNextValidElement(); 35 | int getIndex() const; 36 | bool isGood() const; 37 | 38 | friend int compare(const ThreeNumbersWrapperCondition& lhs, const ThreeNumbersWrapperCondition& rhs); 39 | }; -------------------------------------------------------------------------------- /Week 01/Rational.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | 6 | struct Rational 7 | { 8 | int nom; 9 | int denom; 10 | }; 11 | 12 | bool isValid(const Rational& rat) 13 | { 14 | return rat.denom != 0; 15 | } 16 | 17 | void printRational(const Rational& rat) 18 | { 19 | std::cout << rat.nom << " / " << rat.denom << std::endl; 20 | } 21 | 22 | unsigned getGcd(unsigned a, unsigned b) 23 | { 24 | if(a < b) 25 | std::swap(a, b); 26 | 27 | while(b != 0) 28 | { 29 | int temp = a % b; 30 | a = b; 31 | b = temp; 32 | } 33 | return a; 34 | } 35 | 36 | void rationalize(Rational& rat) 37 | { 38 | assert(isValid(rat)); 39 | 40 | unsigned gcd = getGcd(rat.nom, rat.denom); 41 | rat.denom /= gcd; 42 | rat.nom /= gcd; 43 | if (rat.nom < 0 && rat.denom < 0 || rat.nom > 0 && rat.denom < 0) 44 | { 45 | rat.nom *= -1; 46 | rat.denom *= -1; 47 | } 48 | } 49 | 50 | Rational& plusEq(Rational& lhs, const Rational& rhs) 51 | { 52 | assert(isValid(lhs) && isValid(rhs)); 53 | lhs.nom *= rhs.denom; 54 | lhs.nom += rhs.nom*lhs.denom; 55 | lhs.denom *= rhs.denom; 56 | rationalize(lhs); 57 | return lhs; 58 | } 59 | 60 | Rational plusRationals(const Rational& lhs, const Rational& rhs) 61 | { 62 | assert(isValid(lhs) && isValid(rhs)); 63 | Rational lhsCopy = lhs; 64 | plusEq(lhsCopy, rhs); 65 | return lhsCopy; 66 | } 67 | 68 | int main() 69 | { 70 | Rational r1{1,4}; 71 | Rational r2{1,3}; 72 | 73 | Rational r3 = plusRationals(r1, r2); 74 | 75 | printRational(r3); 76 | 77 | 78 | plusEq(r3, r1); 79 | 80 | printRational(r3); 81 | 82 | 83 | } 84 | 85 | 86 | 87 | -------------------------------------------------------------------------------- /Week 01/convertStringToInt.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | bool isDigit(char ch) { return ch >= '0' && ch <= '9'; } 4 | int convertCharToNumber(char ch) { return ch - '0'; } 5 | 6 | enum class ErrorCode 7 | { 8 | OK, 9 | NullptrGiven, 10 | WrongCharInString, 11 | EmptyString 12 | }; 13 | 14 | struct ConvertResult 15 | { 16 | ErrorCode errCode; 17 | unsigned result; 18 | }; 19 | 20 | ConvertResult convertStringToNumber(const char* str) 21 | { 22 | if (!str) 23 | return { ErrorCode::NullptrGiven, 0}; 24 | 25 | unsigned num = 0; 26 | if(!*str) 27 | return { ErrorCode::EmptyString, num }; 28 | 29 | while (*str) 30 | { 31 | if (!isDigit(*str)) 32 | return { ErrorCode::WrongCharInString, 0 }; 33 | (num *= 10) += convertCharToNumber(*str); 34 | str++; 35 | } 36 | return { ErrorCode::OK, num }; 37 | } 38 | 39 | int main() 40 | { 41 | ConvertResult res = convertStringToNumber("12343"); 42 | 43 | if(res.errCode == ErrorCode::OK) 44 | { 45 | std::cout << res.result << std::endl; 46 | } 47 | else 48 | { 49 | std::cout << "Error!" << std::endl; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /Week 01/enum_example_1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | enum Color { red, green, blue }; // plain enum 4 | enum Card { red_card, green_card, yellow_card }; // another plain enum 5 | enum class Animal { dog, deer, cat, bird, human }; // enum class 6 | enum class Mammal { kangaroo, deer, human }; // another enum class 7 | 8 | int main() 9 | { 10 | 11 | // examples of bad use of plain enums: 12 | Color color = Color::red; 13 | Card card = Card::green_card; 14 | 15 | int num = color; // no problem 16 | 17 | if (color == Card::red_card) // no problem (bad) 18 | cout << "bad" << endl; 19 | 20 | if (card == Color::green) // no problem (bad) 21 | cout << "bad" << endl; 22 | 23 | // examples of good use of enum classes (safe) 24 | Animal a = Animal::deer; 25 | Mammal m = Mammal::deer; 26 | 27 | int num2 = a; // error 28 | if (m == a) // error (good) 29 | cout << "bad" << endl; 30 | 31 | if (a == Mammal::deer) // error (good) 32 | cout << "bad" << endl; 33 | 34 | } 35 | -------------------------------------------------------------------------------- /Week 01/ipAddress.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | union IpAddress 5 | { 6 | uint32_t address; 7 | unsigned char octets[4]; 8 | }; 9 | 10 | int main() 11 | { 12 | IpAddress myAddress; 13 | myAddress.address = 16777343; 14 | 15 | std::cout << (int)myAddress.octets[0] << "." 16 | << (int)myAddress.octets[1] << "." 17 | << (int)myAddress.octets[2] << "." 18 | << (int)myAddress.octets[3]; 19 | 20 | } 21 | -------------------------------------------------------------------------------- /Week 01/isLittleEndian.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | bool isLittleEndian() 4 | { 5 | union endiannessTest { 6 | uint32_t n = 1; 7 | unsigned char bytes[4]; 8 | } myTest; 9 | return myTest.bytes[0]; 10 | } 11 | 12 | int main() 13 | { 14 | std::cout << isLittleEndian(); 15 | 16 | } 17 | -------------------------------------------------------------------------------- /Week 01/struct_example_1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct Point 4 | { 5 | int x; 6 | int y; 7 | }; 8 | 9 | double getDist(const Point& p1, const Point& p2) 10 | { 11 | int dx = p1.x - p2.x; 12 | int dy = p1.y - p2.y; 13 | 14 | return sqrt(dx * dx + dy * dy); 15 | } 16 | 17 | struct Line 18 | { 19 | Point p1; 20 | Point p2; 21 | }; 22 | 23 | double getSlope(const Line& myLine) 24 | { 25 | double dx = myLine.p1.x - myLine.p2.x; 26 | double dy = myLine.p1.y - myLine.p2.y; 27 | 28 | return dy / dx; 29 | 30 | } 31 | 32 | bool areParallel(const Line& line1, const Line& line2) 33 | { 34 | return abs(getSlope(line1) - getSlope(line2)) <= 0.0001; 35 | } 36 | 37 | 38 | int main() 39 | { 40 | Line l1{1,2,3,4}; 41 | Line l2{0,1,2,3}; 42 | 43 | std::cout << areParallel(l1, l2); 44 | 45 | } 46 | -------------------------------------------------------------------------------- /Week 02/1. newLinesCount.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | const char NEW_LINE_CHAR = '\n'; 6 | 7 | int getCharCount(std::ifstream& ifs, char ch) 8 | { 9 | if (!ifs.is_open()) 10 | return -1; 11 | 12 | int count = 0; 13 | char current; 14 | 15 | while (ifs.get(current)) 16 | { 17 | if (current == ch) 18 | ++count; 19 | } 20 | return count; 21 | } 22 | 23 | // we assume that the file have at least one symbol and that there is not an endline symbol at the end. 24 | int getLinesCount(const char* fileName) { 25 | if (!fileName) 26 | return -1; 27 | 28 | std::ifstream ifs(fileName); 29 | if (!ifs.is_open()) 30 | return -1; 31 | 32 | return getCharCount(ifs, NEW_LINE_CHAR) + 1; 33 | } 34 | int main() 35 | { 36 | std::cout << getLinesCount("file.txt"); 37 | } 38 | -------------------------------------------------------------------------------- /Week 02/2. selfPrinting.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main() 6 | { 7 | std::ifstream ifs("selfPrinting.cpp"); 8 | if (!ifs.is_open()) 9 | return -1; 10 | 11 | while (!ifs.eof()) 12 | { 13 | char buff[1024]; 14 | ifs.getline(buff, 1024); 15 | std::cout << buff << std::endl; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Week 02/3. copyFile.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | bool copyTo(const char* fileNameSource, const char* fileNameDest) 5 | { 6 | std::ifstream sourceStream(fileNameSource); 7 | 8 | if (!sourceStream.is_open()) 9 | return false; 10 | 11 | std::ofstream destStream(fileNameDest); 12 | if (!destStream.is_open()) 13 | return false; 14 | 15 | while (!sourceStream.eof()) 16 | { 17 | char buff[1024]; 18 | sourceStream.getline(buff, 1024); 19 | destStream << buff << std::endl; 20 | } 21 | } 22 | int main() 23 | { 24 | std::cout << copyTo("file1.txt", "file2.txt"); 25 | } 26 | -------------------------------------------------------------------------------- /Week 02/img/hierarchy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Angeld55/Object-oriented_programming_FMI/56245c795618b1b575e2c63963773ae0d4f66ace/Week 02/img/hierarchy.png -------------------------------------------------------------------------------- /Week 02/img/stream-flags.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Angeld55/Object-oriented_programming_FMI/56245c795618b1b575e2c63963773ae0d4f66ace/Week 02/img/stream-flags.png -------------------------------------------------------------------------------- /Week 02/img/streams.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Angeld55/Object-oriented_programming_FMI/56245c795618b1b575e2c63963773ae0d4f66ace/Week 02/img/streams.png -------------------------------------------------------------------------------- /Week 03/arrayStudentsStaticName_read.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | struct Student 7 | { 8 | char name[30]; 9 | int age; 10 | int fn; 11 | }; 12 | 13 | size_t getFileSize(ifstream& f) 14 | { 15 | size_t currentPos = f.tellg(); 16 | f.seekg(0, ios::end); 17 | size_t size = f.tellg(); 18 | 19 | f.seekg(currentPos); 20 | return size; 21 | } 22 | 23 | void readFromFile(Student*& ptr, size_t& studentsCount, ifstream& f) 24 | { 25 | size_t sizeOfFile = getFileSize(f); 26 | studentsCount = sizeOfFile / sizeof(Student); 27 | ptr = new Student[studentsCount]; 28 | f.read((char*)ptr, sizeOfFile); 29 | } 30 | 31 | 32 | int main() 33 | { 34 | Student* arr; 35 | size_t count; 36 | ifstream file("students.dat"); 37 | 38 | if(!file.is_open()) 39 | { 40 | std::cout << "Error while opening the file!" << std::endl; 41 | return -1; 42 | } 43 | 44 | readFromFile(arr, count, file); 45 | 46 | for (int i = 0; i < count; i++) 47 | std::cout << "Name: " << arr[i].name << ", age: " << arr[i].age << ", fn: " << arr[i].fn << std::endl; 48 | 49 | delete[] arr; 50 | 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /Week 03/arrayStudentsStaticName_write.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | struct Student 7 | { 8 | char name[30]; 9 | int age; 10 | int fn; 11 | }; 12 | 13 | void initStudent(Student& st, const char* name, int age, int fn) 14 | { 15 | strcpy(st.name, name); 16 | st.age = age; 17 | st.fn = fn; 18 | } 19 | 20 | void saveToFile(const Student* students, size_t count, ofstream& file) 21 | { 22 | file.write((const char*)students, count * sizeof(Student)); 23 | } 24 | 25 | 26 | int main() 27 | { 28 | constexpr size_t size = 4; 29 | Student* arr = new Student[size]; 30 | initStudent(arr[0], "ivan", 44, 1234); 31 | initStudent(arr[1], "petur", 12, 765); 32 | initStudent(arr[2], "alex", 15, 44); 33 | initStudent(arr[3], "katerina", 19, 12134); 34 | 35 | ofstream file("students.dat", ios::binary); 36 | 37 | if(!file.is_open()) 38 | { 39 | std::cout << "Error while opening the file!" << std::endl; 40 | delete[] arr; //! 41 | return -1; 42 | } 43 | 44 | saveToFile(arr, size, file); 45 | 46 | delete[] arr; 47 | 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /Week 03/hexViewer.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | struct HexViewerFile 6 | { 7 | unsigned char* data; 8 | size_t dataSize; 9 | }; 10 | size_t getFileSize(std::ifstream& file) 11 | { 12 | size_t currentPos = file.tellg(); 13 | file.seekg(0, std::ios::end); 14 | size_t fileSize = file.tellg(); 15 | file.seekg(currentPos); 16 | return fileSize; 17 | } 18 | HexViewerFile init(const char* str) 19 | { 20 | std::ifstream ifs(str, std::ios::in | std::ios::binary); 21 | HexViewerFile myFile; 22 | 23 | if(!ifs.is_open()) 24 | { 25 | myFile.data = nullptr; 26 | myFile.dataSize = 0; 27 | return myFile; 28 | } 29 | 30 | myFile.dataSize = getFileSize(ifs); 31 | myFile.data = new unsigned char[myFile.dataSize]; 32 | ifs.read((char*)myFile.data, myFile.dataSize); 33 | 34 | ifs.close(); 35 | return myFile; 36 | } 37 | 38 | void freeHexViewerFile(HexViewerFile& file) 39 | { 40 | delete[] file.data; 41 | file.dataSize = 0; 42 | } 43 | 44 | 45 | bool isValidSymbol(unsigned char ch) 46 | { 47 | return ch >= 'a' && ch <= 'z' || 48 | ch >= 'A' && ch <= 'Z' || 49 | ch >= '0' && ch <= '9'; 50 | } 51 | void print(const HexViewerFile& myFile) 52 | { 53 | for (int i = 0; i < myFile.dataSize; i++) 54 | std::cout << std::hex << std::setw(2) << std::setfill('0') << (int)myFile.data[i] << " "; 55 | std::cout << std::endl; 56 | for (int i = 0; i < myFile.dataSize; i++) 57 | { 58 | if (isValidSymbol(myFile.data[i])) 59 | std::cout << myFile.data[i] << " "; 60 | else 61 | std::cout << ".. "; 62 | } 63 | std::cout << std::endl; 64 | } 65 | 66 | int main() 67 | { 68 | HexViewerFile myFile = init("student.dat"); 69 | print(myFile); 70 | freeHexViewerFile(myFile); 71 | } 72 | -------------------------------------------------------------------------------- /Week 03/numToAndFromBinary.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | 7 | { 8 | int x = 12345; 9 | std::ofstream ofs("num.dat", std::ios::out | std::ios::binary); 10 | ofs.write((const char*)&x, sizeof(x)); 11 | } 12 | { 13 | int n; 14 | std::ifstream ifs("num.dat", std::ios::in | std::ios::binary); 15 | ifs.read((char*)&n, sizeof(n)); 16 | std::cout << n << std::endl; 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /Week 03/replaceInTextFile.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | void replaceInFile(char ch, char ch2, fstream& file) 6 | { 7 | char currentSymbol; 8 | while (file.get(currentSymbol)) 9 | { 10 | if (currentSymbol == ch) 11 | { 12 | file.seekp(-1, std::ios::cur); 13 | file.put(ch2); 14 | file.flush(); 15 | } 16 | } 17 | } 18 | 19 | int main() 20 | { 21 | fstream file("treasureTrail.txt", ios::in | ios::out); 22 | 23 | 24 | if(!file.is_open()) 25 | { 26 | std::cout << "Error while opening the file!" << std::endl; 27 | return -1; 28 | } 29 | 30 | replaceInFile('a', 'X', file); 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /Week 03/studentToBinary.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | struct Student 7 | { 8 | char name[10]; 9 | int age; 10 | int fn; 11 | }; 12 | 13 | 14 | int main() 15 | { 16 | { 17 | std::ofstream ofs("file.dat", std::ios::out | std::ios::binary); 18 | 19 | if(!ofs.is_open()) 20 | return -1; 21 | 22 | Student st{ "Ivan", 10, 1234 }; 23 | 24 | ofs.write((const char*)&st, sizeof(st)); 25 | } 26 | { 27 | Student st; 28 | 29 | std::ifstream ifs("file.dat", std::ios::in | std::ios::binary); 30 | 31 | if(!ifs.is_open()) 32 | return -1; 33 | 34 | ifs.read( (char*)&st, sizeof(Student)); 35 | 36 | std::cout << st.name << " " << st.age << " " << st.fn; 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /Week 03/writeAndReadArrayOfInts.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | 7 | { 8 | const int size = 5; 9 | int arr[size] = {1, 2, 3, 4, 5}; 10 | 11 | std::ofstream ifs("array.dat", std::ios::binary); 12 | ifs.write((const char*)arr, size * sizeof(int)); 13 | } 14 | { 15 | const int size = 5; 16 | int arr[size] = {}; 17 | 18 | std::ifstream ifs("array.dat", std::ios::binary); 19 | ifs.read((char*)arr, size * sizeof(int)); 20 | 21 | for (int i = 0; i < size; i++) 22 | std::cout << arr[i] << " "; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Week 04/Interval/Interval.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | class Interval 4 | { 5 | int _a = INT_MIN; 6 | int _b = INT_MAX; 7 | 8 | public: 9 | Interval(); 10 | Interval(int a, int b); 11 | 12 | void setA(int a); 13 | void setB(int b); 14 | 15 | int getA() const; 16 | int getB() const; 17 | 18 | bool isInInterval(int x) const; 19 | 20 | unsigned getCountCondition(bool (*pred)(int)) const; 21 | 22 | unsigned getPrimesCount() const; 23 | unsigned getPalindromesCount() const; 24 | 25 | bool isSubinterval(const Interval& other) const; 26 | }; 27 | 28 | Interval intersectIntervals(const Interval& lhs, const Interval& rhs); -------------------------------------------------------------------------------- /Week 04/Interval/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "Interval.h" 3 | 4 | int main() 5 | { 6 | Interval v1(1, 10); 7 | 8 | Interval v2(2, 8); 9 | 10 | Interval v3 = intersectIntervals(v1, v2); 11 | 12 | std::cout << v1.getA() << " " << v2.getB() << std::endl; 13 | } 14 | -------------------------------------------------------------------------------- /Week 04/StudentDynanamicName.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | //constructor and destructor example. No copying! 7 | struct Student 8 | { 9 | char* name; 10 | int age; 11 | 12 | Student(const char* name, int age) 13 | { 14 | this->name = new char[strlen(name) + 1]; 15 | strcpy(this->name, name); 16 | this->age = age; 17 | } 18 | 19 | void print() const 20 | { 21 | std::cout << "Name: " << name << ", age: " << age << std::endl; 22 | } 23 | ~Student() 24 | { 25 | delete[] name; 26 | } 27 | }; 28 | int main() 29 | { 30 | Student s("Ivan", 33); 31 | 32 | Student* ptr = new Student("Petur", 17); 33 | 34 | s.print(); 35 | ptr->print(); 36 | 37 | delete ptr; //calls destructor of ptr 38 | }//calls destructor of s 39 | -------------------------------------------------------------------------------- /Week 05/Date, Time, Event/Date/BulgarianDate.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | enum class Month 4 | { 5 | January = 1, 6 | February, 7 | March, 8 | April, 9 | May, 10 | June, 11 | July, 12 | August, 13 | September, 14 | October, 15 | November, 16 | December 17 | }; 18 | 19 | enum class DayOfWeek 20 | { 21 | Monday = 1, 22 | Tuesday, 23 | Wednesday, 24 | Thursday, 25 | Friday, 26 | Saturday, 27 | Sunday 28 | }; 29 | 30 | class BulgarianDate 31 | { 32 | unsigned MAX_DAYS[12] = 33 | { 34 | 31,28,31,30,31,30,31,31,30,31,30,31 35 | }; 36 | unsigned day = 1; 37 | Month month = Month::January; 38 | unsigned year = 1; 39 | 40 | bool isLeapYear() const; 41 | void validateDate(); 42 | bool isDateInValidState = true; 43 | mutable bool isModified = true; //member that can be modified from CONST functions!! 44 | mutable int dayOfWeek = -1; 45 | 46 | public: 47 | BulgarianDate(); 48 | BulgarianDate(unsigned day, unsigned month, unsigned year); 49 | unsigned getDay() const; 50 | unsigned getMonth() const; 51 | unsigned getYear() const; 52 | void setDay(unsigned day); 53 | void setMonth(unsigned month); 54 | void setYear(unsigned year); 55 | void print() const; 56 | void goToNextDay(); 57 | DayOfWeek getDayOfWeek() const; 58 | bool good() const; 59 | void clear(); 60 | }; 61 | 62 | int compareBulgarianDates(const BulgarianDate& lhs, const BulgarianDate& rhs); 63 | -------------------------------------------------------------------------------- /Week 05/Date, Time, Event/Date/main.cpp: -------------------------------------------------------------------------------- 1 | //#include 2 | //#include "Date.h" 3 | 4 | //int main() 5 | //{ 6 | // BulgarianDate d(20,3,2024); 7 | // std::cout << d.getDayOfWeek() << std::endl; 8 | // 9 | // std::cout << d.good() << std::endl; 10 | // 11 | // return 0; 12 | //} 13 | -------------------------------------------------------------------------------- /Week 05/Date, Time, Event/Event/Event.cpp: -------------------------------------------------------------------------------- 1 | #include "Event.h" 2 | #pragma warning(disable : 4996) 3 | 4 | 5 | Event::Event(const char* name, const Date& date, const Time& startTime, const Time& endTime) : _date(date), _startTime(startTime), _endTime(endTime) 6 | { 7 | setName(name); 8 | validateTimes(); 9 | } 10 | 11 | Event::Event(const char* name, unsigned day, unsigned month, unsigned year, 12 | unsigned startTimeHours, unsigned startTimeMins, unsigned startTimeSecs, 13 | unsigned endTimeHours, unsigned endTimeMins, unsigned endTimeSecs) : _date(day, month, year), 14 | _startTime(startTimeHours, startTimeMins, startTimeSecs), 15 | _endTime(endTimeHours, endTimeMins, endTimeSecs) 16 | { 17 | setName(name); 18 | validateTimes(); 19 | } 20 | const char* Event::getName() const 21 | { 22 | return _name; 23 | } 24 | const Date& Event::getDate() const 25 | { 26 | return _date; 27 | } 28 | const Time& Event::getStartTime() const 29 | { 30 | return _startTime; 31 | } 32 | const Time& Event::getEndTime() const 33 | { 34 | return _endTime; 35 | } 36 | 37 | void Event::setName(const char* str) 38 | { 39 | if (strlen(str) > 20) 40 | return; 41 | else 42 | strcpy(_name, str); 43 | } 44 | void Event::validateTimes() 45 | { 46 | //if start > end, swap 47 | if (compareTimes(_startTime, _endTime) > 0) 48 | std::swap(_startTime, _endTime); 49 | } 50 | 51 | Event::Event() : Event("", 1, 1, 1, 0, 0, 0, 0, 0, 0) {} 52 | -------------------------------------------------------------------------------- /Week 05/Date, Time, Event/Event/Event.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "../Time/Time.h" 3 | #include "../Date/BulgarianDate.h" 4 | 5 | typedef BulgarianDate Date; 6 | 7 | class Event 8 | { 9 | char _name[21]; 10 | Date _date; 11 | Time _startTime; 12 | Time _endTime; 13 | 14 | void setName(const char* str); 15 | void validateTimes(); 16 | 17 | public: 18 | Event(); 19 | Event(const char* name, const Date& date, const Time& startTime, const Time& endTime); 20 | 21 | Event(const char* name, unsigned day, unsigned month, unsigned year, 22 | unsigned startTimeHours, unsigned startTimeMins, unsigned startTimeSecs, 23 | unsigned endTimeHours, unsigned endTimeMins, unsigned endTimeSecs); 24 | 25 | const char* getName() const; 26 | const Date& getDate() const; 27 | const Time& getStartTime() const; 28 | const Time& getEndTime() const; 29 | 30 | 31 | 32 | }; 33 | -------------------------------------------------------------------------------- /Week 05/Date, Time, Event/Time/Time.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | constexpr unsigned SECONDS_IN_HOURS = 3600; 7 | constexpr unsigned SECONDS_IN_MINUTE = 60; 8 | constexpr unsigned DAY_SECONDS = 24 * 3600; 9 | 10 | class Time 11 | { 12 | private: 13 | unsigned secondsFromMidnight = 0; 14 | 15 | bool validateAndSet(unsigned lowerBound, unsigned upperBound, unsigned newValue, unsigned oldVlaue, unsigned multiplier); 16 | 17 | public: 18 | Time() = default; 19 | Time(unsigned hours, unsigned mins, unsigned seconds); 20 | 21 | unsigned getHours() const; 22 | unsigned getMins() const; 23 | unsigned getSeconds() const; 24 | 25 | bool setHours(unsigned hours); 26 | bool setMins(unsigned mins); 27 | bool setSeconds(unsigned seconds); 28 | 29 | void tick(); 30 | void serialize(std::ostream& os) const; 31 | }; 32 | int compareTimes(const Time& lhs, const Time& rhs); -------------------------------------------------------------------------------- /Week 05/Date, Time, Event/main.cpp: -------------------------------------------------------------------------------- 1 | #include "Event/Event.h" 2 | 3 | int main() 4 | { 5 | Event e("Party", 31, 12, 2023, 23, 0, 0, 23, 30, 00); 6 | 7 | std::cout << e.getName(); 8 | } -------------------------------------------------------------------------------- /Week 05/Preprocessor/Example1/FuncVsMacro.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | //example for a macro 6 | #define MAX(a,b) (a>b ? a : b) 7 | 8 | using namespace std; 9 | 10 | 11 | int max(int a, int b) 12 | { 13 | return a > b ? a : b; 14 | } 15 | int main() 16 | { 17 | clock_t begin = clock(); 18 | 19 | for (int i = 0; i < 10000000; i++) 20 | max(4, 10); // inline? 21 | 22 | clock_t end = clock(); 23 | cout << "10000000 calls of max function: " << double(end - begin)< 2 | 3 | int main() 4 | { 5 | #include "nz.txt"; 6 | a++; 7 | std::cout << a; 8 | } -------------------------------------------------------------------------------- /Week 05/Preprocessor/Example2/nz.txt: -------------------------------------------------------------------------------- 1 | int a = 1; -------------------------------------------------------------------------------- /Week 06/Bitsets/DynamicSet/DynamicSet.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Angeld55/Object-oriented_programming_FMI/56245c795618b1b575e2c63963773ae0d4f66ace/Week 06/Bitsets/DynamicSet/DynamicSet.h -------------------------------------------------------------------------------- /Week 06/Bitsets/DynamicSet/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "DynamicSet.h" 3 | 4 | int main() 5 | { 6 | 7 | DynamicSet s1(1024); 8 | 9 | s1.add(1); 10 | s1.add(10); 11 | s1.add(5); 12 | s1.print(); 13 | 14 | DynamicSet s2(1024); 15 | 16 | s2.add(1); 17 | 18 | s2.add(17); 19 | s1.add(130); 20 | s1.print(); 21 | 22 | 23 | DynamicSet intersect = UnionOfSets(s1, s2); 24 | DynamicSet uni = IntersectionOfSets(s1, s2); 25 | 26 | intersect.print(); 27 | uni.print(); 28 | 29 | } 30 | -------------------------------------------------------------------------------- /Week 06/Bitsets/StaticSet/StaticSet.cpp: -------------------------------------------------------------------------------- 1 | #include "StaticSet.h" 2 | 3 | unsigned StaticSet::getBucketIndex(unsigned n) const 4 | { 5 | return n / BUCKET_SIZE; 6 | } 7 | unsigned StaticSet::getBitIndex(unsigned n) const 8 | { 9 | return n % BUCKET_SIZE; 10 | } 11 | 12 | void StaticSet::add(unsigned n) 13 | { 14 | if (n > MAX_NUM) 15 | return; 16 | 17 | unsigned bucketIndex = getBucketIndex(n); 18 | unsigned bitIndex = getBitIndex(n); 19 | 20 | uint8_t mask = 1 << bitIndex; 21 | 22 | buckets[bucketIndex] |= mask; 23 | 24 | } 25 | 26 | void StaticSet::remove(unsigned n) 27 | { 28 | unsigned bucketIndex = getBucketIndex(n); 29 | unsigned bitIndex = getBitIndex(n); 30 | 31 | uint8_t mask = 1 << bitIndex; 32 | mask = ~mask; 33 | 34 | buckets[bucketIndex] &= mask; 35 | } 36 | 37 | bool StaticSet::contains(unsigned n) const 38 | { 39 | unsigned bucketIndex = getBucketIndex(n); 40 | unsigned bitIndex = getBitIndex(n); 41 | 42 | uint8_t mask = 1 << bitIndex; 43 | 44 | return (buckets[bucketIndex] & mask) != 0; 45 | } 46 | void StaticSet::print() const 47 | { 48 | std::cout << "{ "; 49 | for (unsigned i = 0; i <= MAX_NUM; i++) 50 | { 51 | if (contains(i)) 52 | std::cout << i << " "; 53 | } 54 | std::cout << "} " << std::endl; 55 | 56 | } 57 | 58 | StaticSet UnionOfSets(const StaticSet& lhs, const StaticSet& rhs) 59 | { 60 | StaticSet result; 61 | for (int i = 0; i < BUCKETS_COUNT; i++) 62 | result.buckets[i] = (lhs.buckets[i] | rhs.buckets[i]); 63 | return result; 64 | 65 | } 66 | StaticSet IntersectionOfSets(const StaticSet& lhs, const StaticSet& rhs) 67 | { 68 | StaticSet result; 69 | for (int i = 0; i < BUCKETS_COUNT; i++) 70 | result.buckets[i] = lhs.buckets[i] & rhs.buckets[i]; 71 | return result; 72 | } -------------------------------------------------------------------------------- /Week 06/Bitsets/StaticSet/StaticSet.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | constexpr unsigned MAX_NUM = 1023; 5 | constexpr unsigned NUMBERS_COUNT = MAX_NUM + 1; 6 | constexpr unsigned BUCKET_SIZE = sizeof(uint8_t) * 8; 7 | constexpr unsigned BUCKETS_COUNT = NUMBERS_COUNT / BUCKET_SIZE + 1; 8 | 9 | class StaticSet 10 | { 11 | uint8_t buckets[BUCKETS_COUNT] = { 0 }; 12 | unsigned getBucketIndex(unsigned n) const; 13 | unsigned getBitIndex(unsigned n) const; 14 | public: 15 | StaticSet() = default; 16 | 17 | void add(unsigned n); 18 | void remove(unsigned n); 19 | 20 | bool contains(unsigned n) const; 21 | void print() const; 22 | 23 | friend StaticSet UnionOfSets(const StaticSet& lhs, const StaticSet& rhs); 24 | friend StaticSet IntersectionOfSets(const StaticSet& lhs, const StaticSet& rhs); 25 | 26 | }; 27 | -------------------------------------------------------------------------------- /Week 06/Bitsets/StaticSet/main.cpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include "StaticSet.h" 4 | 5 | int main() 6 | { 7 | 8 | StaticSet s1; 9 | 10 | s1.add(1); 11 | s1.add(10); 12 | s1.add(5); 13 | s1.print(); 14 | 15 | StaticSet s2; 16 | 17 | s2.add(1); 18 | 19 | s2.add(17); 20 | s1.add(130); 21 | s1.print(); 22 | 23 | 24 | StaticSet intersect = UnionOfSets(s1, s2); 25 | StaticSet uni = IntersectionOfSets(s1, s2); 26 | 27 | intersect.print(); 28 | uni.print(); 29 | 30 | } -------------------------------------------------------------------------------- /Week 06/GraduatedStudent/GraduatedStudent.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | class GraduatedStudent 3 | { 4 | public: 5 | GraduatedStudent(const char* name, const int* grades, size_t gradesCount, const char* quote); 6 | GraduatedStudent(const GraduatedStudent& other); 7 | GraduatedStudent& operator=(const GraduatedStudent& other); 8 | ~GraduatedStudent(); 9 | 10 | void setName(const char* newName); 11 | void setGrades(const int* newGrades, size_t newGradesCount); 12 | void setQuote(const char* quote); 13 | 14 | const char* getName() const; 15 | const int* getGrades() const; 16 | unsigned getGradesCount() const; 17 | const char* getQuote() const; 18 | 19 | private: 20 | char* name = nullptr; 21 | int* grades = nullptr; 22 | size_t gradesCount = 0; 23 | char quote[31] = ""; 24 | void copyDynamic(const GraduatedStudent& other); 25 | void freeDynamic(); 26 | }; 27 | -------------------------------------------------------------------------------- /Week 06/GraduatedStudent/main.cpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include "GraduatedStudent.h" 4 | 5 | int main() 6 | { 7 | int grades[] = { 3,3,4,4,5,5 }; 8 | GraduatedStudent gr("Test Student", grades, sizeof(grades) / sizeof(int), "Winning!"); 9 | 10 | std::cout << gr.getName(); 11 | } -------------------------------------------------------------------------------- /Week 06/Quiz (not finished)/Question.cpp: -------------------------------------------------------------------------------- 1 | #include "Question.h" 2 | 3 | Question::Question(const char* task, 4 | const char* a1, 5 | const char* a2, 6 | const char* a3, 7 | const char* a4, 8 | int correct) : answers(a1, a2, a3, a4), correctAnswer(correctAnswer) 9 | { 10 | this->task = new char[strlen(task) + 1]; 11 | strcpy(this->task, task); 12 | } 13 | 14 | void Question::freeDynamic() { 15 | delete[] task; 16 | } 17 | void Question::copyDynamic(const Question& other) { 18 | this->task = new char[strlen(other.task) + 1]; 19 | strcpy(this->task, other.task); 20 | } 21 | 22 | 23 | Question::Question(const Question& other) : answers(other.answers), correctAnswer(correctAnswer) 24 | { 25 | copyDynamic(other); 26 | } 27 | 28 | 29 | Question& Question::operator=(const Question& other) { 30 | 31 | if (this != &other) { 32 | answers = other.answers; 33 | correctAnswer = other.correctAnswer; 34 | 35 | freeDynamic(); 36 | copyDynamic(other); 37 | } 38 | 39 | return *this; 40 | 41 | } 42 | Question::~Question() { 43 | freeDynamic(); 44 | } -------------------------------------------------------------------------------- /Week 06/Quiz (not finished)/Question.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #pragma warning (disable : 4996) 3 | #include 4 | 5 | class Question 6 | { 7 | public: 8 | 9 | struct Answer 10 | { 11 | Answer(const char* str) 12 | { 13 | if (!str || strlen(str) > 127) 14 | return; //error ! 15 | strcpy(text, str); 16 | } 17 | char text[127 + 1] = ""; 18 | }; 19 | struct Answers 20 | { 21 | Answer answers[4]; 22 | 23 | Answers(const char* a1 = nullptr, 24 | const char* a2 = nullptr, 25 | const char* a3 = nullptr, 26 | const char* a4 = nullptr) : answers{Answer(a1), 27 | Answer(a2), 28 | Answer(a3), 29 | Answer(a4)} {} 30 | }; 31 | 32 | Question() = default; 33 | Question(const char* task, 34 | const char* a1, 35 | const char* a2, 36 | const char* a3, 37 | const char* a4, 38 | int correct); 39 | 40 | Question(const Question& other); 41 | Question& operator=(const Question& other); 42 | ~Question(); 43 | 44 | 45 | private: 46 | 47 | void freeDynamic(); 48 | void copyDynamic(const Question& other); 49 | 50 | 51 | char* task; // no limit for the length 52 | Answers answers; //no def constr!!! 53 | int correctAnswer; //[1...4] 54 | }; 55 | 56 | -------------------------------------------------------------------------------- /Week 06/Quiz (not finished)/Quiz.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Angeld55/Object-oriented_programming_FMI/56245c795618b1b575e2c63963773ae0d4f66ace/Week 06/Quiz (not finished)/Quiz.cpp -------------------------------------------------------------------------------- /Week 06/Quiz (not finished)/Quiz.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "Question.h" 3 | class Quiz 4 | { 5 | public: 6 | Quiz(size_t maxQuestions); 7 | Quiz(const Quiz& other); 8 | Quiz& operator=(const Quiz& other); 9 | ~Quiz(); 10 | void addQuestion(const Question& q); 11 | 12 | size_t getSize() const; 13 | size_t isFull() const; 14 | private: 15 | 16 | void copyDynamic(const Quiz& other); 17 | void freeDynamic(); 18 | 19 | Question* questions; 20 | size_t size; 21 | size_t capacity; 22 | }; 23 | 24 | -------------------------------------------------------------------------------- /Week 06/Quiz (not finished)/Source.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "Quiz.h" 3 | int main() 4 | { 5 | Quiz q(5); 6 | 7 | Question question("Capital of germany? ", "Berlin", "London", "New York", "Hamburg", 1); 8 | 9 | q.addQuestion(question); 10 | } 11 | -------------------------------------------------------------------------------- /Week 07/Complex/Complex.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | class Complex 4 | { 5 | public: 6 | Complex(); 7 | Complex(double real, double im); 8 | 9 | double getReal() const; 10 | double getIm() const; 11 | 12 | void setReal(double real); 13 | void setIm(double im); 14 | 15 | Complex getConjugated() const; //връща комплексно спрегнатото число на текущия обект. 16 | 17 | //assignment operators 18 | // a+=b Към а се добавя стойността на b. а се променя , b не се. Операцията ще върне a за да може да се правят верижни изрази (a+=b+=c) 19 | Complex& operator+=(const Complex&); 20 | Complex& operator-=(const Complex&); 21 | Complex& operator*=(const Complex&); 22 | Complex& operator/=(const Complex&); 23 | 24 | 25 | 26 | //stream opeartors ( std::cout << c1) (std::cin >> c1 ) 27 | friend std::ostream& operator<<(std::ostream&, const Complex&); 28 | friend std::istream& operator>>(std::istream&, Complex&); 29 | 30 | private: 31 | double real; 32 | double im; 33 | 34 | }; 35 | // a+b. Операторът връща НОВА променлива(Complex), която е резултатът от операцията. 36 | Complex operator+(const Complex&, const Complex&); 37 | Complex operator-(const Complex&, const Complex&); 38 | Complex operator*(const Complex&, const Complex&); 39 | Complex operator/(const Complex&, const Complex&); 40 | 41 | bool operator==(const Complex& lhs, const Complex& rhs); 42 | bool operator!=(const Complex& lhs, const Complex& rhs); 43 | -------------------------------------------------------------------------------- /Week 07/Complex/main.cpp: -------------------------------------------------------------------------------- 1 | #include "Complex.h" 2 | 3 | int main() 4 | { 5 | Complex c(3, 4); 6 | Complex c2(3, 4); 7 | 8 | std::cout << c * c2; 9 | } 10 | -------------------------------------------------------------------------------- /Week 07/MyString/MyString.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | class MyString 5 | { 6 | public: 7 | MyString(); 8 | MyString(const char* data); 9 | 10 | MyString(const MyString& other); 11 | MyString& operator=(const MyString& other); 12 | ~MyString(); 13 | 14 | size_t getCapacity() const; 15 | size_t getSize() const; 16 | 17 | const char* c_str() const; 18 | 19 | MyString& operator+=(const MyString& other); 20 | 21 | char& operator[](size_t index); 22 | const char& operator[](size_t index) const; 23 | 24 | friend std::ostream& operator<<(std::ostream& os, const MyString& obj); 25 | friend std::istream& operator>>(std::istream& is, MyString& ref); 26 | friend MyString operator+(const MyString& lhs, const MyString& rhs); 27 | private: 28 | explicit MyString(size_t stringLength); 29 | void resize(unsigned newAllocatedDataSize); 30 | 31 | void free(); 32 | void copyFrom(const MyString& other); 33 | 34 | char* _data; 35 | size_t _size; 36 | size_t _allocatedDataSize; 37 | }; 38 | 39 | 40 | 41 | bool operator==(const MyString& lhs, const MyString& rhs); 42 | bool operator!=(const MyString& lhs, const MyString& rhs); 43 | bool operator<(const MyString& lhs, const MyString& rhs); 44 | bool operator<=(const MyString& lhs, const MyString& rhs); 45 | bool operator>(const MyString& lhs, const MyString& rhs); 46 | bool operator>=(const MyString& lhs, const MyString& rhs); 47 | -------------------------------------------------------------------------------- /Week 07/MyString/main.cpp: -------------------------------------------------------------------------------- 1 | #include "MyString.h" 2 | 3 | int main() 4 | { 5 | MyString test = "test str"; 6 | 7 | std::cout << test << " "; 8 | std::cout << test.getSize() << " " << test.getCapacity() << std::endl; 9 | 10 | MyString test2; 11 | std::cin >> test2; 12 | 13 | MyString test3 = test + test2; 14 | std::cout << test << std::endl; 15 | std::cout << test2 << std::endl; 16 | std::cout << test3 << std::endl; 17 | 18 | test3 += test3; 19 | std::cout << test3; 20 | 21 | } 22 | -------------------------------------------------------------------------------- /Week 07/NVector/NVector.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | class NVector 5 | { 6 | private: 7 | int* data; 8 | size_t size; 9 | 10 | void copyFrom(const NVector& other); 11 | void free(); 12 | 13 | public: 14 | NVector(size_t size); 15 | 16 | NVector(const NVector& other); 17 | NVector& operator=(const NVector& other); 18 | ~NVector(); 19 | 20 | 21 | NVector& operator+=(const NVector& other); 22 | NVector& operator-=(const NVector& other); 23 | 24 | 25 | NVector& operator*=(size_t scalar); 26 | 27 | int& operator[](size_t); //get set 28 | int operator[](size_t) const; // get 29 | 30 | 31 | size_t operator~() const;// size; 32 | 33 | friend std::ostream& operator<<(std::ostream& os, const NVector& v); 34 | friend std::istream& operator>>(std::istream&, NVector& v); 35 | }; 36 | 37 | NVector operator+(const NVector& lhs, const NVector& rhs); 38 | NVector operator-(const NVector& lhs, const NVector& rhs); 39 | 40 | 41 | //So it could be commutative: 42 | NVector operator*(const NVector& lhs, size_t scalar); 43 | NVector operator*(size_t scalar, const NVector& rhs); 44 | 45 | 46 | //are parallel 47 | bool operator||(const NVector& lhs, const NVector& rhs); 48 | 49 | 50 | //scalar product 51 | size_t operator%(const NVector& lhs, const NVector& rhs); 52 | 53 | 54 | //are perpendicular 55 | bool operator|=(const NVector& lhs, const NVector& rhs); 56 | -------------------------------------------------------------------------------- /Week 07/NVector/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "NVector.h" 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | NVector v(3); 9 | v[2] = 10; 10 | NVector v2 = 3 * v; 11 | cout << v2; 12 | 13 | } 14 | -------------------------------------------------------------------------------- /Week 08/Fibb_static_cache/MapKeys0toN.cpp: -------------------------------------------------------------------------------- 1 | #include "MapKeys0toN.h" 2 | 3 | MapKeys0toN::MapKeys0toN(unsigned nullValue) 4 | { 5 | for (int i = 0; i < N; i++) 6 | _values[i] = nullValue; 7 | _nullValue = nullValue; 8 | } 9 | 10 | void MapKeys0toN::add(unsigned key, unsigned value) 11 | { 12 | if (value == _nullValue || key >= N) 13 | return; 14 | 15 | _values[key] = value; 16 | } 17 | 18 | bool MapKeys0toN::contains(unsigned key) const 19 | { 20 | return _values[key] != _nullValue; 21 | } 22 | 23 | unsigned MapKeys0toN::getValue(unsigned key) const 24 | { 25 | if (!contains(key)) 26 | throw "Error"; 27 | return _values[key]; 28 | } 29 | -------------------------------------------------------------------------------- /Week 08/Fibb_static_cache/MapKeys0toN.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | constexpr unsigned N = 100; 4 | 5 | class MapKeys0toN 6 | { 7 | public: 8 | MapKeys0toN(unsigned nullValue); 9 | void add(unsigned key, unsigned value); 10 | bool contains(unsigned key) const; 11 | unsigned getValue(unsigned key) const; 12 | 13 | private: 14 | unsigned _values[N]; 15 | unsigned _nullValue; 16 | }; 17 | 18 | -------------------------------------------------------------------------------- /Week 08/Fibb_static_cache/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "MapKeys0toN.h" 3 | 4 | unsigned fibb(unsigned n) 5 | { 6 | if (n == 0 || n == 1) 7 | return 1; 8 | static MapKeys0toN cache(0); 9 | 10 | if (cache.contains(n)) 11 | { 12 | return cache.getValue(n); 13 | } 14 | else 15 | { 16 | unsigned result = fibb(n - 1) + fibb(n - 2); 17 | cache.add(n, result); 18 | return result; 19 | } 20 | } 21 | int main() 22 | { 23 | std::cout << fibb(30) << std::endl; 24 | std::cout << fibb(30); 25 | 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /Week 08/FlightsScanner - Exception handling task/FlightsScanner.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | class FlightsScanner 5 | { 6 | char inputFileName[1024] = ""; 7 | char outputFileName[1024] = ""; 8 | int sec = -1; 9 | unsigned lineIndex = 0; 10 | 11 | 12 | struct FlightRecord 13 | { 14 | char origin[64]; 15 | char dest[64]; 16 | unsigned amount; 17 | }; 18 | 19 | void handleAirport(char* airport) const; 20 | void parseLine(const char* line, FlightRecord& record) const; 21 | bool readAndExportData(std::ifstream& input); 22 | void saveRecord(std::ofstream& ofs, const FlightRecord& record) const; 23 | 24 | public: 25 | FlightsScanner(const char* input, const char* output, int scanInterval); 26 | void run(); 27 | }; 28 | -------------------------------------------------------------------------------- /Week 08/FlightsScanner - Exception handling task/Utills.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | //we don't make them static, because we want to use the in other cpp files. 4 | 5 | bool isLower(char ch) { return ch >= 'a' && ch <= 'z'; } 6 | 7 | bool isSymbol(char ch) 8 | { 9 | return ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z'; 10 | } 11 | 12 | void toUpper(char* str) 13 | { 14 | if (str == nullptr) 15 | throw std::invalid_argument("The given string does not exist"); 16 | 17 | static int diff = 'a' - 'A'; 18 | while (*str) 19 | { 20 | if (!isSymbol(*str)) 21 | throw std::bad_cast(); 22 | if (isLower(*str)) 23 | *str = *str - diff; 24 | str++; 25 | } 26 | } 27 | 28 | unsigned charToDigit(char ch) 29 | { 30 | if (ch < '0' || ch > '9') 31 | throw std::bad_cast(); 32 | 33 | return ch - '0'; 34 | } 35 | 36 | unsigned convertToNumber(const char* str) 37 | { 38 | if (!str) 39 | throw std::invalid_argument("The given string does not exist"); 40 | 41 | unsigned result = 0; 42 | while (*str) 43 | { 44 | result *= 10; 45 | result += charToDigit(*str); 46 | str++; 47 | } 48 | return result; 49 | } -------------------------------------------------------------------------------- /Week 08/FlightsScanner - Exception handling task/Utills.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | bool isLower(char ch); 4 | bool isSymbol(char ch); 5 | void toUpper(char* str); 6 | unsigned charToDigit(char ch); 7 | unsigned convertToNumber(const char* str); -------------------------------------------------------------------------------- /Week 08/FlightsScanner - Exception handling task/inputFlights.txt: -------------------------------------------------------------------------------- 1 | soF muN 32 2 | Ber LoN 434 3 | Rom Prs t5t 4 | Rome PlD 23 5 | Mad Mscs 444 6 | dsfs -------------------------------------------------------------------------------- /Week 08/FlightsScanner - Exception handling task/source.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "FlightsScanner.h" 3 | 4 | int main() 5 | { 6 | FlightsScanner scanner("inputFlights.txt", "outputFlights.txt", 10); 7 | scanner.run(); 8 | } -------------------------------------------------------------------------------- /Week 08/ImmutableString/ImmutableString.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include "StringPool.h" 4 | 5 | class ImmutableString 6 | { 7 | 8 | public: 9 | 10 | ImmutableString(const char* data); 11 | ImmutableString(const ImmutableString& other); 12 | ImmutableString& operator=(const ImmutableString& other) = delete; //this could be implemented in some cases 13 | ~ImmutableString(); 14 | 15 | size_t length() const; 16 | char operator[](size_t index) const; 17 | const char* c_str() const; 18 | 19 | private: 20 | 21 | const char* _data; 22 | size_t _length; 23 | 24 | void copyFrom(const ImmutableString& data); 25 | void free(); 26 | 27 | static StringPool _pool; 28 | }; 29 | 30 | std::ostream& operator<<(std::ostream& os, const ImmutableString& str); 31 | 32 | bool operator<(const ImmutableString& lhs, const ImmutableString& rhs); 33 | bool operator<=(const ImmutableString& lhs, const ImmutableString& rhs); 34 | bool operator>=(const ImmutableString& lhs, const ImmutableString& rhs); 35 | bool operator>(const ImmutableString& lhs, const ImmutableString& rhs); 36 | bool operator==(const ImmutableString& lhs, const ImmutableString& rhs); 37 | bool operator!=(const ImmutableString& lhs, const ImmutableString& rhs); 38 | -------------------------------------------------------------------------------- /Week 08/ImmutableString/StringPool.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | class StringPool 4 | { 5 | public: 6 | StringPool(); 7 | const char* getAllocatedString(const char* str); 8 | void releaseString(const char* str); 9 | StringPool(const StringPool&) = delete; 10 | StringPool& operator=(const StringPool&) = delete; 11 | ~StringPool(); 12 | private: 13 | 14 | unsigned allocatedNewString(const char* str); 15 | void resize(unsigned newCap); 16 | int findAllocatedString(const char* str) const; 17 | 18 | void removeRecord(unsigned index); 19 | 20 | struct StringRecord 21 | { 22 | char* str = nullptr; 23 | unsigned refCount = 0; 24 | }; 25 | 26 | StringRecord* stringRecords; 27 | size_t stringCount = 0; 28 | size_t stringCapacity = 0; 29 | }; 30 | -------------------------------------------------------------------------------- /Week 08/ImmutableString/test2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "ImmutableString.h" 3 | 4 | int main() 5 | { 6 | ImmutableString str = "abv"; 7 | ImmutableString str2 = "abv"; 8 | ImmutableString str3 = "abq"; 9 | 10 | } -------------------------------------------------------------------------------- /Week 08/SelfCounting/SelfCounting.cpp: -------------------------------------------------------------------------------- 1 | #include "SelfCounting.h" 2 | 3 | //static class member's should be 4 | //initialized here ( "only in one .cpp" ) 5 | unsigned SelfCounting::liveObjectsCount = 0; 6 | unsigned SelfCounting::createdCount = 0; 7 | 8 | SelfCounting::SelfCounting() : SelfCounting(42) //initialization of constants 9 | //can only be done while creating them 10 | //so the only possible way is in 11 | //the initialization list 12 | { 13 | } 14 | 15 | SelfCounting::SelfCounting(int val) : const_val(val) 16 | { 17 | liveObjectsCount++; 18 | createdCount++; 19 | } 20 | SelfCounting::SelfCounting(const SelfCounting& other) : const_val(other.const_val) 21 | { 22 | liveObjectsCount++; 23 | createdCount++; 24 | } 25 | 26 | SelfCounting::~SelfCounting() 27 | { 28 | liveObjectsCount--; 29 | } 30 | 31 | unsigned SelfCounting::getLiveObjectsCount() 32 | { 33 | return liveObjectsCount; 34 | } 35 | 36 | unsigned SelfCounting::getCreatedCount() 37 | { 38 | return createdCount; 39 | } 40 | -------------------------------------------------------------------------------- /Week 08/SelfCounting/SelfCounting.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | 4 | class SelfCounting 5 | { 6 | 7 | //a constant, which may be different 8 | //for different objects 9 | //so it is "per object" 10 | const int const_val; 11 | 12 | static unsigned liveObjectsCount; 13 | static unsigned createdCount; 14 | 15 | public: 16 | SelfCounting(); 17 | SelfCounting(int val); 18 | SelfCounting(const SelfCounting& other); 19 | ~SelfCounting(); 20 | 21 | //methods which aren't 22 | //related with particular 23 | //instance 24 | static unsigned getLiveObjectsCount(); 25 | static unsigned getCreatedCount(); 26 | 27 | }; 28 | -------------------------------------------------------------------------------- /Week 08/SelfCounting/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "SelfCounting.h" 5 | 6 | int main() 7 | { 8 | SelfCounting s(4); 9 | SelfCounting s2(30); 10 | 11 | { 12 | SelfCounting s3(232); 13 | 14 | std::cout << SelfCounting::getCreatedCount() << " " << SelfCounting::getLiveObjectsCount() << std::endl; 15 | } 16 | std::cout << SelfCounting::getCreatedCount() << " " << SelfCounting::getLiveObjectsCount() << std::endl; 17 | 18 | } 19 | -------------------------------------------------------------------------------- /Week 08/SwapsCounter/swapsCounter.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct SwapCounter 4 | { 5 | private: 6 | static int count; 7 | public: 8 | static void swap(int& a, int& b) 9 | { 10 | int temp = a; 11 | a = b; 12 | b = temp; 13 | count++; 14 | } 15 | static int getCount() 16 | { 17 | return count; 18 | } 19 | static void resetCount() 20 | { 21 | count = 0; 22 | } 23 | 24 | }; 25 | int SwapCounter::count = 0; 26 | 27 | void print(const int* arr, size_t size) 28 | { 29 | for (int i = 0; i < size; i++) 30 | std::cout << arr[i] << " "; 31 | std::cout << std::endl; 32 | } 33 | 34 | void bubbleSort(int* arr, size_t size) 35 | { 36 | for (int i = 0; i < size - 1; i++) 37 | { 38 | bool isSwapped = false; 39 | for (int j = 0; j < size - 1 - i; j++) 40 | { 41 | if (arr[j + 1] < arr[j]) 42 | { 43 | SwapCounter::swap(arr[j], arr[j + 1]); 44 | isSwapped = true; 45 | } 46 | } 47 | if (!isSwapped) 48 | return; 49 | } 50 | } 51 | 52 | void selectionSort(int* arr, size_t size) 53 | { 54 | for (int i = 0; i < size - 1; i++) 55 | { 56 | int minElIndex = i; 57 | for (int j = i + 1; j < size; j++) 58 | { 59 | if (arr[j] < arr[minElIndex]) 60 | minElIndex = j; 61 | } 62 | 63 | if (minElIndex != i) 64 | SwapCounter::swap(arr[minElIndex], arr[i]); 65 | } 66 | } 67 | 68 | 69 | 70 | int main() 71 | { 72 | { 73 | int arr[10] = { 10,9,8,7,6,5,4,3,2,1 }; 74 | bubbleSort(arr, 10); 75 | std::cout << "Bubble sort swaps: " << SwapCounter::getCount() << std::endl; 76 | } 77 | { 78 | SwapCounter::resetCount(); 79 | int arr[10] = { 10,9,8,7,6,5,4,3,2,1 }; 80 | selectionSort(arr, 10); 81 | std::cout << "Selection sort swaps: " << SwapCounter::getCount() << std::endl; 82 | 83 | } 84 | } -------------------------------------------------------------------------------- /Week 09/DynamicArrayOfA (with move)/DynamicArrayOfA.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | struct A 5 | { 6 | int a = 4; 7 | int b = 3; 8 | }; 9 | class DynamicArray 10 | { 11 | 12 | private: 13 | A* arr = nullptr; 14 | size_t size = 0; 15 | size_t capacity = 0; 16 | void moveFrom(DynamicArray&& other); 17 | public: 18 | DynamicArray(); 19 | DynamicArray(size_t capacity); 20 | DynamicArray(const DynamicArray& other); 21 | DynamicArray& operator=(const DynamicArray& other); 22 | ~DynamicArray(); 23 | 24 | DynamicArray(DynamicArray&& other) noexcept; 25 | DynamicArray& operator=(DynamicArray&& other) noexcept; 26 | 27 | private: 28 | void copyFrom(const DynamicArray& other); 29 | void free(); 30 | void resize(size_t newCap); 31 | 32 | public: 33 | void pushBack(const A& newElem); //add a new element in the end 34 | void pushBack(A&& newElem); //add a new element in the end 35 | 36 | void popBack(); //removes the last element 37 | 38 | void setAtIndex(const A& element, size_t index); 39 | void setAtIndex(A&& element, size_t index); 40 | 41 | size_t getSize() const; 42 | bool isEmpty() const; 43 | 44 | const A& operator[](size_t index) const; 45 | A& operator[](size_t index); 46 | }; 47 | -------------------------------------------------------------------------------- /Week 09/DynamicArrayOfA (with move)/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "DynamicArrayOfA.h" 3 | 4 | int main() 5 | { 6 | DynamicArray arraysOfA; 7 | 8 | arraysOfA.pushBack({ 3,4 }); 9 | 10 | A obj{ 4,3 }; 11 | 12 | arraysOfA.pushBack(obj); 13 | } -------------------------------------------------------------------------------- /Week 09/DynamicArrayOfPointers (with move)/DynamicArrayOfPointers.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct A 4 | { 5 | int x = 3; 6 | int y = 2; 7 | }; 8 | 9 | class DynamicArrayOfPointers 10 | { 11 | A** _data = nullptr; 12 | size_t _capacity = 0; 13 | size_t _count = 0; 14 | 15 | void free(); 16 | void copyFrom(const DynamicArrayOfPointers& other); 17 | void resize(size_t newCap); 18 | 19 | void moveFrom(DynamicArrayOfPointers&& other); 20 | 21 | int getFirstFreeIndex() const; //Better solution will be to store a variable with the first free index 22 | public: 23 | DynamicArrayOfPointers(); 24 | DynamicArrayOfPointers(const DynamicArrayOfPointers& other); 25 | DynamicArrayOfPointers& operator=(const DynamicArrayOfPointers& other); 26 | ~DynamicArrayOfPointers(); 27 | 28 | DynamicArrayOfPointers(DynamicArrayOfPointers&& other) noexcept; 29 | DynamicArrayOfPointers& operator=(DynamicArrayOfPointers&& other) noexcept; 30 | 31 | void addAtFirstFreeIndex(const A& current); 32 | void addAtFirstFreeIndex(A&& obj); 33 | 34 | bool containsAt(unsigned ind) const; 35 | void popBack(); 36 | void removeAt(size_t index); 37 | 38 | void setAtIndex(const A& obj, size_t index); 39 | void setAtIndex(A&& obj, size_t index); 40 | 41 | 42 | size_t size() const; 43 | const A& operator[](size_t index) const; 44 | A& operator[](size_t index); 45 | }; 46 | -------------------------------------------------------------------------------- /Week 09/DynamicArrayOfPointers (with move)/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "DynamicArrayOfPointers.h" 3 | 4 | int main() 5 | { 6 | DynamicArrayOfPointers test; 7 | 8 | A obj1{ 3,1 }; 9 | A obj2{ 0,0 }; 10 | 11 | test.addAtFirstFreeIndex(obj1); 12 | 13 | test.addAtFirstFreeIndex(obj2); 14 | 15 | std::cout << test[0].x; 16 | } -------------------------------------------------------------------------------- /Week 09/GraduatedStudent (with move)/GraduatedStudent.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | class GraduatedStudent 3 | { 4 | char* name = nullptr; 5 | int* grades = nullptr; 6 | size_t gradesCount = 0; 7 | char quote[30 + 1] = ""; 8 | 9 | void copyFrom(const GraduatedStudent& other); 10 | void moveFrom(GraduatedStudent&& other); 11 | void free(); 12 | 13 | public: 14 | GraduatedStudent(const char* name, 15 | const int* grades, 16 | size_t gradesCount, 17 | const char* quote); 18 | 19 | GraduatedStudent(const GraduatedStudent& other); 20 | GraduatedStudent& operator=(const GraduatedStudent& other); 21 | ~GraduatedStudent(); 22 | 23 | GraduatedStudent(GraduatedStudent&& other); 24 | GraduatedStudent& operator=(GraduatedStudent&& other); 25 | 26 | 27 | void setName(const char* newName); 28 | void setGrades(const int* newGrades, size_t newGradesCount); 29 | void setQuote(const char* quote); 30 | 31 | const char* getName() const; 32 | const int* getGrades() const; 33 | unsigned getGradesCount() const; 34 | const char* getQuote() const; 35 | }; -------------------------------------------------------------------------------- /Week 09/GraduatedStudent (with move)/main.cpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include "GraduatedStudent.h" 4 | 5 | int main() 6 | { 7 | int grades[] = { 3,3,4,4,5,5 }; 8 | GraduatedStudent gr("Test Student", grades, sizeof(grades) / sizeof(int), "Winning!"); 9 | 10 | std::cout << gr.getName(); 11 | } -------------------------------------------------------------------------------- /Week 09/MyString (with move)/MyString.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | class MyString 5 | { 6 | public: 7 | MyString(); 8 | MyString(const char* data); 9 | 10 | MyString(const MyString& other); 11 | MyString(MyString&& other) noexcept; 12 | 13 | MyString& operator=(const MyString& other); 14 | 15 | MyString& operator=(MyString&& other) noexcept; 16 | ~MyString(); 17 | 18 | size_t getCapacity() const; 19 | size_t getSize() const; 20 | 21 | const char* c_str() const; 22 | 23 | MyString& operator+=(const MyString& other); 24 | 25 | char& operator[](size_t index); 26 | const char& operator[](size_t index) const; 27 | 28 | friend std::ostream& operator<<(std::ostream& os, const MyString& obj); 29 | friend std::istream& operator>>(std::istream& is, MyString& ref); 30 | friend MyString operator+(const MyString& lhs, const MyString& rhs); 31 | private: 32 | explicit MyString(size_t stringLength); 33 | void resize(unsigned newAllocatedDataSize); 34 | 35 | void free(); 36 | void copyFrom(const MyString& other); 37 | 38 | void moveFrom(MyString&& other); 39 | 40 | char* _data; 41 | size_t _size; 42 | size_t _allocatedDataSize; 43 | }; 44 | 45 | 46 | 47 | bool operator==(const MyString& lhs, const MyString& rhs); 48 | bool operator!=(const MyString& lhs, const MyString& rhs); 49 | bool operator<(const MyString& lhs, const MyString& rhs); 50 | bool operator<=(const MyString& lhs, const MyString& rhs); 51 | bool operator>(const MyString& lhs, const MyString& rhs); 52 | bool operator>=(const MyString& lhs, const MyString& rhs); 53 | -------------------------------------------------------------------------------- /Week 09/MyString (with move)/main.cpp: -------------------------------------------------------------------------------- 1 | #include "MyString.h" 2 | 3 | int main() 4 | { 5 | MyString test = "test str"; 6 | 7 | std::cout << test << " "; 8 | std::cout << test.getSize() << " " << test.getCapacity() << std::endl; 9 | 10 | MyString test2; 11 | std::cin >> test2; 12 | 13 | MyString test3 = test + test2; 14 | std::cout << test << std::endl; 15 | std::cout << test2 << std::endl; 16 | std::cout << test3 << std::endl; 17 | 18 | test3 += test3; 19 | std::cout << test3; 20 | 21 | } 22 | -------------------------------------------------------------------------------- /Week 10/Person, Student, Teacher/Person/Person.cpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "Person.h" 3 | #include 4 | #pragma warning (disable:4996) 5 | 6 | void Person::copyFrom(const Person& other) 7 | { 8 | name = new char[strlen(other.name) + 1]; 9 | strcpy(name, other.name); 10 | age = other.age; 11 | } 12 | 13 | void Person::free() 14 | { 15 | delete[] name; 16 | } 17 | 18 | Person::Person(const char* name, int age) 19 | { 20 | setName(name); 21 | setAge(age); 22 | } 23 | 24 | Person::Person(const Person& other) 25 | { 26 | copyFrom(other); 27 | } 28 | 29 | Person& Person::operator=(const Person& other) 30 | { 31 | if (this != &other) 32 | { 33 | free(); 34 | copyFrom(other); 35 | } 36 | return *this; 37 | } 38 | 39 | void Person::moveFrom(Person&& other) 40 | { 41 | name = other.name; 42 | other.name = nullptr; 43 | age = other.age; 44 | } 45 | 46 | 47 | Person::Person(Person&& other) noexcept 48 | { 49 | moveFrom(std::move(other)); 50 | } 51 | 52 | Person& Person::operator=(Person&& other) noexcept 53 | { 54 | if (this != &other) 55 | { 56 | free(); 57 | moveFrom(std::move(other)); 58 | } 59 | return *this; 60 | } 61 | const char* Person::getName() const 62 | { 63 | return name; 64 | } 65 | 66 | int Person::getAge() const 67 | { 68 | return age; 69 | } 70 | 71 | void Person::setName(const char* name) 72 | { 73 | if (name == nullptr || this->name == name) 74 | return; 75 | 76 | delete[] this->name; 77 | size_t nameLen = strlen(name); 78 | this->name = new char[nameLen + 1]; 79 | strcpy(this->name, name); 80 | } 81 | 82 | void Person::setAge(int age) 83 | { 84 | this->age = age; 85 | } 86 | 87 | 88 | Person::~Person() 89 | { 90 | free(); 91 | } 92 | 93 | void Person::print() const 94 | { 95 | std::cout << name << " " << age << std::endl; 96 | } 97 | -------------------------------------------------------------------------------- /Week 10/Person, Student, Teacher/Person/Person.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | class Person 4 | { 5 | char* name = nullptr; 6 | int age = 0; 7 | 8 | void copyFrom(const Person& other); 9 | void free(); 10 | void moveFrom(Person&& other); 11 | 12 | public: 13 | Person() = default; 14 | Person(const char* name, int age); 15 | 16 | Person(const Person& other); 17 | Person& operator=(const Person& other); 18 | 19 | Person(Person&& other) noexcept; 20 | Person& operator=(Person&& other) noexcept; 21 | 22 | const char* getName() const; 23 | int getAge() const; 24 | 25 | ~Person(); 26 | void print() const; 27 | 28 | protected: 29 | void setName(const char* name); 30 | void setAge(int age); 31 | }; 32 | -------------------------------------------------------------------------------- /Week 10/Person, Student, Teacher/Source.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "Person/Person.h" 3 | #include "Student/Student.h" 4 | #include "Teacher/Teacher.h" 5 | 6 | int main() 7 | { 8 | 9 | char subjects[3][20] = { "English", "Mathematics", "Physics" }; 10 | 11 | char** subjectsPointers = new char* [3]; 12 | subjectsPointers[0] = subjects[0]; 13 | subjectsPointers[1] = subjects[1]; 14 | subjectsPointers[2] = subjects[2]; 15 | 16 | Teacher t("Prof. Ivanov", 33, subjectsPointers, 3); 17 | 18 | std::cout << t.getName() << std::endl; 19 | 20 | delete[] subjectsPointers; //only the pointers - not the data! 21 | 22 | } 23 | -------------------------------------------------------------------------------- /Week 10/Person, Student, Teacher/Student/Student.cpp: -------------------------------------------------------------------------------- 1 | #include "Student.h" 2 | 3 | Student::Student(const char* name, int age, size_t fn) : Person(name, age) 4 | { 5 | setFn(fn); 6 | } 7 | 8 | size_t Student::getFn() const 9 | { 10 | return fn; 11 | } 12 | 13 | void Student::setFn(size_t fn) 14 | { 15 | 16 | if (fn < 100) 17 | fn = 100; 18 | this->fn = fn; 19 | } 20 | 21 | // The compiler will make: 22 | 23 | //Student(const Student& other) : Person(other), fn(other.fn), grade(other.grade) OK!!! 24 | //{} 25 | 26 | //Student& operator=(const Student& other) OK!!!! 27 | //{ 28 | // if (this != &other) 29 | // { 30 | // Person::operator=(other); //handles the deletion and copying of the base class 31 | // fn = other.fn; 32 | // } 33 | // return *this; 34 | //} -------------------------------------------------------------------------------- /Week 10/Person, Student, Teacher/Student/Student.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include "../Person/Person.h" 3 | 4 | class Student : public Person 5 | { 6 | size_t fn = 0; 7 | public: 8 | Student() = default; 9 | Student(const char* name, int age, size_t fn); 10 | 11 | size_t getFn() const; 12 | void setFn(size_t fn); 13 | 14 | 15 | // No need for big 4, since there is NO dyn. memory in Student 16 | // The compiler will generate valid: 17 | 18 | //Student(const Student& other); 19 | //Student& operator=(const Student& other); //no need 20 | // ~Student() 21 | 22 | //See on the .cpp file how the compiler creates them 23 | 24 | }; 25 | -------------------------------------------------------------------------------- /Week 10/Person, Student, Teacher/Teacher/Teacher.h: -------------------------------------------------------------------------------- 1 | #include "../Person/Person.h" 2 | 3 | class Teacher : public Person 4 | { 5 | char** subjects; 6 | size_t subjectsCount; 7 | 8 | void free(); 9 | void copyFrom(const Teacher& other);// само нещата, които са от Teacher 10 | void moveFrom(Teacher&& other); 11 | 12 | public: 13 | Teacher(const char* name, int age, const char* const * subjects, size_t subjectsCount); 14 | 15 | Teacher(const Teacher& other); 16 | Teacher& operator=(const Teacher& other); 17 | 18 | Teacher(Teacher&& other) noexcept; 19 | Teacher& operator=(Teacher&& other) noexcept; 20 | ~Teacher(); 21 | }; 22 | -------------------------------------------------------------------------------- /Week 10/Sets/DynamicSet/DynamicSet.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | class DynamicSet 5 | { 6 | uint8_t* buckets = nullptr; 7 | unsigned bucketsCount = 0; 8 | unsigned N = 0; 9 | const unsigned elementsInBucket = sizeof(uint8_t) * 8; 10 | 11 | void free(); 12 | void copyFrom(const DynamicSet& other); 13 | 14 | unsigned getBucketIndex(unsigned num) const; 15 | public: 16 | DynamicSet(unsigned n); // [0....n] (n + 1 ÷èñëà) 17 | 18 | DynamicSet(const DynamicSet& other); 19 | DynamicSet& operator=(const DynamicSet& other); 20 | ~DynamicSet(); 21 | 22 | void add(unsigned num); 23 | void remove(unsigned num); 24 | bool contains(unsigned num) const; 25 | unsigned getN() const; 26 | void print() const; 27 | void removeAll(); 28 | friend DynamicSet UnionOfSets(const DynamicSet& lhs, const DynamicSet& rhs); 29 | friend DynamicSet IntersectionOfSets(const DynamicSet& lhs, const DynamicSet& rhs); 30 | 31 | }; 32 | -------------------------------------------------------------------------------- /Week 10/Sets/SetByCriteria/SetByCriteria.cpp: -------------------------------------------------------------------------------- 1 | #include "SetByCriteria.h" 2 | 3 | SetByCriteria::SetByCriteria(unsigned n, bool (*incl)(unsigned n)) : DynamicSet(n) 4 | { 5 | fillSet(incl); 6 | } 7 | 8 | void SetByCriteria::fillSet(bool (*criteria)(unsigned n)) 9 | { 10 | for (unsigned i = 0; i < getN(); i++) 11 | { 12 | if (criteria(i)) 13 | add(i); 14 | else 15 | remove(i); 16 | } 17 | } 18 | 19 | 20 | void SetByCriteria::setInclude(bool (*incl)(unsigned n)) 21 | { 22 | fillSet(incl); 23 | } 24 | -------------------------------------------------------------------------------- /Week 10/Sets/SetByCriteria/SetByCriteria.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "../DynamicSet/DynamicSet.h" 3 | 4 | class SetByCriteria : private DynamicSet 5 | { 6 | public: 7 | SetByCriteria(unsigned n, bool (*incl)(unsigned n)); 8 | void setInclude(bool (*incl)(unsigned n)); 9 | 10 | using DynamicSet::print; 11 | using DynamicSet::contains; 12 | 13 | private: 14 | void fillSet(bool (*criteria)(unsigned n)); 15 | }; 16 | -------------------------------------------------------------------------------- /Week 10/Sets/SetByString/SetByString.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "../DynamicSet/DynamicSet.h" 3 | #include 4 | 5 | class SetByString : private DynamicSet 6 | { 7 | char* str; 8 | 9 | void extractNumbersFromString(); 10 | void copyFrom(const SetByString& other); 11 | void free(); 12 | 13 | void moveFrom(SetByString&& other); 14 | 15 | public: 16 | SetByString(unsigned n, const char* data); 17 | SetByString(const SetByString& other); 18 | SetByString(SetByString&& other); 19 | SetByString& operator=(SetByString&& other); 20 | SetByString& operator=(const SetByString& other); 21 | ~SetByString(); 22 | 23 | bool contains(int i) const; 24 | void print() const; 25 | void setAt(unsigned ind, char ch); 26 | }; 27 | -------------------------------------------------------------------------------- /Week 10/Sets/source.cpp: -------------------------------------------------------------------------------- 1 | // ConsoleApplication4.cpp : This file contains the 'main' function. Program execution begins and ends there. 2 | // 3 | 4 | #include 5 | #include "SetByCriteria/SetByCriteria.h" 6 | #include "SetByString/SetByString.h" 7 | 8 | 9 | int main() 10 | { 11 | SetByString s(1000, "1 5 9"); 12 | s.print(); 13 | s.setAt(1, '0'); 14 | s.print(); 15 | 16 | 17 | SetByCriteria s2(11, [](unsigned i) {return i % 2 == 0; }); 18 | 19 | s2.print(); 20 | } 21 | -------------------------------------------------------------------------------- /Week 10/String and StringView/MyString.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | class MyString 5 | { 6 | public: 7 | MyString(); 8 | MyString(const char* data); 9 | 10 | MyString(const MyString& other); 11 | MyString(MyString&& other) noexcept; 12 | 13 | MyString& operator=(const MyString& other); 14 | 15 | MyString& operator=(MyString&& other) noexcept; 16 | ~MyString(); 17 | 18 | size_t getCapacity() const; 19 | size_t getSize() const; 20 | 21 | const char* c_str() const; 22 | 23 | MyString& operator+=(const MyString& other); 24 | 25 | char& operator[](size_t index); 26 | const char& operator[](size_t index) const; 27 | 28 | friend std::ostream& operator<<(std::ostream& os, const MyString& obj); 29 | friend std::istream& operator>>(std::istream& is, MyString& ref); 30 | friend MyString operator+(const MyString& lhs, const MyString& rhs); 31 | 32 | MyString substr(size_t begin, size_t howMany) const; 33 | 34 | private: 35 | explicit MyString(size_t stringLength); 36 | void resize(unsigned newAllocatedDataSize); 37 | 38 | void free(); 39 | void copyFrom(const MyString& other); 40 | 41 | void moveFrom(MyString&& other); 42 | 43 | char* _data; 44 | size_t _size; 45 | size_t _allocatedDataSize; 46 | }; 47 | 48 | 49 | 50 | bool operator==(const MyString& lhs, const MyString& rhs); 51 | bool operator!=(const MyString& lhs, const MyString& rhs); 52 | bool operator<(const MyString& lhs, const MyString& rhs); 53 | bool operator<=(const MyString& lhs, const MyString& rhs); 54 | bool operator>(const MyString& lhs, const MyString& rhs); 55 | bool operator>=(const MyString& lhs, const MyString& rhs); 56 | -------------------------------------------------------------------------------- /Week 10/String and StringView/StringView.cpp: -------------------------------------------------------------------------------- 1 | #include "StringView.h" 2 | 3 | StringView::StringView(const char* begin, const char* end): _begin(begin), _end(end) 4 | {} 5 | 6 | StringView::StringView(const char* str) : StringView(str, str + strlen(str)) {} 7 | 8 | StringView::StringView(const MyString& str) : StringView(str.c_str()) {} 9 | 10 | size_t StringView::length() const 11 | { 12 | return _end - _begin; 13 | } 14 | char StringView::operator[](size_t index) const 15 | { 16 | return _begin[index]; 17 | } 18 | 19 | StringView StringView::substr(size_t from, size_t length) const 20 | { 21 | if (_begin + from + length > _end) 22 | throw std::length_error("Error, Substr out of range"); 23 | 24 | return StringView(_begin + from, _begin + from + length); 25 | } 26 | 27 | std::ostream& operator<<(std::ostream& os, const StringView& strView) 28 | { 29 | const char* iter = strView._begin; 30 | 31 | while (iter != strView._end) 32 | { 33 | os << *iter; 34 | iter++; 35 | } 36 | return os; 37 | } 38 | -------------------------------------------------------------------------------- /Week 10/String and StringView/StringView.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include "MyString.h" 4 | class StringView 5 | { 6 | const char* _begin; 7 | const char* _end; //1 element after the final char; 8 | 9 | public: 10 | StringView(const char* begin, const char* end); 11 | StringView(const char* str); //terminatedString 12 | StringView(const MyString& string); 13 | 14 | size_t length() const; 15 | char operator[](size_t ind) const; 16 | 17 | StringView substr(size_t from, size_t length) const; 18 | friend std::ostream& operator<<(std::ostream&, const StringView& strView); 19 | 20 | }; 21 | 22 | //TODO: implement comparison operators -------------------------------------------------------------------------------- /Week 10/String and StringView/main.cpp: -------------------------------------------------------------------------------- 1 | #include "StringView.h" 2 | 3 | int main() 4 | { 5 | MyString test = "Hi, petur!"; 6 | StringView res(test); 7 | StringView res2 = res.substr(4, 5); 8 | std::cout << res2[0]; 9 | } 10 | -------------------------------------------------------------------------------- /Week 11/Collections/Collection.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | class Collection 3 | { 4 | public: 5 | virtual void add(int) = 0; 6 | virtual void remove(int) = 0; 7 | virtual unsigned count(int) const = 0; 8 | virtual bool contains(int) const = 0; 9 | 10 | virtual ~Collection() = default; 11 | }; -------------------------------------------------------------------------------- /Week 11/Collections/DynamicCollection.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include"Collection.h" 3 | 4 | class DynamicCollection : public Collection 5 | { 6 | protected: 7 | int* data = nullptr; 8 | size_t size = 0; 9 | size_t capacity = 0; 10 | 11 | void free(); 12 | void copyFrom(const DynamicCollection& other); 13 | void moveFrom(DynamicCollection&&); 14 | 15 | void resize(size_t); 16 | DynamicCollection(size_t cap); 17 | public: 18 | DynamicCollection(); 19 | 20 | DynamicCollection(const DynamicCollection& other); 21 | DynamicCollection(DynamicCollection&& other); 22 | 23 | DynamicCollection& operator=(const DynamicCollection& other); 24 | DynamicCollection& operator=(DynamicCollection&& other); 25 | 26 | ~DynamicCollection(); 27 | }; 28 | -------------------------------------------------------------------------------- /Week 11/Collections/IntervalCollection.cpp: -------------------------------------------------------------------------------- 1 | #include "IntervalCollection.h" 2 | #include 3 | 4 | IntervalCollection::IntervalCollection(int start, int end) 5 | { 6 | if (end < start) 7 | { 8 | std::swap(start, end); 9 | } 10 | 11 | this->start = start; 12 | this->end = end; 13 | int size = end - start; 14 | 15 | data = new int[size] {0}; 16 | } 17 | 18 | 19 | unsigned IntervalCollection::intervalLength() const 20 | { 21 | return end - start; 22 | } 23 | 24 | void IntervalCollection::add(int elem) 25 | { 26 | if (elem < start || elem > end) 27 | { 28 | return; 29 | } 30 | 31 | int index = elem - start; 32 | 33 | ++data[index]; 34 | } 35 | 36 | void IntervalCollection::remove(int elem) 37 | { 38 | if (elem < start || elem > end) 39 | { 40 | return; 41 | } 42 | 43 | int index = elem - start; 44 | 45 | if (data[index] == 0) 46 | { 47 | return; 48 | } 49 | 50 | --data[index]; 51 | } 52 | 53 | unsigned IntervalCollection::count(int elem) const 54 | { 55 | if (elem < start || elem > end) 56 | { 57 | return 0; 58 | } 59 | 60 | int index = elem - start; 61 | 62 | return data[index]; 63 | } 64 | 65 | bool IntervalCollection::contains(int elem) const 66 | { 67 | return count(elem) > 0; 68 | } -------------------------------------------------------------------------------- /Week 11/Collections/IntervalCollection.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include"DynamicCollection.h" 3 | 4 | class IntervalCollection : public DynamicCollection 5 | { 6 | private: 7 | int start; 8 | int end; 9 | public: 10 | IntervalCollection(int start, int end); 11 | unsigned intervalLength() const; 12 | 13 | void add(int) override; 14 | void remove(int) override; 15 | unsigned count(int) const override; 16 | bool contains(int) const override; 17 | }; -------------------------------------------------------------------------------- /Week 11/Collections/NormalCollection.cpp: -------------------------------------------------------------------------------- 1 | #include "NormalCollection.h" 2 | #include 3 | 4 | void NormalCollection::add(int elem) 5 | { 6 | if (size == capacity) 7 | { 8 | resize(2 * size); 9 | } 10 | 11 | data[size++] = elem; 12 | } 13 | 14 | void NormalCollection::remove(int elem) 15 | { 16 | int elemIndex = -1; 17 | 18 | for (size_t i = 0; i < size; i++) 19 | { 20 | if (data[i] == elem) 21 | { 22 | elemIndex = i; 23 | break; 24 | } 25 | } 26 | 27 | if (elemIndex != -1) 28 | { 29 | std::swap(data[elemIndex], data[size - 1]); 30 | size--; 31 | } 32 | } 33 | 34 | unsigned NormalCollection::count(int elem) const 35 | { 36 | unsigned elementCounter = 0; 37 | 38 | for (size_t i = 0; i < size; i++) 39 | { 40 | if (data[i] == elem) 41 | { 42 | ++elementCounter; 43 | } 44 | } 45 | 46 | return elementCounter; 47 | } 48 | 49 | bool NormalCollection::contains(int elem) const 50 | { 51 | for (size_t i = 0; i < size; i++) 52 | { 53 | if (data[i] == elem) 54 | { 55 | return true; 56 | } 57 | } 58 | return false; 59 | } -------------------------------------------------------------------------------- /Week 11/Collections/NormalCollection.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "PureNumbersCollection.h" 3 | 4 | class NormalCollection : public PureNumbersCollection 5 | { 6 | public: 7 | void add(int) override; 8 | void remove(int) override; 9 | unsigned count(int) const override; 10 | bool contains(int) const override; 11 | }; -------------------------------------------------------------------------------- /Week 11/Collections/PureNumbersCollection.cpp: -------------------------------------------------------------------------------- 1 | #include "PureNumbersCollection.h" 2 | -------------------------------------------------------------------------------- /Week 11/Collections/PureNumbersCollection.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "DynamicCollection.h" 3 | 4 | class PureNumbersCollection : public DynamicCollection 5 | { 6 | 7 | }; 8 | 9 | -------------------------------------------------------------------------------- /Week 11/Collections/Set.cpp: -------------------------------------------------------------------------------- 1 | #include "Set.h" 2 | #include "NormalCollection.h" 3 | #include "SortedCollection.h" 4 | 5 | Set::Set(CollectionType type) 6 | { 7 | if (type == NORMAL_COLLECTION) { 8 | collection = new NormalCollection(); 9 | } 10 | else if (type == SORTED_COLLECTION) { 11 | collection = new SortedCollection(); 12 | } 13 | } 14 | 15 | void Set::add(int elem) 16 | { 17 | if (!collection->contains(elem)) { 18 | collection->add(elem); 19 | } 20 | } 21 | 22 | void Set::remove(int elem) 23 | { 24 | collection->remove(elem); 25 | } 26 | 27 | unsigned Set::count(int elem) const 28 | { 29 | return collection->count(elem); 30 | } 31 | 32 | bool Set::contains(int elem) const 33 | { 34 | return collection->contains(elem); 35 | } 36 | 37 | Set::~Set() 38 | { 39 | delete collection; 40 | } -------------------------------------------------------------------------------- /Week 11/Collections/Set.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "Collection.cpp" 3 | #include "PureNumbersCollection.h" 4 | 5 | enum CollectionType { 6 | NORMAL_COLLECTION, 7 | SORTED_COLLECTION 8 | }; 9 | 10 | class Set : public Collection 11 | { 12 | PureNumbersCollection* collection; 13 | 14 | public: 15 | Set(CollectionType); 16 | 17 | Set(const Set&) = delete; 18 | Set& operator=(const Set&) = delete; 19 | 20 | void add(int) override; 21 | void remove(int) override; 22 | unsigned count(int) const override; 23 | bool contains(int) const override; 24 | 25 | ~Set(); 26 | }; 27 | -------------------------------------------------------------------------------- /Week 11/Collections/SortedCollection.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include"PureNumbersCollection.h" 3 | 4 | class SortedCollection : public PureNumbersCollection 5 | { 6 | int lowerBound(int x) const; 7 | int upperBound(int x) const; 8 | public: 9 | void add(int) override; 10 | void remove(int) override; 11 | unsigned count(int) const override; 12 | bool contains(int) const override; 13 | }; -------------------------------------------------------------------------------- /Week 11/Example_polymorphism/Circle.cpp: -------------------------------------------------------------------------------- 1 | #include "Circle.h" 2 | 3 | const double PI = 3.1415; 4 | Circle::Circle(int x, int y, double radius) : Shape(1), radius(radius) 5 | { 6 | setPoint(0, x, y); 7 | } 8 | 9 | double Circle::getArea() const 10 | { 11 | return PI * radius * radius; 12 | } 13 | double Circle::getPer() const 14 | { 15 | return 2 * PI * radius; 16 | } 17 | bool Circle::isPointIn(int x, int y) const 18 | { 19 | Shape::point p(x, y); 20 | return p.getDist(getPointAtIndex(0)) <= radius; 21 | } 22 | -------------------------------------------------------------------------------- /Week 11/Example_polymorphism/Circle.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "Shape.h" 3 | 4 | class Circle : public Shape 5 | { 6 | double radius; 7 | 8 | public: 9 | Circle(int x, int y, double radius); 10 | 11 | double getArea() const override; 12 | double getPer() const override; 13 | bool isPointIn(int x, int y) const override; 14 | 15 | }; -------------------------------------------------------------------------------- /Week 11/Example_polymorphism/Rectangle.cpp: -------------------------------------------------------------------------------- 1 | #include "Rectangle.h" 2 | #include 3 | 4 | Rectangle::Rectangle(int x1, int y1, int x3, int y3) : Shape(4) 5 | { 6 | setPoint(0, x1, y1); 7 | setPoint(1, x1, y3); 8 | setPoint(2, x3, y3); 9 | setPoint(3, x3, y1); 10 | } 11 | double Rectangle::getArea() const 12 | { 13 | const Shape::point& p0 = getPointAtIndex(0); 14 | const Shape::point& p1 = getPointAtIndex(1); 15 | const Shape::point& p3 = getPointAtIndex(3); 16 | 17 | return p0.getDist(p1) * p0.getDist(p3); 18 | 19 | } 20 | 21 | bool Rectangle::isPointIn(int x, int y) const 22 | { 23 | Shape::point p(x, y); 24 | int leftX = std::min(getPointAtIndex(0).x, getPointAtIndex(2).x); 25 | int rightX = std::max(getPointAtIndex(0).x, getPointAtIndex(2).x); 26 | 27 | int upY = std::max(getPointAtIndex(0).y, getPointAtIndex(2).y); 28 | int downY = std::min(getPointAtIndex(0).y, getPointAtIndex(2).y); 29 | 30 | return p.x >= leftX && p.x <= rightX && 31 | p.y <= upY && p.y >= downY; 32 | } 33 | -------------------------------------------------------------------------------- /Week 11/Example_polymorphism/Rectangle.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "Shape.h" 3 | 4 | class Rectangle : public Shape 5 | { 6 | public: 7 | Rectangle(int x1, int y1, int x3, int y3); 8 | double getArea() const override; 9 | bool isPointIn(int x, int y) const override; 10 | }; -------------------------------------------------------------------------------- /Week 11/Example_polymorphism/Shape.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | class Shape // Abstract class - no instances of Shape are allowed! 5 | { 6 | protected: 7 | struct point 8 | { 9 | point() :x(0), y(0){} 10 | point(int x, int y) :x(x), y(y){} 11 | int x; 12 | int y; 13 | double getDist(const point& other) const 14 | { 15 | int dx = x - other.x; 16 | int dy = y - other.y; 17 | 18 | return sqrt(dx*dx + dy*dy); 19 | } 20 | }; 21 | const point& getPointAtIndex(size_t index) const; 22 | private: 23 | point* points; 24 | size_t pointsCount; 25 | 26 | void copyFrom(const Shape& other); 27 | void moveFrom(Shape&& other); 28 | void free(); 29 | 30 | 31 | public: 32 | Shape(size_t pointsCount); 33 | 34 | Shape(const Shape& other); 35 | Shape(Shape&& other) noexcept; 36 | 37 | Shape& operator=(const Shape& other); 38 | Shape& operator=(Shape&& other) noexcept; 39 | 40 | virtual ~Shape(); //!!!!!! 41 | 42 | void setPoint(size_t pointIndex, int x, int y); 43 | 44 | virtual double getArea() const = 0; //pure virtual 45 | virtual double getPer() const; // non-pure virtual 46 | virtual bool isPointIn(int x, int y) const = 0; //pure virtual 47 | 48 | }; 49 | -------------------------------------------------------------------------------- /Week 11/Example_polymorphism/ShapeFactory.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "Rectangle.h" 3 | #include "Circle.h" 4 | #include "Triangle.h" 5 | 6 | class Shape; 7 | class Rectangle; 8 | class Circle; 9 | class Triangle; 10 | 11 | Shape* shapeFactory() 12 | { 13 | static std::random_device rd; 14 | static std::mt19937 gen(rd()); 15 | static std::uniform_int_distribution<> dist(0, 2); 16 | 17 | int r = dist(gen); //random generator 18 | 19 | switch (r) 20 | { 21 | case 0: return new Rectangle(3, 4, 6, 8); 22 | case 1: return new Circle(3, 3, 4); 23 | default: return new Triangle(1, 1, 2, 2, 3, 3); 24 | } 25 | } -------------------------------------------------------------------------------- /Week 11/Example_polymorphism/ShapeFactory.h: -------------------------------------------------------------------------------- 1 | #include "Shape.h" 2 | 3 | Shape* shapeFactory(); -------------------------------------------------------------------------------- /Week 11/Example_polymorphism/Triangle.cpp: -------------------------------------------------------------------------------- 1 | #include "Triangle.h" 2 | #include 3 | 4 | Triangle::Triangle(int x1, int y1, int x2, int y2, int x3, int y3) : Shape(3) 5 | { 6 | setPoint(0, x1, y1); 7 | setPoint(1, x2, y2); 8 | setPoint(2, x3, y3); 9 | } 10 | double Triangle::getArea() const 11 | { 12 | const Shape::point& p1 = getPointAtIndex(0); 13 | const Shape::point& p2 = getPointAtIndex(1); 14 | const Shape::point& p3 = getPointAtIndex(2); 15 | 16 | return abs(p1.x*p2.y + p2.x*p3.y + p3.x*p1.y - p1.y * p2.x - p2.y*p3.x - p3.y*p1.x) / 2.00; //formula with the determinant 17 | } 18 | 19 | bool Triangle::isPointIn(int x, int y) const 20 | { 21 | Shape::point p(x, y); 22 | Triangle t1(getPointAtIndex(0).x, getPointAtIndex(0).y, getPointAtIndex(1).x, getPointAtIndex(1).y, p.x, p.y); 23 | Triangle t2(getPointAtIndex(2).x, getPointAtIndex(2).y, getPointAtIndex(1).x, getPointAtIndex(1).y, p.x, p.y); 24 | Triangle t3(getPointAtIndex(2).x, getPointAtIndex(2).y, getPointAtIndex(0).x, getPointAtIndex(0).y, p.x, p.y); 25 | 26 | return abs(t1.getArea() + t2.getArea() + t3.getArea() - getArea()) <= std::numeric_limits::epsilon(); 27 | 28 | } 29 | -------------------------------------------------------------------------------- /Week 11/Example_polymorphism/Triangle.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Shape.h" 4 | 5 | class Triangle : public Shape 6 | { 7 | 8 | public: 9 | Triangle(int x1, int y1, int x2, int y2, int x3, int y3); 10 | double getArea() const override; 11 | bool isPointIn(int x, int y) const override; 12 | }; -------------------------------------------------------------------------------- /Week 11/Example_polymorphism/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #include "ShapeFactory.h" 4 | 5 | 6 | void printAreas(const Shape* const * shapes, size_t shapesCount) 7 | { 8 | for (int i = 0; i < shapesCount; i++) 9 | cout << shapes[i]->getArea() <getPer() << endl; 15 | } 16 | 17 | void checkPointIn(const Shape* const* shapes, size_t shapesCount, int x, int y) 18 | { 19 | for (int i = 0; i < shapesCount; i++) 20 | cout << shapes[i]->isPointIn(x,y) << endl; 21 | } 22 | 23 | void freeCollection(Shape** shapes, size_t shapesCount) 24 | { 25 | for (int i = 0; i < shapesCount; i++) 26 | delete shapes[i]; 27 | delete[] shapes; 28 | } 29 | 30 | int main() 31 | { 32 | Shape** arr = new Shape*[4]; 33 | 34 | for (int i = 0; i < 4; i++) 35 | arr[i] = shapeFactory(); 36 | 37 | printAreas(arr, 4); 38 | std::cout << endl; 39 | printPers(arr, 4); 40 | std::cout << endl; 41 | checkPointIn(arr, 4, 3, 3); 42 | 43 | freeCollection(arr, 4); 44 | } 45 | -------------------------------------------------------------------------------- /Week 11/File Readers and Writers/ArrFileReader.cpp: -------------------------------------------------------------------------------- 1 | #include "ArrFileReader.h" 2 | #include 3 | 4 | int ArrFileReader::getCharCount(std::ifstream& ifs, char ch) 5 | { 6 | size_t currPos = ifs.tellg(); 7 | 8 | if (!ifs.is_open()) { 9 | return -1; 10 | } 11 | 12 | int count = 0; 13 | while (true) { 14 | char current = ifs.get(); 15 | 16 | if (ifs.eof()) { 17 | break; 18 | } 19 | 20 | if (current == ch) { 21 | count++; 22 | } 23 | } 24 | 25 | ifs.clear(); 26 | ifs.seekg(currPos); 27 | return count; 28 | } 29 | 30 | ArrFileReader::ArrFileReader(const MyString& filePath) : FileReader(filePath) 31 | { 32 | } 33 | 34 | int* ArrFileReader::read(size_t& size) const 35 | { 36 | std::ifstream inFile(filePath.c_str()); 37 | 38 | if (!inFile.is_open()) { 39 | throw std::exception("Cannot open file"); 40 | } 41 | 42 | size = getCharCount(inFile, ' ') + 1; 43 | int* arr = new int[size]; 44 | 45 | inFile.ignore(); 46 | 47 | for (size_t i = 0; i < size; i++) 48 | { 49 | inFile >> arr[i]; 50 | } 51 | inFile.close(); 52 | return arr; 53 | } 54 | -------------------------------------------------------------------------------- /Week 11/File Readers and Writers/ArrFileReader.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "FileReader.h" 3 | 4 | class ArrFileReader : public FileReader 5 | { 6 | static int getCharCount(std::ifstream& ifs, char ch); 7 | public: 8 | ArrFileReader(const MyString& filePath); 9 | int* read(size_t& size) const override; 10 | }; 11 | 12 | -------------------------------------------------------------------------------- /Week 11/File Readers and Writers/ArrFileWriter.cpp: -------------------------------------------------------------------------------- 1 | #include "ArrFileWriter.h" 2 | #include 3 | 4 | ArrFileWriter::ArrFileWriter(const MyString& filePath) : FileWriter(filePath) 5 | { 6 | } 7 | 8 | void ArrFileWriter::write(const int* arr, size_t size) const 9 | { 10 | std::ofstream outFile(filePath.c_str()); 11 | 12 | if (!outFile.is_open()) { 13 | throw std::exception("Cannot open file"); 14 | } 15 | 16 | outFile << '['; 17 | 18 | for (size_t i = 0; i < size; i++) 19 | { 20 | outFile << arr[i]; 21 | if (i != size - 1) { 22 | outFile << ' '; 23 | } 24 | } 25 | 26 | outFile << ']'; 27 | outFile.close(); 28 | } 29 | -------------------------------------------------------------------------------- /Week 11/File Readers and Writers/ArrFileWriter.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "FileWriter.h" 3 | 4 | class ArrFileWriter : public FileWriter 5 | { 6 | public: 7 | ArrFileWriter(const MyString& filePath); 8 | // Inherited via FileWriter 9 | void write(const int* arr, size_t size) const override; 10 | }; 11 | -------------------------------------------------------------------------------- /Week 11/File Readers and Writers/BinaryFileReader.cpp: -------------------------------------------------------------------------------- 1 | #include "BinaryFileReader.h" 2 | #include 3 | 4 | 5 | int BinaryFileReader::getFileSize(std::ifstream& ifs) 6 | { 7 | int currPos = ifs.tellg(); 8 | ifs.seekg(0, std::ios::end); 9 | int size = ifs.tellg(); 10 | ifs.seekg(currPos); 11 | 12 | return size; 13 | } 14 | 15 | BinaryFileReader::BinaryFileReader(const MyString& filePath) : FileReader(filePath) 16 | { 17 | } 18 | 19 | int* BinaryFileReader::read(size_t& size) const 20 | { 21 | std::ifstream inFile(filePath.c_str(), std::ios::binary); 22 | 23 | if (!inFile.is_open()) { 24 | throw std::exception("Cannot open file"); 25 | } 26 | 27 | size = getFileSize(inFile) / sizeof(int); 28 | int* arr = new int[size]; 29 | 30 | inFile.read((char*)arr, size * sizeof(int)); 31 | inFile.close(); 32 | return arr; 33 | } 34 | -------------------------------------------------------------------------------- /Week 11/File Readers and Writers/BinaryFileReader.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "FileReader.h" 3 | class BinaryFileReader : public FileReader 4 | { 5 | static int getFileSize(std::ifstream& ifs); 6 | public: 7 | BinaryFileReader(const MyString& filePath); 8 | int* read(size_t& size) const override; 9 | }; 10 | 11 | -------------------------------------------------------------------------------- /Week 11/File Readers and Writers/BinaryFileWriter.cpp: -------------------------------------------------------------------------------- 1 | #include "BinaryFileWriter.h" 2 | #include 3 | 4 | BinaryFileWriter::BinaryFileWriter(const MyString& filePath) : FileWriter(filePath) 5 | { 6 | } 7 | 8 | void BinaryFileWriter::write(const int* arr, size_t size) const 9 | { 10 | std::ofstream outFile(filePath.c_str(), std::ios::binary); 11 | 12 | if (!outFile.is_open()) { 13 | throw std::exception("Cannot open file"); 14 | } 15 | 16 | outFile.write((const char*)arr, size * sizeof(int)); 17 | outFile.close(); 18 | } 19 | -------------------------------------------------------------------------------- /Week 11/File Readers and Writers/BinaryFileWriter.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "FileWriter.h" 3 | 4 | class BinaryFileWriter : public FileWriter 5 | { 6 | public: 7 | BinaryFileWriter(const MyString& filePath); 8 | void write(const int* arr, size_t size) const override; 9 | }; 10 | -------------------------------------------------------------------------------- /Week 11/File Readers and Writers/CSVFileReader.cpp: -------------------------------------------------------------------------------- 1 | #include "CSVFileReader.h" 2 | #include 3 | #include 4 | 5 | int CSVFileReader::getCharCount(std::ifstream& ifs, char ch) 6 | { 7 | size_t currPos = ifs.tellg(); 8 | 9 | if (!ifs.is_open()) { 10 | return -1; 11 | } 12 | 13 | int count = 0; 14 | while (true) { 15 | char current = ifs.get(); 16 | 17 | if (ifs.eof()) { 18 | break; 19 | } 20 | 21 | if (current == ch) { 22 | count++; 23 | } 24 | } 25 | 26 | ifs.clear(); 27 | ifs.seekg(currPos); 28 | return count; 29 | } 30 | 31 | CSVFileReader::CSVFileReader(const MyString& filePath) : FileReader(filePath) 32 | { 33 | 34 | } 35 | 36 | int* CSVFileReader::read(size_t& size) const 37 | { 38 | std::ifstream inFile(filePath.c_str()); 39 | 40 | if (!inFile.is_open()) { 41 | throw std::exception("Cannot open file"); 42 | } 43 | 44 | size = getCharCount(inFile, ',') + 1; 45 | int* arr = new int[size]; 46 | 47 | for (size_t i = 0; i < size; i++) 48 | { 49 | inFile >> arr[i]; 50 | inFile.ignore(); 51 | } 52 | inFile.close(); 53 | return arr; 54 | } 55 | -------------------------------------------------------------------------------- /Week 11/File Readers and Writers/CSVFileReader.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "FileReader.h" 3 | class CSVFileReader : public FileReader 4 | { 5 | static int getCharCount(std::ifstream& ifs, char ch); 6 | public: 7 | CSVFileReader(const MyString& filePath); 8 | int* read(size_t& size) const override; 9 | }; 10 | 11 | -------------------------------------------------------------------------------- /Week 11/File Readers and Writers/CSVFileWriter.cpp: -------------------------------------------------------------------------------- 1 | #include "CSVFileWriter.h" 2 | #include 3 | 4 | CSVFileWriter::CSVFileWriter(const MyString& filePath) : FileWriter(filePath) 5 | { 6 | } 7 | 8 | void CSVFileWriter::write(const int* arr, size_t size) const 9 | { 10 | std::ofstream outFile(filePath.c_str()); 11 | 12 | if (!outFile.is_open()) { 13 | throw std::exception("Cannot open file"); 14 | } 15 | 16 | for (size_t i = 0; i < size; i++) 17 | { 18 | outFile << arr[i]; 19 | if (i != size - 1) { 20 | outFile << ','; 21 | } 22 | } 23 | 24 | outFile.close(); 25 | } 26 | -------------------------------------------------------------------------------- /Week 11/File Readers and Writers/CSVFileWriter.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "FileWriter.h" 3 | 4 | class CSVFileWriter : public FileWriter 5 | { 6 | public: 7 | CSVFileWriter(const MyString& filePath); 8 | void write(const int* arr, size_t size) const override; 9 | }; 10 | 11 | -------------------------------------------------------------------------------- /Week 11/File Readers and Writers/FilePath.cpp: -------------------------------------------------------------------------------- 1 | #include "FilePath.h" 2 | #include 3 | 4 | FilePath::FilePath(const MyString& fileName) 5 | { 6 | const char* beg = fileName.c_str(); 7 | const char* end = fileName.c_str() + fileName.getSize(); 8 | const char* iter = end; 9 | 10 | while (iter != beg && *iter != '.') { 11 | iter--; 12 | } 13 | 14 | this->name = fileName.substr(0, iter - beg); 15 | this->extension = fileName.substr(iter - beg, end - iter); 16 | } 17 | 18 | const MyString& FilePath::getName() const 19 | { 20 | return name; 21 | } 22 | 23 | const MyString& FilePath::getExtension() const 24 | { 25 | return extension; 26 | } 27 | -------------------------------------------------------------------------------- /Week 11/File Readers and Writers/FilePath.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "MyString.h" 3 | 4 | class FilePath 5 | { 6 | MyString name; 7 | MyString extension; 8 | 9 | public: 10 | FilePath(const MyString& fileName); 11 | const MyString& getName() const; 12 | const MyString& getExtension() const; 13 | }; 14 | 15 | -------------------------------------------------------------------------------- /Week 11/File Readers and Writers/FileReader.cpp: -------------------------------------------------------------------------------- 1 | #include "FileReader.h" 2 | 3 | FileReader::FileReader(const MyString& filePath) : filePath(filePath) 4 | { 5 | } 6 | -------------------------------------------------------------------------------- /Week 11/File Readers and Writers/FileReader.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "MyString.h" 3 | class FileReader 4 | { 5 | protected: 6 | MyString filePath; 7 | public: 8 | FileReader(const MyString& filePath); 9 | virtual int* read(size_t& size) const = 0; 10 | 11 | virtual ~FileReader() = default; 12 | }; 13 | 14 | -------------------------------------------------------------------------------- /Week 11/File Readers and Writers/FileWriter.cpp: -------------------------------------------------------------------------------- 1 | #include "FileWriter.h" 2 | 3 | FileWriter::FileWriter(const MyString& filePath) : filePath(filePath) 4 | { 5 | } 6 | -------------------------------------------------------------------------------- /Week 11/File Readers and Writers/FileWriter.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "MyString.h" 3 | class FileWriter 4 | { 5 | protected: 6 | MyString filePath; 7 | public: 8 | FileWriter(const MyString& filePath); 9 | virtual void write(const int* arr, size_t size) const = 0; 10 | 11 | virtual ~FileWriter() = default; 12 | }; 13 | 14 | -------------------------------------------------------------------------------- /Week 11/File Readers and Writers/MyString.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | class MyString 5 | { 6 | public: 7 | MyString(); 8 | MyString(const char* data); 9 | 10 | MyString(const MyString& other); 11 | MyString(MyString&& other) noexcept; 12 | 13 | MyString& operator=(const MyString& other); 14 | 15 | MyString& operator=(MyString&& other) noexcept; 16 | ~MyString(); 17 | 18 | size_t getCapacity() const; 19 | size_t getSize() const; 20 | 21 | const char* c_str() const; 22 | 23 | MyString& operator+=(const MyString& other); 24 | 25 | char& operator[](size_t index); 26 | const char& operator[](size_t index) const; 27 | 28 | friend std::ostream& operator<<(std::ostream& os, const MyString& obj); 29 | friend std::istream& operator>>(std::istream& is, MyString& ref); 30 | friend MyString operator+(const MyString& lhs, const MyString& rhs); 31 | 32 | MyString substr(size_t begin, size_t howMany) const; 33 | 34 | private: 35 | explicit MyString(size_t stringLength); 36 | void resize(unsigned newAllocatedDataSize); 37 | 38 | void free(); 39 | void copyFrom(const MyString& other); 40 | 41 | void moveFrom(MyString&& other); 42 | 43 | char* _data; 44 | size_t _size; 45 | size_t _allocatedDataSize; 46 | }; 47 | 48 | 49 | 50 | bool operator==(const MyString& lhs, const MyString& rhs); 51 | bool operator!=(const MyString& lhs, const MyString& rhs); 52 | bool operator<(const MyString& lhs, const MyString& rhs); 53 | bool operator<=(const MyString& lhs, const MyString& rhs); 54 | bool operator>(const MyString& lhs, const MyString& rhs); 55 | bool operator>=(const MyString& lhs, const MyString& rhs); -------------------------------------------------------------------------------- /Week 11/File Readers and Writers/StringView.cpp: -------------------------------------------------------------------------------- 1 | #include "StringView.h" 2 | 3 | StringView::StringView(const char* begin, const char* end) : _begin(begin), _end(end) 4 | {} 5 | 6 | StringView::StringView(const char* str) : StringView(str, str + strlen(str)) {} 7 | 8 | StringView::StringView(const MyString& str) : StringView(str.c_str()) {} 9 | 10 | size_t StringView::length() const 11 | { 12 | return _end - _begin; 13 | } 14 | char StringView::operator[](size_t index) const 15 | { 16 | return _begin[index]; 17 | } 18 | 19 | StringView StringView::substr(size_t from, size_t length) const 20 | { 21 | if (_begin + from + length > _end) 22 | throw std::length_error("Error, Substr out of range"); 23 | 24 | return StringView(_begin + from, _begin + from + length); 25 | } 26 | 27 | std::ostream& operator<<(std::ostream& os, const StringView& strView) 28 | { 29 | const char* iter = strView._begin; 30 | 31 | while (iter != strView._end) 32 | { 33 | os << *iter; 34 | iter++; 35 | } 36 | return os; 37 | } 38 | 39 | bool operator==(const StringView& lhs, const StringView& rhs) 40 | { 41 | if (lhs.length() != rhs.length()) { 42 | return false; 43 | } 44 | for (size_t i = 0; i < lhs.length(); i++) 45 | { 46 | if (lhs[i] != rhs[i]) { 47 | return false; 48 | } 49 | } 50 | return true; 51 | } 52 | 53 | bool operator!=(const StringView& lhs, const StringView& rhs) 54 | { 55 | return !operator==(lhs, rhs); 56 | } 57 | -------------------------------------------------------------------------------- /Week 11/File Readers and Writers/StringView.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include "MyString.h" 4 | class StringView 5 | { 6 | const char* _begin = nullptr; 7 | const char* _end = nullptr; //1 element after the final char; 8 | 9 | public: 10 | StringView() = default; 11 | StringView(const char* begin, const char* end); 12 | StringView(const char* str); //terminatedString 13 | StringView(const MyString& string); 14 | 15 | size_t length() const; 16 | char operator[](size_t ind) const; 17 | 18 | StringView substr(size_t from, size_t length) const; 19 | friend std::ostream& operator<<(std::ostream&, const StringView& strView); 20 | }; 21 | 22 | bool operator==(const StringView& lhs, const StringView& rhs); 23 | bool operator!=(const StringView& lhs, const StringView& rhs); 24 | -------------------------------------------------------------------------------- /Week 11/File Readers and Writers/numbers.arr: -------------------------------------------------------------------------------- 1 | [1 2 3 4] -------------------------------------------------------------------------------- /Week 11/File Readers and Writers/numbers.csv: -------------------------------------------------------------------------------- 1 | 1,2,3,4 -------------------------------------------------------------------------------- /Week 11/File Readers and Writers/numbers.dat: -------------------------------------------------------------------------------- 1 |  -------------------------------------------------------------------------------- /Week 11/File Readers and Writers/numbers2.arr: -------------------------------------------------------------------------------- 1 | [1 2 3 4] -------------------------------------------------------------------------------- /Week 11/virtual_functions_playground.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct A 4 | { 5 | virtual void f() 6 | { 7 | std::cout << "A::f()" << std::endl; 8 | } 9 | virtual void g() 10 | { 11 | std::cout << "A::f()" << std::endl; 12 | } 13 | void non_virtual_function() 14 | { 15 | std::cout << "A::non-virt()" << std::endl; 16 | } 17 | }; 18 | 19 | struct B : public A 20 | { 21 | void f() 22 | { 23 | std::cout << "B::f()" << std::endl; 24 | } 25 | void g() 26 | { 27 | std::cout << "B::f()" << std::endl; 28 | } 29 | void h() 30 | { 31 | std::cout << "B::f()" << std::endl; 32 | } 33 | }; 34 | 35 | struct C : public B 36 | { 37 | void f() 38 | { 39 | std::cout << "C::f()" << std::endl; 40 | } 41 | void non_virtual_function() 42 | { 43 | std::cout << "C::non_virtual_function()" << std::endl; 44 | } 45 | 46 | }; 47 | 48 | struct D : public C 49 | { 50 | void f() 51 | { 52 | std::cout << "C::f()" << std::endl; 53 | } 54 | void d() 55 | { 56 | std::cout << "D::h()" << std::endl; 57 | } 58 | }; 59 | 60 | 61 | 62 | 63 | int main() 64 | { 65 | A objA; 66 | B objB; 67 | C objC; 68 | D objD; 69 | 70 | A* ptrA = &objA; 71 | 72 | ptrA->f(); 73 | ptrA->g(); 74 | ptrA->non_virtual_function(); 75 | 76 | A* ptrB = &objB; 77 | 78 | ptrB->f(); 79 | ptrB->g(); 80 | ptrB->non_virtual_function(); 81 | 82 | B* ptrC = &objC; 83 | 84 | ptrC->f(); 85 | ptrC->g(); 86 | ptrC->non_virtual_function(); 87 | 88 | C* ptrD = &objD; 89 | 90 | ptrD->f(); 91 | ptrD->g(); 92 | ptrD->non_virtual_function(); 93 | 94 | 95 | } 96 | -------------------------------------------------------------------------------- /Week 12/Example_visitor/Circle.cpp: -------------------------------------------------------------------------------- 1 | #include "Circle.h" 2 | 3 | const double PI = 3.1415; 4 | Circle::Circle(int x, int y, double radius) : Shape(1), radius(radius) 5 | { 6 | setPoint(0, x, y); 7 | } 8 | 9 | bool Circle::intersectsWith(const Shape* other) const 10 | { 11 | return other->intersectsWithCircle(this); 12 | } 13 | 14 | bool Circle::intersectsWithTriangle(const Triangle* other) const 15 | { 16 | std::cout << "Formula for circle with triangle" << std::endl; 17 | return true; 18 | } 19 | bool Circle::intersectsWithRect(const Rectangle* other) const 20 | { 21 | std::cout << "Formula for circle with rect" << std::endl; 22 | return true; 23 | } 24 | bool Circle::intersectsWithCircle(const Circle* other) const 25 | { 26 | std::cout << "Formula for circle with circle" << std::endl; 27 | return true; 28 | } 29 | -------------------------------------------------------------------------------- /Week 12/Example_visitor/Circle.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "Shape.h" 3 | #include "Circle.h" 4 | #include "Rectangle.h" 5 | #include "Triangle.h" 6 | 7 | 8 | class Circle : public Shape 9 | { 10 | double radius; 11 | 12 | public: 13 | Circle(int x, int y, double radius); 14 | 15 | bool intersectsWith(const Shape* other) const override; 16 | 17 | bool intersectsWithTriangle(const Triangle* other) const override; 18 | bool intersectsWithRect(const Rectangle* other) const override; 19 | bool intersectsWithCircle(const Circle* other) const override; 20 | 21 | }; -------------------------------------------------------------------------------- /Week 12/Example_visitor/Rectangle.cpp: -------------------------------------------------------------------------------- 1 | #include "Rectangle.h" 2 | 3 | Rectangle::Rectangle(int x1, int y1, int x3, int y3) : Shape(4) 4 | { 5 | setPoint(0, x1, y1); 6 | setPoint(1, x1, y3); 7 | setPoint(2, x3, y3); 8 | setPoint(3, x3, y1); 9 | } 10 | 11 | bool Rectangle::intersectsWith(const Shape* other) const 12 | { 13 | return other->intersectsWithRect(this); 14 | } 15 | 16 | bool Rectangle::intersectsWithTriangle(const Triangle* other) const 17 | { 18 | std::cout << "Formula for rect with triangle" << std::endl; 19 | return true; 20 | } 21 | bool Rectangle::intersectsWithRect(const Rectangle* other) const 22 | { 23 | std::cout << "Formula for rect with rect" << std::endl; 24 | return true; 25 | } 26 | bool Rectangle::intersectsWithCircle(const Circle* other) const 27 | { 28 | std::cout << "Formula for rect with circle" << std::endl; 29 | return true; 30 | } -------------------------------------------------------------------------------- /Week 12/Example_visitor/Rectangle.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "Shape.h" 3 | 4 | class Rectangle : public Shape 5 | { 6 | public: 7 | Rectangle(int x1, int y1, int x3, int y3); 8 | 9 | bool intersectsWith(const Shape* other) const override; 10 | 11 | bool intersectsWithTriangle(const Triangle* other) const override; 12 | bool intersectsWithRect(const Rectangle* other) const override; 13 | bool intersectsWithCircle(const Circle* other) const override; 14 | 15 | }; -------------------------------------------------------------------------------- /Week 12/Example_visitor/Shape.cpp: -------------------------------------------------------------------------------- 1 | #include "Shape.h" 2 | 3 | Shape::Shape(size_t pointsCount) : pointsCount(pointsCount) 4 | { 5 | points = new point[pointsCount]; // [0,0], [0,0].... 6 | } 7 | 8 | void Shape::copyFrom(const Shape& other) 9 | { 10 | points = new point[other.pointsCount]; 11 | 12 | for (int i = 0; i < other.pointsCount; i++) 13 | points[i] = other.points[i]; 14 | 15 | pointsCount = other.pointsCount; 16 | } 17 | void Shape::free() 18 | { 19 | delete[] points; 20 | } 21 | 22 | Shape::Shape(const Shape& other) 23 | { 24 | copyFrom(other); 25 | } 26 | Shape& Shape::operator= (const Shape& other) 27 | { 28 | if (this != &other) 29 | { 30 | free(); 31 | copyFrom(other); 32 | } 33 | return *this; 34 | } 35 | Shape::~Shape() 36 | { 37 | free(); 38 | } 39 | 40 | const Shape::point& Shape::getPointAtIndex(size_t index) const 41 | { 42 | if (index >= pointsCount) 43 | throw std::exception("Invalid point index!"); 44 | 45 | return points[index]; 46 | } 47 | 48 | void Shape::setPoint(size_t pointIndex, int x, int y) 49 | { 50 | if (pointIndex >= pointsCount) 51 | throw std::exception("Invalid point index!"); 52 | 53 | points[pointIndex] = point(x, y); 54 | } 55 | -------------------------------------------------------------------------------- /Week 12/Example_visitor/Shape.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | 5 | class Triangle; 6 | class Rectangle; 7 | class Circle; 8 | 9 | class Shape // Abstract class - no instances of Shape are allowed! 10 | { 11 | protected: 12 | struct point 13 | { 14 | point() :x(0), y(0){} 15 | point(int x, int y) :x(x), y(y){} 16 | int x; 17 | int y; 18 | double getDist(const point& other) const 19 | { 20 | int dx = x - other.x; 21 | int dy = y - other.y; 22 | 23 | return sqrt(dx*dx + dy*dy); 24 | } 25 | }; 26 | const point& getPointAtIndex(size_t index) const; 27 | private: 28 | point* points; 29 | size_t pointsCount; 30 | 31 | void copyFrom(const Shape& other); 32 | void free(); 33 | 34 | 35 | public: 36 | Shape(size_t pointsCount); 37 | 38 | Shape(const Shape& other); 39 | Shape& operator=(const Shape& other); 40 | virtual ~Shape(); //!!!!!! 41 | 42 | void setPoint(size_t pointIndex, int x, int y); 43 | 44 | 45 | virtual bool intersectsWith(const Shape* other) const = 0; 46 | 47 | virtual bool intersectsWithTriangle(const Triangle* other) const = 0; 48 | virtual bool intersectsWithRect(const Rectangle* other) const = 0; 49 | virtual bool intersectsWithCircle(const Circle* other) const = 0; 50 | }; -------------------------------------------------------------------------------- /Week 12/Example_visitor/Triangle.cpp: -------------------------------------------------------------------------------- 1 | #include "Triangle.h" 2 | #include 3 | 4 | Triangle::Triangle(int x1, int y1, int x2, int y2, int x3, int y3) : Shape(3) 5 | { 6 | setPoint(0, x1, y1); 7 | setPoint(1, x2, y2); 8 | setPoint(2, x3, y3); 9 | } 10 | 11 | bool Triangle::intersectsWith(const Shape* other) const 12 | { 13 | return other->intersectsWithTriangle(this); 14 | } 15 | 16 | bool Triangle::intersectsWithTriangle(const Triangle* other) const 17 | { 18 | std::cout << "Formula for triangle with triangle" << std::endl; 19 | return true; 20 | } 21 | bool Triangle::intersectsWithRect(const Rectangle* other) const 22 | { 23 | std::cout << "Formula for triangle with rect" << std::endl; 24 | return true; 25 | } 26 | bool Triangle::intersectsWithCircle(const Circle* other) const 27 | { 28 | std::cout << "Formula for triangle with circle" << std::endl; 29 | return true; 30 | } -------------------------------------------------------------------------------- /Week 12/Example_visitor/Triangle.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Shape.h" 4 | 5 | class Triangle : public Shape 6 | { 7 | 8 | public: 9 | Triangle(int x1, int y1, int x2, int y2, int x3, int y3); 10 | 11 | bool intersectsWith(const Shape* other) const override; 12 | 13 | bool intersectsWithTriangle(const Triangle* other) const override; 14 | bool intersectsWithRect(const Rectangle* other) const override; 15 | bool intersectsWithCircle(const Circle* other) const override; 16 | 17 | }; -------------------------------------------------------------------------------- /Week 12/Example_visitor/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #include "Rectangle.h" 5 | #include "Circle.h" 6 | #include "Triangle.h" 7 | 8 | 9 | 10 | bool intersect(const Shape* sh1, const Shape* sh2) 11 | { 12 | return sh1->intersectsWith(sh2); 13 | } 14 | int main() 15 | { 16 | Shape** arr = new Shape*[4]; 17 | 18 | arr[0] = new Rectangle(3, 4, 6, 8); 19 | arr[1] = new Circle(3, 3, 4); 20 | arr[2] = new Circle(1, 4, 5); 21 | arr[3] = new Triangle(1, 1, 2, 2, 3, 3); 22 | 23 | intersect(arr[0], arr[1]); 24 | intersect(arr[1], arr[2]); 25 | intersect(arr[2], arr[3]); 26 | 27 | 28 | for (int i = 0; i < 4; i++) 29 | delete arr[i]; 30 | 31 | delete[] arr; 32 | 33 | } 34 | -------------------------------------------------------------------------------- /Week 12/FixedCapacityStack/MyStack.hpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | 4 | template 5 | class MyStack 6 | { 7 | private: 8 | T arr[S]; 9 | size_t size = 0; 10 | public: 11 | 12 | void push(const T& obj); 13 | void push(T&& obj); 14 | 15 | const T& peek() const; 16 | void pop(); 17 | 18 | bool isEmpty() const; 19 | }; 20 | 21 | 22 | template 23 | void MyStack::push(const T& obj) 24 | { 25 | if (size >= S) 26 | return; 27 | arr[size++] = obj; 28 | } 29 | 30 | template 31 | void MyStack::push(T&& obj) 32 | { 33 | if (size >= S) 34 | return; 35 | arr[size++] = std::move(obj); 36 | } 37 | 38 | template 39 | const T& MyStack::peek() const 40 | { 41 | if (isEmpty()) 42 | throw std::out_of_range("Error!"); 43 | 44 | return arr[size - 1]; 45 | } 46 | 47 | template 48 | void MyStack::pop() 49 | { 50 | if (isEmpty()) 51 | throw std::out_of_range("Error!"); 52 | size--; 53 | } 54 | 55 | template 56 | bool MyStack::isEmpty() const 57 | { 58 | return size == 0; 59 | } 60 | -------------------------------------------------------------------------------- /Week 12/FixedCapacityStack/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "MyStack.hpp" 4 | 5 | 6 | int main() 7 | { 8 | MyStack s; 9 | 10 | s.push(3); 11 | 12 | std::cout << s.peek(); 13 | return 0; 14 | } 15 | -------------------------------------------------------------------------------- /Week 12/FunctionAverage/FunctionAverage.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | template 4 | class IntFunctionAverage 5 | { 6 | private: 7 | FunctionOne first; 8 | FunctionTwo second; 9 | public: 10 | IntFunctionAverage(const FunctionOne& fOne, const FunctionTwo& fTwo) : 11 | first(fOne), 12 | second(fTwo) {} 13 | 14 | double average(int x) const 15 | { 16 | return (first(x) + second(x)) / 2.0; 17 | } 18 | }; -------------------------------------------------------------------------------- /Week 12/FunctionAverage/numbers.dat: -------------------------------------------------------------------------------- 1 |  -------------------------------------------------------------------------------- /Week 12/Polymorphic containters/Farm/Animal.cpp: -------------------------------------------------------------------------------- 1 | #include "Animal.h" 2 | -------------------------------------------------------------------------------- /Week 12/Polymorphic containters/Farm/Animal.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Angeld55/Object-oriented_programming_FMI/56245c795618b1b575e2c63963773ae0d4f66ace/Week 12/Polymorphic containters/Farm/Animal.h -------------------------------------------------------------------------------- /Week 12/Polymorphic containters/Farm/Cat.cpp: -------------------------------------------------------------------------------- 1 | #include "Cat.h" 2 | #include 3 | 4 | void Cat::roar() const 5 | { 6 | std::cout << "meow mewo" << std::endl; 7 | } 8 | 9 | Animal* Cat::clone() const 10 | { 11 | return new Cat(*this); 12 | } 13 | 14 | int Cat::getType() const 15 | { 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /Week 12/Polymorphic containters/Farm/Cat.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "Animal.h" 3 | 4 | class Cat : public Animal 5 | { 6 | public: 7 | void roar() const override; 8 | Animal* clone() const override; 9 | int getType() const override; 10 | }; 11 | 12 | -------------------------------------------------------------------------------- /Week 12/Polymorphic containters/Farm/Cow.cpp: -------------------------------------------------------------------------------- 1 | #include "Cow.h" 2 | #include 3 | 4 | void Cow::roar() const 5 | { 6 | std::cout << "muu muu" << std::endl; 7 | } 8 | 9 | Animal* Cow::clone() const 10 | { 11 | return new Cow(*this); 12 | } 13 | 14 | int Cow::getType() const 15 | { 16 | return 2; 17 | } -------------------------------------------------------------------------------- /Week 12/Polymorphic containters/Farm/Cow.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "Animal.h" 3 | 4 | class Cow : public Animal 5 | { 6 | public: 7 | void roar() const override; 8 | Animal* clone() const override; 9 | int getType() const override; 10 | }; 11 | 12 | -------------------------------------------------------------------------------- /Week 12/Polymorphic containters/Farm/Dog.cpp: -------------------------------------------------------------------------------- 1 | #include "Dog.h" 2 | #include 3 | 4 | void Dog::roar() const 5 | { 6 | std::cout << "wof wof" << std::endl; 7 | } 8 | 9 | Animal* Dog::clone() const 10 | { 11 | return new Dog(*this); 12 | } 13 | 14 | int Dog::getType() const 15 | { 16 | return 1; 17 | } -------------------------------------------------------------------------------- /Week 12/Polymorphic containters/Farm/Dog.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "Animal.h" 3 | 4 | class Dog : public Animal 5 | { 6 | public: 7 | void roar() const override; 8 | Animal* clone() const override; 9 | int getType() const override; 10 | }; 11 | 12 | -------------------------------------------------------------------------------- /Week 12/Polymorphic containters/Farm/Factory.cpp: -------------------------------------------------------------------------------- 1 | #include "Factory.h" 2 | #include 3 | #include "Dog.h" 4 | #include "Cat.h" 5 | #include "Cow.h" 6 | 7 | 8 | Animal* animalFactory() 9 | { 10 | int type; 11 | std::cin >> type; 12 | 13 | switch (type) 14 | { 15 | case 0: return new Dog(); 16 | case 1: return new Cow(); 17 | case 2: return new Cat(); 18 | default: 19 | return nullptr; 20 | break; 21 | } 22 | 23 | } -------------------------------------------------------------------------------- /Week 12/Polymorphic containters/Farm/Factory.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | class Animal; 3 | 4 | Animal* animalFactory(); -------------------------------------------------------------------------------- /Week 12/Polymorphic containters/Farm/Farm.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Angeld55/Object-oriented_programming_FMI/56245c795618b1b575e2c63963773ae0d4f66ace/Week 12/Polymorphic containters/Farm/Farm.cpp -------------------------------------------------------------------------------- /Week 12/Polymorphic containters/Farm/Farm.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | class Animal; //no need to include it. Just pointers 4 | class Farm 5 | { 6 | public: 7 | Farm(); 8 | Farm(const Farm& other); 9 | Farm& operator=(const Farm& other); 10 | ~Farm(); 11 | 12 | void addAnimal(Animal* animal); //will take ownership of the object 13 | void addAnimal(const Animal* animal);// will copy the object 14 | 15 | void roarAll() const; 16 | int getTypeCode(int index) const; // Bad design to have such function! 17 | 18 | private: 19 | 20 | void resize(); 21 | void freeDynamic(); 22 | void copyDynamic(const Farm& other); 23 | 24 | Animal** animals = nullptr; 25 | size_t capacity = 0; 26 | size_t count = 0; 27 | }; 28 | 29 | -------------------------------------------------------------------------------- /Week 12/Polymorphic containters/Farm/source.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "Farm.h" 3 | #include "Factory.h" 4 | 5 | 6 | int main() 7 | { 8 | Farm f; 9 | int n = 0; 10 | std::cin >> n; 11 | for (int i = 0; i < n; i++) 12 | f.addAnimal(animalFactory()); 13 | f.roarAll(); 14 | 15 | } //~Farm() --> deletes all animals 16 | 17 | -------------------------------------------------------------------------------- /Week 12/Polymorphic containters/ShapeCollection/Circle.cpp: -------------------------------------------------------------------------------- 1 | #include "Circle.h" 2 | 3 | const double PI = 3.1415; 4 | Circle::Circle(int x, int y, double radius) : Shape(1), radius(radius) 5 | { 6 | setPoint(0, x, y); 7 | } 8 | 9 | double Circle::getArea() const 10 | { 11 | return PI * radius * radius; 12 | } 13 | double Circle::getPer() const 14 | { 15 | return 2 * PI * radius; 16 | } 17 | bool Circle::isPointIn(int x, int y) const 18 | { 19 | Shape::point p(x, y); 20 | return p.getDist(getPointAtIndex(0)) <= radius; 21 | } 22 | 23 | Shape* Circle::clone() const 24 | { 25 | return new Circle(*this); 26 | } 27 | -------------------------------------------------------------------------------- /Week 12/Polymorphic containters/ShapeCollection/Circle.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "Shape.h" 3 | 4 | class Circle : public Shape 5 | { 6 | double radius; 7 | 8 | public: 9 | Circle(int x, int y, double radius); 10 | 11 | double getArea() const override; 12 | double getPer() const override; 13 | bool isPointIn(int x, int y) const override; 14 | Shape* clone() const override; 15 | }; -------------------------------------------------------------------------------- /Week 12/Polymorphic containters/ShapeCollection/Rectangle.cpp: -------------------------------------------------------------------------------- 1 | #include "Rectangle.h" 2 | 3 | Rectangle::Rectangle(int x1, int y1, int x3, int y3) : Shape(4) 4 | { 5 | setPoint(0, x1, y1); 6 | setPoint(1, x1, y3); 7 | setPoint(2, x3, y3); 8 | setPoint(3, x3, y1); 9 | } 10 | double Rectangle::getArea() const 11 | { 12 | const Shape::point& p0 = getPointAtIndex(0); 13 | const Shape::point& p1 = getPointAtIndex(1); 14 | const Shape::point& p3 = getPointAtIndex(3); 15 | 16 | return p0.getDist(p1) * p0.getDist(p3); 17 | 18 | } 19 | 20 | bool Rectangle::isPointIn(int x, int y) const 21 | { 22 | Shape::point p(x, y); 23 | return p.x >= getPointAtIndex(0).x && p.x <= getPointAtIndex(2).x && 24 | p.y <= getPointAtIndex(0).y && p.y >= getPointAtIndex(2).y; 25 | } 26 | 27 | Shape* Rectangle::clone() const 28 | { 29 | return new Rectangle(*this); 30 | } 31 | -------------------------------------------------------------------------------- /Week 12/Polymorphic containters/ShapeCollection/Rectangle.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "Shape.h" 3 | 4 | class Rectangle : public Shape 5 | { 6 | public: 7 | Rectangle(int x1, int y1, int x3, int y3); 8 | double getArea() const override; 9 | bool isPointIn(int x, int y) const override; 10 | Shape* clone() const override; 11 | }; -------------------------------------------------------------------------------- /Week 12/Polymorphic containters/ShapeCollection/Shape.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | class Circle; 5 | class Rectangle; 6 | class Triangle; 7 | 8 | class Shape // Abstract class - no instances of Shape are allowed! 9 | { 10 | protected: 11 | struct point 12 | { 13 | point() :x(0), y(0){} 14 | point(int x, int y) :x(x), y(y){} 15 | int x; 16 | int y; 17 | double getDist(const point& other) const 18 | { 19 | int dx = x - other.x; 20 | int dy = y - other.y; 21 | 22 | return sqrt(dx*dx + dy*dy); 23 | } 24 | }; 25 | const point& getPointAtIndex(size_t index) const; 26 | private: 27 | point* points; 28 | size_t pointsCount; 29 | 30 | void copyFrom(const Shape& other); 31 | void moveFrom(Shape&& other); 32 | void free(); 33 | public: 34 | Shape(size_t pointsCount); 35 | 36 | Shape(const Shape& other); 37 | Shape(Shape&& other) noexcept; 38 | 39 | Shape& operator=(const Shape& other); 40 | Shape& operator=(Shape&& other) noexcept; 41 | 42 | virtual ~Shape(); //!!!!!! 43 | 44 | void setPoint(size_t pointIndex, int x, int y); 45 | 46 | virtual double getArea() const = 0; //pure virtual 47 | virtual double getPer() const; // non-pure virtual 48 | virtual bool isPointIn(int x, int y) const = 0; //pure virtual 49 | virtual Shape* clone() const = 0; 50 | 51 | }; 52 | -------------------------------------------------------------------------------- /Week 12/Polymorphic containters/ShapeCollection/ShapeCollection.h: -------------------------------------------------------------------------------- 1 | #include "Shape.h" 2 | 3 | class ShapeCollection 4 | { 5 | public: 6 | ShapeCollection(); 7 | 8 | ShapeCollection(const ShapeCollection& other); 9 | ShapeCollection(ShapeCollection&& other) noexcept; 10 | 11 | ShapeCollection& operator=(const ShapeCollection&); 12 | ShapeCollection& operator=(ShapeCollection&&) noexcept; 13 | 14 | ~ShapeCollection() noexcept; 15 | 16 | void addFigure(Shape* shape); //will take the ownership of the object 17 | 18 | void addFigure(const Shape& shape); 19 | 20 | double getAreaByIndex(unsigned ind) const; 21 | double getPerByIndex(unsigned ind) const; 22 | double getIsPointInByIndex(unsigned ind, int x, int y) const; 23 | 24 | const Shape* operator[](unsigned) const; 25 | unsigned getSize() const; 26 | 27 | private: 28 | 29 | void resize(size_t newCap); 30 | void moveFrom(ShapeCollection&& other); 31 | void copyFrom(const ShapeCollection& other); 32 | void free(); 33 | 34 | Shape** data = nullptr; 35 | size_t capacity = 0; 36 | size_t size = 0;; 37 | }; 38 | -------------------------------------------------------------------------------- /Week 12/Polymorphic containters/ShapeCollection/ShapeFactory.cpp: -------------------------------------------------------------------------------- 1 | #include "ShapeFactory.h" 2 | #include "Circle.h" 3 | #include "Rectangle.h" 4 | #include "Triangle.h" 5 | #include 6 | 7 | Shape* shapeFactory() 8 | { 9 | int figureType; 10 | std::cin >> figureType; 11 | 12 | switch (figureType) 13 | { 14 | case 1: 15 | { 16 | int x1, y1, x2, y2, x3, y3; 17 | std::cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3; 18 | return new Triangle(x1, y1, x2, y2, x3, y3); 19 | } 20 | case 2: 21 | { 22 | int x1, y1, radius; 23 | std::cin >> x1 >> y1 >> radius; 24 | return new Circle(x1, y1, radius); 25 | } 26 | case 3: 27 | { 28 | int x1, y1, x3, y3; 29 | std::cin >> x1 >> y1 >> x3 >> y3; 30 | return new Rectangle(x1, y1, x3, y3); 31 | } 32 | default: 33 | return nullptr; 34 | break; 35 | } 36 | } -------------------------------------------------------------------------------- /Week 12/Polymorphic containters/ShapeCollection/ShapeFactory.h: -------------------------------------------------------------------------------- 1 | #include "Shape.h" 2 | Shape* shapeFactory(); -------------------------------------------------------------------------------- /Week 12/Polymorphic containters/ShapeCollection/Triangle.cpp: -------------------------------------------------------------------------------- 1 | #include "Triangle.h" 2 | #include 3 | 4 | Triangle::Triangle(int x1, int y1, int x2, int y2, int x3, int y3) : Shape(3) 5 | { 6 | setPoint(0, x1, y1); 7 | setPoint(1, x2, y2); 8 | setPoint(2, x3, y3); 9 | } 10 | double Triangle::getArea() const 11 | { 12 | const Shape::point& p1 = getPointAtIndex(0); 13 | const Shape::point& p2 = getPointAtIndex(1); 14 | const Shape::point& p3 = getPointAtIndex(2); 15 | 16 | return abs(p1.x*p2.y + p2.x*p3.y + p3.x*p1.y - p1.y * p2.x - p2.y*p3.x - p3.y*p1.x) / 2.00; //formula with the determinant 17 | } 18 | 19 | bool Triangle::isPointIn(int x, int y) const 20 | { 21 | Shape::point p(x, y); 22 | Triangle t1(getPointAtIndex(0).x, getPointAtIndex(0).y, getPointAtIndex(1).x, getPointAtIndex(1).y, p.x, p.y); 23 | Triangle t2(getPointAtIndex(2).x, getPointAtIndex(2).y, getPointAtIndex(1).x, getPointAtIndex(1).y, p.x, p.y); 24 | Triangle t3(getPointAtIndex(2).x, getPointAtIndex(2).y, getPointAtIndex(0).x, getPointAtIndex(0).y, p.x, p.y); 25 | 26 | return abs(t1.getArea() + t2.getArea() + t3.getArea() - getArea()) <= std::numeric_limits::epsilon(); 27 | 28 | } 29 | 30 | 31 | Shape* Triangle::clone() const 32 | { 33 | return new Triangle(*this); 34 | } -------------------------------------------------------------------------------- /Week 12/Polymorphic containters/ShapeCollection/Triangle.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "Shape.h" 4 | 5 | class Triangle : public Shape 6 | { 7 | public: 8 | Triangle(int x1, int y1, int x2, int y2, int x3, int y3); 9 | double getArea() const override; 10 | bool isPointIn(int x, int y) const override; 11 | Shape* clone() const override; 12 | }; -------------------------------------------------------------------------------- /Week 12/Polymorphic containters/ShapeCollection/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "ShapeCollection.h" 3 | #include "ShapeFactory.h" 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | ShapeCollection collection; 9 | size_t n; 10 | std::cin >> n; 11 | 12 | for (int i = 0; i < n; i++) 13 | collection.addFigure(shapeFactory()); 14 | 15 | 16 | //Example usage of the container. 17 | 18 | double maxArea = 0; 19 | for (int i = 0; i < collection.getSize(); i++) 20 | { 21 | double currArea = collection[i]->getArea(); 22 | if (currArea > maxArea) 23 | maxArea = currArea; 24 | } 25 | std::cout << maxArea << std::endl; 26 | } 27 | -------------------------------------------------------------------------------- /Week 12/Templates/FixedCapacityStack/MyStack.hpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | 4 | template 5 | class MyStack 6 | { 7 | private: 8 | T arr[S]; 9 | size_t size = 0; 10 | public: 11 | 12 | void push(const T& obj); 13 | void push(T&& obj); 14 | 15 | const T& peek() const; 16 | void pop(); 17 | 18 | bool isEmpty() const; 19 | bool isFull() const; 20 | }; 21 | 22 | 23 | template 24 | void MyStack::push(const T& obj) 25 | { 26 | if (size >= S) 27 | return; 28 | arr[size++] = obj; 29 | } 30 | 31 | template 32 | void MyStack::push(T&& obj) 33 | { 34 | if (size >= S) 35 | return; 36 | arr[size++] = std::move(obj); 37 | } 38 | 39 | template 40 | const T& MyStack::peek() const 41 | { 42 | if (isEmpty()) 43 | throw std::out_of_range("Error!"); 44 | 45 | return arr[size - 1]; 46 | } 47 | 48 | template 49 | void MyStack::pop() 50 | { 51 | if (isEmpty()) 52 | throw std::out_of_range("Error!"); 53 | size--; 54 | } 55 | 56 | template 57 | bool MyStack::isEmpty() const 58 | { 59 | return size == 0; 60 | } 61 | 62 | template 63 | bool MyStack::isFull() const 64 | { 65 | return size == S; 66 | } 67 | -------------------------------------------------------------------------------- /Week 12/Templates/FixedCapacityStack/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "MyStack.hpp" 4 | 5 | 6 | int main() 7 | { 8 | MyStack s; 9 | 10 | s.push(3); 11 | 12 | std::cout << s.peek(); 13 | return 0; 14 | } 15 | -------------------------------------------------------------------------------- /Week 12/Templates/Template instantiation/Sorts.cpp: -------------------------------------------------------------------------------- 1 | #include "Sorts.h" 2 | #include 3 | 4 | struct A; 5 | template 6 | void SelectionSort(T* pArr, size_t Size) 7 | { 8 | if (!pArr || Size == 0) 9 | return; 10 | 11 | for (size_t i = 0; i < Size - 1; i++) 12 | { 13 | size_t min = i; 14 | 15 | for (size_t j = i + 1; j < Size; j++) 16 | { 17 | if (pArr[j] < pArr[min]) 18 | min = j; 19 | } 20 | 21 | if (pArr[min] < pArr[i]) 22 | std::swap(pArr[i], pArr[min]); 23 | } 24 | } 25 | 26 | template 27 | void BubbleSort(T* pArr, size_t Size) 28 | { 29 | if (!pArr || Size == 0) 30 | return; 31 | 32 | for (size_t i = 0; i < Size - 1; i++) 33 | { 34 | for (size_t j = Size - 1; j > i; j--) 35 | { 36 | if (pArr[j] < pArr[j - 1]) 37 | std::swap(pArr[j], pArr[j - 1]); 38 | } 39 | } 40 | } 41 | 42 | template void SelectionSort(double* pArr, size_t Size); 43 | template void BubbleSort(double* pArr, size_t Size); 44 | 45 | 46 | template void BubbleSort(A* pArr, size_t Size); -------------------------------------------------------------------------------- /Week 12/Templates/Template instantiation/Sorts.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | struct A 4 | { 5 | bool operator<(const A& other) const 6 | { 7 | return false; 8 | } 9 | }; 10 | 11 | template void SelectionSort(T* pArr, size_t Size); 12 | template void BubbleSort(T* pArr, size_t Size); 13 | -------------------------------------------------------------------------------- /Week 12/Templates/Template instantiation/source.cpp: -------------------------------------------------------------------------------- 1 | #include "Sorts.h" 2 | 3 | int main() 4 | { 5 | A* str = nullptr; 6 | 7 | BubbleSort(str, 3); 8 | } 9 | -------------------------------------------------------------------------------- /Week 12/Templates/main.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Angeld55/Object-oriented_programming_FMI/56245c795618b1b575e2c63963773ae0d4f66ace/Week 12/Templates/main.cpp -------------------------------------------------------------------------------- /Week 12/UniquePointer/UniquePointer.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | template 4 | class UniquePointer 5 | { 6 | T* ptr; 7 | public: 8 | UniquePointer(T* ptr); 9 | 10 | UniquePointer(const UniquePointer&) = delete; 11 | UniquePointer& operator=(const UniquePointer&) = delete; 12 | 13 | UniquePointer(UniquePointer&&) noexcept; 14 | UniquePointer& operator=(UniquePointer&&) noexcept; 15 | 16 | T& operator*(); 17 | const T& operator*() const; 18 | 19 | T* operator->(); 20 | const T* operator->() const; 21 | 22 | ~UniquePointer(); 23 | }; 24 | 25 | template 26 | UniquePointer::UniquePointer(T* ptr) : ptr(ptr) 27 | {} 28 | 29 | template 30 | UniquePointer::UniquePointer(UniquePointer&& other) noexcept 31 | { 32 | ptr = other.ptr; 33 | other.ptr = nullptr; 34 | } 35 | template 36 | UniquePointer& UniquePointer::operator=(UniquePointer&& other) noexcept 37 | { 38 | if (this != &other) 39 | { 40 | delete ptr; 41 | ptr = other.ptr; 42 | other.ptr = nullptr; 43 | } 44 | return *this; 45 | } 46 | 47 | template 48 | T& UniquePointer::operator*() 49 | { 50 | return *ptr; 51 | } 52 | 53 | template 54 | const T& UniquePointer::operator*() const 55 | { 56 | return *ptr; 57 | } 58 | 59 | 60 | template 61 | T* UniquePointer::operator->() 62 | { 63 | return ptr; 64 | } 65 | 66 | template 67 | const T* UniquePointer::operator->() const 68 | { 69 | return ptr; 70 | } 71 | 72 | template 73 | UniquePointer::~UniquePointer() 74 | { 75 | delete *ptr; 76 | } 77 | 78 | 79 | -------------------------------------------------------------------------------- /Week 12/UniquePointer/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct A 5 | { 6 | A(int a) 7 | { 8 | std::cout << "A(int)" << std::endl; 9 | } 10 | 11 | ~A() 12 | { 13 | std::cout << "~A()" << std::endl; 14 | 15 | } 16 | }; 17 | int main() 18 | { 19 | 20 | std::unique_ptr ptr(new A(1)); 21 | 22 | } 23 | -------------------------------------------------------------------------------- /Week 13/Chess_basic_prototype/ChessBoard/ChessBoard.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "../Figures/FigureBase/Figure.h" 3 | 4 | const size_t BOARD_SIZE = 8; 5 | class ChessBoard 6 | { 7 | struct Cell 8 | { 9 | Figure* f = nullptr; 10 | Cell() = default; 11 | 12 | Cell(const Cell& other) = delete; 13 | Cell& operator=(const Cell& other) = delete; 14 | bool isEmpty() 15 | { 16 | return f == nullptr; 17 | } 18 | 19 | void print() const 20 | { 21 | if (f != nullptr) 22 | f->print(); 23 | else 24 | std::cout << ' '; 25 | } 26 | 27 | ~Cell() 28 | { 29 | delete f; 30 | } 31 | }; 32 | Cell board[BOARD_SIZE][BOARD_SIZE]; 33 | 34 | public: 35 | ChessBoard(); 36 | ChessBoard(const ChessBoard& other) = delete; 37 | ChessBoard& operator=(const ChessBoard&) = delete; 38 | 39 | void print() const; 40 | 41 | void moveFigure(size_t x, size_t y, size_t destX, size_t destY); 42 | 43 | }; 44 | -------------------------------------------------------------------------------- /Week 13/Chess_basic_prototype/ConfigEnums/ConfigEnums.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | enum FigureType 4 | { 5 | KingFigure, 6 | QueenFigure, 7 | KnightFigure, 8 | BishopFigure, 9 | PawnFigure, 10 | RookFigure 11 | }; -------------------------------------------------------------------------------- /Week 13/Chess_basic_prototype/FigureFactory/FigureFactory.cpp: -------------------------------------------------------------------------------- 1 | #include "FigureFactory.h" 2 | #include "../Figures/Bishop/Bishop.h" 3 | #include "../Figures/King/King.h" 4 | #include "../Figures/Knight/Knight.h" 5 | #include "../Figures/Rook/Rook.h" 6 | #include "../Figures/Queen/Queen.h" 7 | #include "../Figures/Pawn/Pawn.h" 8 | 9 | Figure* FigureFactory::createFigure(bool isWhite, FigureType type) 10 | { 11 | 12 | switch (type) 13 | { 14 | case KingFigure: 15 | return new King(isWhite); 16 | case QueenFigure: 17 | return new Queen(isWhite); 18 | case KnightFigure: 19 | return new Knight(isWhite); 20 | case BishopFigure: 21 | return new Bishop(isWhite); 22 | case PawnFigure: 23 | return new Pawn(isWhite); 24 | case RookFigure: 25 | return new Rook(isWhite); 26 | } 27 | } -------------------------------------------------------------------------------- /Week 13/Chess_basic_prototype/FigureFactory/FigureFactory.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "../Figures/FigureBase/Figure.h" 3 | #include "../ConfigEnums/ConfigEnums.h" 4 | 5 | class FigureFactory 6 | { 7 | public: 8 | static Figure* createFigure(bool isWhite, FigureType); //enum 9 | }; -------------------------------------------------------------------------------- /Week 13/Chess_basic_prototype/Figures/Bishop/Bishop.cpp: -------------------------------------------------------------------------------- 1 | #include "Bishop.h" 2 | #include 3 | 4 | Bishop::Bishop(bool isWhite) : Figure(isWhite, RookFigure) 5 | {} 6 | bool Bishop::canBeMoved(size_t currentX, size_t currentY, size_t destX, size_t destY) const 7 | { 8 | return abs((int)currentX - (int)destX) == abs((int)currentY - (int)destY); 9 | } 10 | void Bishop::print() const 11 | { 12 | if (getIsWhite()) 13 | std::cout << 'B'; 14 | else 15 | std::cout << 'b'; 16 | } 17 | -------------------------------------------------------------------------------- /Week 13/Chess_basic_prototype/Figures/Bishop/Bishop.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "../FigureBase/Figure.h" 3 | 4 | class Bishop : virtual public Figure 5 | { 6 | 7 | public: 8 | Bishop(bool isWhite); 9 | bool canBeMoved(size_t currentX, size_t currentY, size_t destX, size_t destY) const override; 10 | 11 | void print() const override; 12 | 13 | }; -------------------------------------------------------------------------------- /Week 13/Chess_basic_prototype/Figures/FigureBase/Figure.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Angeld55/Object-oriented_programming_FMI/56245c795618b1b575e2c63963773ae0d4f66ace/Week 13/Chess_basic_prototype/Figures/FigureBase/Figure.cpp -------------------------------------------------------------------------------- /Week 13/Chess_basic_prototype/Figures/FigureBase/Figure.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include "../../ConfigEnums/ConfigEnums.h" 4 | 5 | class Figure 6 | { 7 | bool isWhite; 8 | FigureType type; 9 | 10 | public: 11 | Figure(bool isWhite, FigureType type) :isWhite(isWhite), type(type) 12 | {} 13 | 14 | virtual bool canBeMoved(size_t currentX, size_t currentY, size_t destX, size_t destY) const = 0; 15 | virtual void print() const = 0; 16 | 17 | bool getIsWhite() const { return isWhite; }; 18 | FigureType getType() const { return type; } 19 | 20 | virtual ~Figure() = default; 21 | }; -------------------------------------------------------------------------------- /Week 13/Chess_basic_prototype/Figures/King/King.cpp: -------------------------------------------------------------------------------- 1 | #include "King.h" 2 | #include 3 | 4 | King::King(bool isWhite) : Figure(isWhite, KingFigure) 5 | {} 6 | bool King::canBeMoved(size_t currentX, size_t currentY, size_t destX, size_t destY) const 7 | { 8 | return abs((int)currentX - (int)destX) <= 1 && abs((int)currentY - (int)destY) <= 1; 9 | } 10 | void King::print() const 11 | { 12 | if (getIsWhite()) 13 | std::cout << '%'; 14 | else 15 | std::cout << '$'; 16 | } -------------------------------------------------------------------------------- /Week 13/Chess_basic_prototype/Figures/King/King.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "../FigureBase/Figure.h" 3 | 4 | class King : public Figure 5 | { 6 | 7 | public: 8 | King(bool isWhite); 9 | bool canBeMoved(size_t currentX, size_t currentY, size_t destX, size_t destY) const override; 10 | void print() const override; 11 | }; -------------------------------------------------------------------------------- /Week 13/Chess_basic_prototype/Figures/Knight/Knight.cpp: -------------------------------------------------------------------------------- 1 | #include "Knight.h" 2 | #include 3 | 4 | Knight::Knight(bool isWhite) : Figure(isWhite, KnightFigure) 5 | {} 6 | bool Knight::canBeMoved(size_t currentX, size_t currentY, size_t destX, size_t destY) const 7 | { 8 | int xMovеment[] = { 1, 1, -1, -1, 2, -2, 2, -2 }; 9 | int yMovеment[] = { 2, -2, 2, -2, 1, 1, -1, -1 }; 10 | 11 | for (int i = 0; i < 8; i++) 12 | { 13 | if (currentX + xMovеment[i] == destX && 14 | currentY + yMovеment[i] == destY) 15 | return true; 16 | } 17 | return false; 18 | } 19 | 20 | void Knight::print() const 21 | { 22 | if (getIsWhite()) 23 | std::cout << 'K'; 24 | else 25 | std::cout << 'k'; 26 | } -------------------------------------------------------------------------------- /Week 13/Chess_basic_prototype/Figures/Knight/Knight.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "../FigureBase/Figure.h" 3 | 4 | class Knight : public Figure 5 | { 6 | 7 | public: 8 | Knight(bool isWhite); 9 | bool canBeMoved(size_t currentX, size_t currentY, size_t destX, size_t destY) const override; 10 | void print() const override; 11 | }; -------------------------------------------------------------------------------- /Week 13/Chess_basic_prototype/Figures/Pawn/Pawn.cpp: -------------------------------------------------------------------------------- 1 | #include "Pawn.h" 2 | #include 3 | Pawn::Pawn(bool isWhite) : Figure(isWhite, PawnFigure), isFirstMove(true) 4 | {} 5 | 6 | bool Pawn::canBeMoved(size_t currentX, size_t currentY, size_t destX, size_t destY) const 7 | { 8 | if (getIsWhite()) 9 | return currentY - 1 == destY && abs((int)currentX - (int)destX) <= 1; 10 | else 11 | return currentY + 1 == destY && abs((int)currentX - (int)destX) <= 1; 12 | } 13 | 14 | void Pawn::print() const 15 | { 16 | if (getIsWhite()) 17 | std::cout << 'P'; 18 | else 19 | std::cout << 'p'; 20 | } -------------------------------------------------------------------------------- /Week 13/Chess_basic_prototype/Figures/Pawn/Pawn.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "../FigureBase/Figure.h" 3 | 4 | class Pawn : public Figure 5 | { 6 | bool isFirstMove; 7 | public: 8 | Pawn(bool isWhite); 9 | bool canBeMoved(size_t currentX, size_t currentY, size_t destX, size_t destY) const override; 10 | void print() const override; 11 | }; 12 | -------------------------------------------------------------------------------- /Week 13/Chess_basic_prototype/Figures/Queen/Queen.cpp: -------------------------------------------------------------------------------- 1 | #include "Queen.h" 2 | 3 | Queen::Queen(bool isWhite) : Bishop(isWhite), Rook(isWhite), Figure(isWhite, QueenFigure) 4 | {} 5 | 6 | bool Queen::canBeMoved(size_t currentX, size_t currentY, size_t destX, size_t destY) const 7 | { 8 | return Bishop::canBeMoved(currentX, currentY, destX, destY) 9 | || Rook::canBeMoved(currentX, currentY, destX, destY); 10 | } 11 | 12 | void Queen::print() const 13 | { 14 | if (getIsWhite()) 15 | std::cout << 'Q'; 16 | else 17 | std::cout << 'q'; 18 | } -------------------------------------------------------------------------------- /Week 13/Chess_basic_prototype/Figures/Queen/Queen.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "../Bishop/Bishop.h" 3 | #include "../Rook/Rook.h" 4 | 5 | class Queen : public Bishop, public Rook 6 | { 7 | public: 8 | Queen(bool isWhite); 9 | bool canBeMoved(size_t currentX, size_t currentY, size_t destX, size_t destY) const override; 10 | void print() const; 11 | }; 12 | -------------------------------------------------------------------------------- /Week 13/Chess_basic_prototype/Figures/Rook/Rook.cpp: -------------------------------------------------------------------------------- 1 | #include "Rook.h" 2 | 3 | Rook::Rook(bool isWhite) : Figure(isWhite, RookFigure) 4 | {} 5 | bool Rook::canBeMoved(size_t currentX, size_t currentY, size_t destX, size_t destY) const 6 | { 7 | return currentX == destX || currentY == destY; 8 | } 9 | void Rook::print() const 10 | { 11 | if (getIsWhite()) 12 | std::cout << 'R'; 13 | else 14 | std::cout << 'r'; 15 | } 16 | -------------------------------------------------------------------------------- /Week 13/Chess_basic_prototype/Figures/Rook/Rook.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "../FigureBase/Figure.h" 3 | 4 | class Rook : virtual public Figure 5 | { 6 | 7 | public: 8 | Rook(bool isWhite); 9 | bool canBeMoved(size_t currentX, size_t currentY, size_t destX, size_t destY) const override; 10 | void print() const override; 11 | }; -------------------------------------------------------------------------------- /Week 13/Chess_basic_prototype/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "ChessBoard/ChessBoard.h" 3 | using namespace std; 4 | 5 | //ШАХ 6 | 7 | int main() 8 | { 9 | ChessBoard c; 10 | 11 | c.print(); 12 | 13 | c.moveFigure(0, 1, 2, 0); 14 | 15 | c.print(); 16 | } -------------------------------------------------------------------------------- /Week 13/SmartPointers/SharedAndWeak/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "WeakPtr.hpp" 3 | 4 | 5 | struct A 6 | { 7 | A() { 8 | std::cout << "A()" << std::endl; 9 | } 10 | 11 | ~A() { 12 | std::cout << "~A()" << std::endl; 13 | } 14 | 15 | }; 16 | int main() 17 | { 18 | WeakPtr wp; 19 | { 20 | SharedPtr pt(new A()); 21 | wp = pt; 22 | 23 | std::cout << wp.expired() << std::endl; 24 | } 25 | 26 | std::cout << wp.expired() << std::endl; 27 | } -------------------------------------------------------------------------------- /Week 13/SmartPointers/UniquePointer/UniquePointer.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | template 4 | class UniquePointer 5 | { 6 | T* ptr; 7 | public: 8 | UniquePointer(T* ptr); 9 | 10 | UniquePointer(const UniquePointer&) = delete; 11 | UniquePointer& operator=(const UniquePointer&) = delete; 12 | 13 | UniquePointer(UniquePointer&&) noexcept; 14 | UniquePointer& operator=(UniquePointer&&) noexcept; 15 | 16 | T& operator*(); 17 | const T& operator*() const; 18 | 19 | T* operator->(); 20 | const T* operator->() const; 21 | 22 | ~UniquePointer(); 23 | }; 24 | 25 | template 26 | UniquePointer::UniquePointer(T* ptr) : ptr(ptr) 27 | {} 28 | 29 | template 30 | UniquePointer::UniquePointer(UniquePointer&& other) noexcept 31 | { 32 | ptr = other.ptr; 33 | other.ptr = nullptr; 34 | } 35 | template 36 | UniquePointer& UniquePointer::operator=(UniquePointer&& other) noexcept 37 | { 38 | if (this != &other) 39 | { 40 | delete ptr; 41 | ptr = other.ptr; 42 | other.ptr = nullptr; 43 | } 44 | return *this; 45 | } 46 | 47 | template 48 | T& UniquePointer::operator*() 49 | { 50 | return *ptr; 51 | } 52 | 53 | template 54 | const T& UniquePointer::operator*() const 55 | { 56 | return *ptr; 57 | } 58 | 59 | template 60 | T* UniquePointer::operator->() 61 | { 62 | return ptr; 63 | } 64 | 65 | template 66 | const T* UniquePointer::operator->() const 67 | { 68 | return ptr; 69 | } 70 | 71 | template 72 | UniquePointer::~UniquePointer() 73 | { 74 | delete ptr; 75 | } 76 | -------------------------------------------------------------------------------- /Week 13/SmartPointers/UniquePointer/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct A 5 | { 6 | A(int a) : x(a) 7 | { 8 | std::cout << "A(int)" << std::endl; 9 | } 10 | int x; 11 | ~A() 12 | { 13 | std::cout << "~A()" << std::endl; 14 | 15 | } 16 | }; 17 | int main() 18 | { 19 | 20 | std::unique_ptr ptr(new A(1)); 21 | std::cout << ptr->x << std::endl; 22 | } -------------------------------------------------------------------------------- /Week 13/readme.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Week 14/ExpressionCalculator/String and StringView/MyString.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | class MyString 5 | { 6 | public: 7 | MyString(); 8 | MyString(const char* data); 9 | 10 | MyString(const MyString& other); 11 | MyString(MyString&& other) noexcept; 12 | 13 | MyString& operator=(const MyString& other); 14 | 15 | MyString& operator=(MyString&& other) noexcept; 16 | ~MyString(); 17 | 18 | size_t getCapacity() const; 19 | size_t getSize() const; 20 | 21 | const char* c_str() const; 22 | 23 | MyString& operator+=(const MyString& other); 24 | 25 | char& operator[](size_t index); 26 | const char& operator[](size_t index) const; 27 | 28 | friend std::ostream& operator<<(std::ostream& os, const MyString& obj); 29 | friend std::istream& operator>>(std::istream& is, MyString& ref); 30 | friend MyString operator+(const MyString& lhs, const MyString& rhs); 31 | 32 | MyString substr(size_t begin, size_t howMany) const; 33 | 34 | private: 35 | explicit MyString(size_t stringLength); 36 | void resize(unsigned newAllocatedDataSize); 37 | 38 | void free(); 39 | void copyFrom(const MyString& other); 40 | 41 | void moveFrom(MyString&& other); 42 | 43 | char* _data; 44 | size_t _size; 45 | size_t _allocatedDataSize; 46 | }; 47 | 48 | 49 | 50 | bool operator==(const MyString& lhs, const MyString& rhs); 51 | bool operator!=(const MyString& lhs, const MyString& rhs); 52 | bool operator<(const MyString& lhs, const MyString& rhs); 53 | bool operator<=(const MyString& lhs, const MyString& rhs); 54 | bool operator>(const MyString& lhs, const MyString& rhs); 55 | bool operator>=(const MyString& lhs, const MyString& rhs); 56 | -------------------------------------------------------------------------------- /Week 14/ExpressionCalculator/String and StringView/StringView.cpp: -------------------------------------------------------------------------------- 1 | #include "StringView.h" 2 | 3 | StringView::StringView(const char* begin, const char* end): _begin(begin), _end(end) 4 | {} 5 | 6 | StringView::StringView(const char* str) : StringView(str, str + strlen(str)) {} 7 | 8 | StringView::StringView(const MyString& str) : StringView(str.c_str()) {} 9 | 10 | size_t StringView::length() const 11 | { 12 | return _end - _begin; 13 | } 14 | char StringView::operator[](size_t index) const 15 | { 16 | return _begin[index]; 17 | } 18 | 19 | StringView StringView::substr(size_t from, size_t length) const 20 | { 21 | if (_begin + from + length > _end) 22 | throw std::length_error("Error, Substr out of range"); 23 | 24 | return StringView(_begin + from, _begin + from + length); 25 | } 26 | 27 | std::ostream& operator<<(std::ostream& os, const StringView& strView) 28 | { 29 | const char* iter = strView._begin; 30 | 31 | while (iter != strView._end) 32 | { 33 | os << *iter; 34 | iter++; 35 | } 36 | return os; 37 | } 38 | -------------------------------------------------------------------------------- /Week 14/ExpressionCalculator/String and StringView/StringView.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include "MyString.h" 4 | class StringView 5 | { 6 | const char* _begin; 7 | const char* _end; //1 element after the final char; 8 | 9 | public: 10 | StringView(const char* begin, const char* end); 11 | StringView(const char* str); //terminatedString 12 | StringView(const MyString& string); 13 | 14 | size_t length() const; 15 | char operator[](size_t ind) const; 16 | 17 | StringView substr(size_t from, size_t length) const; 18 | friend std::ostream& operator<<(std::ostream&, const StringView& strView); 19 | 20 | }; 21 | 22 | //TODO: implement comparison operators -------------------------------------------------------------------------------- /Week 14/ExpressionCalculator/String and StringView/main.cpp: -------------------------------------------------------------------------------- 1 | #include "StringView.h" 2 | 3 | int main() 4 | { 5 | MyString test = "Hi, petur!"; 6 | StringView res(test); 7 | StringView res2 = res.substr(4, 5); 8 | std::cout << res2[0]; 9 | } 10 | -------------------------------------------------------------------------------- /Week 15/DesignPatterns/Creational/AbstractFactory.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct AirBag {}; 4 | struct EUSafetyStandardAirBag : AirBag {}; 5 | struct USSafetyStandardAirBag : AirBag {}; 6 | 7 | struct TurnSignal {}; 8 | struct YellowTurnSignal : TurnSignal { }; 9 | struct RedTurnSignal : TurnSignal { }; 10 | 11 | // Abstract factory creating a family of car parts 12 | class CarPartsFactory { 13 | public: 14 | virtual AirBag* createAirBag() const = 0; 15 | virtual TurnSignal* createTurnSignal() const = 0; 16 | // ... 17 | 18 | virtual ~CarPartsFactory() = default; 19 | }; 20 | 21 | class EuropeanCarPartsFactory : public CarPartsFactory { 22 | public: 23 | AirBag* createAirBag() const override { 24 | return new EUSafetyStandardAirBag(); 25 | } 26 | TurnSignal* createTurnSignal() const override { 27 | return new YellowTurnSignal(); 28 | } 29 | }; 30 | 31 | class USCarPartsFactory : public CarPartsFactory { 32 | public: 33 | AirBag* createAirBag() const override { 34 | return new USSafetyStandardAirBag(); 35 | } 36 | TurnSignal* createTurnSignal() const override { 37 | return new RedTurnSignal(); 38 | } 39 | }; 40 | 41 | // maybe with enum :) 42 | CarPartsFactory* factoryOfFactories(bool isEU) { 43 | if (isEU) { 44 | return new EuropeanCarPartsFactory(); 45 | } 46 | else { 47 | return new USCarPartsFactory(); 48 | } 49 | } 50 | 51 | void createCar(CarPartsFactory* partsFactory) { 52 | AirBag* airbag = partsFactory->createAirBag(); 53 | TurnSignal* turnSignal = partsFactory->createTurnSignal(); 54 | // create much more stuff 55 | } 56 | 57 | int main() { 58 | CarPartsFactory* factory = factoryOfFactories(true); 59 | createCar(factory); 60 | 61 | delete factory; 62 | } 63 | -------------------------------------------------------------------------------- /Week 15/DesignPatterns/Creational/FactoryAndFactoryMethod.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | class Base { 4 | public: 5 | virtual ~Base() = default; 6 | }; 7 | 8 | class Der1 : public Base {}; 9 | 10 | class Der2 : public Base {}; 11 | 12 | // Factory Method!!! 13 | class BaseFactory { 14 | public: 15 | virtual Base* create() const = 0; 16 | virtual ~BaseFactory() = default; 17 | }; 18 | 19 | class Der1Factory : public BaseFactory { 20 | public: 21 | Base* create() const override { 22 | return new Der1(); 23 | } 24 | }; 25 | 26 | class Der2Factory : public BaseFactory { 27 | public: 28 | Base* create() const override { 29 | return new Der2(); 30 | } 31 | }; 32 | 33 | // Factory !!! 34 | BaseFactory* factoryOfFactories(bool useDer1) { 35 | if (useDer1) { 36 | return new Der1Factory(); 37 | } 38 | else { 39 | return new Der2Factory(); 40 | } 41 | } 42 | 43 | 44 | void runApp(BaseFactory* factory) { 45 | 46 | } 47 | 48 | int main() { 49 | BaseFactory* factory = factoryOfFactories(true); 50 | runApp(factory); 51 | delete factory; 52 | } 53 | -------------------------------------------------------------------------------- /Week 15/DesignPatterns/Creational/Singleton.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | class SingletonClass { 4 | private: 5 | SingletonClass() { 6 | std::cout << "SingletonClass was created" << std::endl; 7 | } 8 | 9 | ~SingletonClass() { 10 | std::cout << "SingletonClass was destroyed" << std::endl; 11 | } 12 | public: 13 | static SingletonClass& getInstance() { 14 | static SingletonClass instance; 15 | return instance; 16 | } 17 | 18 | SingletonClass(const SingletonClass& other) = delete; 19 | SingletonClass& operator=(const SingletonClass& other) = delete; 20 | 21 | void doStuff() { 22 | std::cout << this << std::endl; 23 | } 24 | }; 25 | 26 | int main() { 27 | { 28 | std::cout << "hello"; 29 | SingletonClass& s1 = SingletonClass::getInstance(); 30 | } 31 | SingletonClass& s2 = SingletonClass::getInstance(); 32 | s2.doStuff(); 33 | SingletonClass& s3 = SingletonClass::getInstance(); 34 | s3.doStuff(); 35 | SingletonClass& s4 = SingletonClass::getInstance(); 36 | } 37 | -------------------------------------------------------------------------------- /Week 15/DesignPatterns/Structural/Composite.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "polymorphic_ptr.hpp" 3 | #include "MyVector.hpp" 4 | 5 | class FileSystemEntity { 6 | public: 7 | virtual size_t getSize() const = 0; 8 | virtual ~FileSystemEntity() = default; 9 | }; 10 | 11 | class File : public FileSystemEntity { 12 | size_t size = 0; 13 | public: 14 | size_t getSize() const { 15 | return size; 16 | } 17 | }; 18 | 19 | class Directory : public FileSystemEntity { 20 | Vector> children; 21 | public: 22 | size_t getSize() const { 23 | size_t size = 0; 24 | for (size_t i = 0; i < children.getSize(); i++) { 25 | size += children[i]->getSize(); 26 | } 27 | 28 | return size; 29 | } 30 | }; 31 | 32 | int main() { 33 | 34 | } 35 | -------------------------------------------------------------------------------- /Week 15/SingletonFactory/data.txt: -------------------------------------------------------------------------------- 1 | 3 2 | 1 2 3 3 | -------------------------------------------------------------------------------- /Week 15/SingletonFactory/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | class Base { 4 | public: 5 | virtual ~Base() = default; 6 | }; 7 | class A : public Base { }; 8 | class B : public Base { }; 9 | 10 | class SingletonFactory { 11 | SingletonFactory() { 12 | std::ifstream in("data.txt"); 13 | if (!in.is_open()) { 14 | throw std::exception("Could not open data.txt"); 15 | } 16 | 17 | in >> numbersSize; 18 | numbers = new size_t[numbersSize]; 19 | size_t index = 0; 20 | while (!in.eof()) { 21 | in >> numbers[index++]; 22 | } 23 | } 24 | 25 | ~SingletonFactory() { 26 | delete[] numbers; 27 | } 28 | 29 | size_t current = 0; 30 | size_t numbersSize = 0; 31 | size_t* numbers = nullptr; 32 | public: 33 | Base* create() { 34 | if (current >= numbersSize) { 35 | return nullptr; 36 | } 37 | 38 | if (numbers[current++] % 2 == 0) { 39 | return new A(); 40 | } 41 | else { 42 | return new B(); 43 | } 44 | } 45 | 46 | static SingletonFactory& getInstance() { 47 | static SingletonFactory instance; 48 | return instance; 49 | } 50 | 51 | SingletonFactory(const SingletonFactory& other) = delete; 52 | SingletonFactory& operator=(const SingletonFactory& other) = delete; 53 | }; 54 | 55 | int main() { 56 | SingletonFactory& sf = SingletonFactory::getInstance(); 57 | 58 | Base* obj = sf.create(); 59 | Base* obj2 = sf.create(); 60 | delete obj; 61 | delete obj2; 62 | } 63 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | ### Код от лекциите по ООП спец. Софтуерно инженерство ### 2 | ### Код от семинарите на спец. Информационни системи и спец. Софтуерно инженерство ### 3 | 4 | - **Тема 01:** Преговор на указатели, референции и динамична памет. Увод в ООП. Енумерации. Структури и обединения. Инстанции и обекти. Представяния в паметта. Работа с функции, които приемат инстанции/обекти. 5 | 6 | - **Тема 02:** Увод в потоците и текстовите файлове. Писане и четене в текстов файл. 7 | 8 | - **Тема 03:** Двоични файлове. Четене и писане в двоичен файл. 9 | - **Тема 04** Член-функции. Жизнен цикъл на обект. Конструктори и деструктор. Капсулация. Модификатори за достъп. Член-функции get и set. 10 | - **Тема 05**: Разделна компилация. Препроцесор. Композиция и агрегация. Копиращ конструктор и оператор= 11 | - **Тема 06**: Динамична памет в класовете. Голямата четворка (Rule of four). 12 | - **Тема 07**: Предефиниране на оператори. Приятелски класове и функции 13 | - **Тема 08**: Ключова дума static. Изключения. 14 | - **Тема 09**: Масиви от указатели към обекти. Move семантики. 15 | - **Тема 10**: Наследяване. 16 | - **Тема 11**: Статично и динамично свързване. Виртуални функции. Полиморфизъм. Абстрактни класове. Ключови думи - override, final. Виртуални таблици. 17 | - **Тема 12**: Колекции от обекти в полиморфна йерархия. Копиране, триене, разпознаване. Visitor pattern. Шаблони. 18 | - **Тема 13**: Множествено наследяване. Виртуално наследяване. Виртуални таблици при множествено и виртуално наследяване. Диамантен проблем. 19 | - **Тема 14:** Дървовидна структура от обекти от полиморфна йерархия. 20 | - **Тема 15:** Тype casting. Въведение в design patterns. Solid принципи. 21 | --------------------------------------------------------------------------------