├── .gitignore ├── Misc └── Tutorials │ └── README.md ├── Practicum ├── Week 01 │ ├── Example │ │ └── main.cpp │ └── README.md ├── Week 02 │ ├── Examples │ │ ├── city_types.cpp │ │ ├── city_types.hpp │ │ ├── main.cpp │ │ ├── smartcity.cpp │ │ └── smartcity.hpp │ └── README.md ├── Week 03 │ └── README.md ├── Week 04 │ ├── Examples │ │ └── tests.cpp │ └── README.md ├── Week 05 │ ├── Examples │ │ ├── main.cpp │ │ ├── test_player.hpp │ │ └── test_weapon.hpp │ └── README.md ├── Week 06 │ ├── Examples │ │ ├── main.cpp │ │ └── test_enemy.hpp │ └── README.md ├── Week 07 │ ├── Examples │ │ ├── main.cpp │ │ ├── test_player_spell.hpp │ │ └── test_spell.hpp │ └── README.md ├── Week 08 │ └── README.md ├── Week 09 │ └── README.md ├── Week 10 │ └── README.md ├── Week 11 │ ├── Examples │ │ └── Demo │ │ │ └── inheritance.cpp │ └── README.md ├── Week 12 │ └── README.md ├── Week 13 │ └── README.md └── Week 14 │ └── README.md ├── README.md └── Seminar ├── Week 01 ├── Data alignment │ ├── dataAlignment.cpp │ ├── moreDataAlignment.cpp │ └── padding.cpp ├── Examples │ ├── Enums.cpp │ ├── Little_endianess_test.cpp │ ├── Namespaces.cpp │ ├── Namespaces_exercise.cpp │ └── Structs.cpp ├── README.md ├── Reviews │ ├── Alina_Blagoeva_7MI0400318 │ │ ├── domashnoZad1.cpp │ │ ├── domashnoZad3.cpp │ │ └── domashnozad2.cpp │ ├── Angel_Filipov_9MI0700313 │ │ ├── Task1.cpp │ │ ├── Task2.cpp │ │ ├── Task3.cpp │ │ └── Task4.cpp │ ├── Antonio_Boyadjiev_8MI0400192 │ │ ├── Task1.cpp │ │ ├── Task2.cpp │ │ ├── Task3.cpp │ │ └── Task4.cpp │ ├── Asparuh_Dinev_2MI0400372 │ │ └── HW.cpp │ ├── Boyan_Sinilkov_1MI0400220 │ │ ├── Zadacha1.txt │ │ ├── Zadacha2.txt │ │ ├── Zadacha3.txt │ │ └── Zadacha4.txt │ ├── Dimitar_Kolev_1MI0400363 │ │ ├── 1.cpp │ │ ├── 2.cpp │ │ ├── 3.cpp │ │ └── 4.cpp │ ├── Evgeni_Darmanchev_1MI8000019 │ │ ├── zad1.cpp │ │ ├── zad2.cpp │ │ └── zad3.cpp │ ├── Georgi_Komerdjanov_3MI0400017 │ │ ├── hw1_task1.cpp │ │ ├── hw1_task2.cpp │ │ ├── hw1_task3.cpp │ │ └── hw1_task4.cpp │ ├── Georgi_Naumov_2MI0400329 │ │ ├── zad1.cpp │ │ ├── zad2.cpp │ │ └── zad3.cpp │ ├── Georgi_Radev_9MI0400247 │ │ ├── prob01.cpp │ │ ├── prob02.cpp │ │ └── prob03.cpp │ ├── Giorgi_Begalinoski_3MI8000065 │ │ ├── Domasno1_zad1.cpp │ │ ├── Domasno1_zad2.cpp │ │ ├── Domasno1_zad3.cpp │ │ └── Domasno1_zad4.cpp │ ├── Hristina_Zehireva_2MI0400242 │ │ ├── areaoftriangles.cpp │ │ ├── complex.cpp │ │ ├── quadratic.cpp │ │ └── student.cpp │ ├── Ivo_Kisiov_5MI0400254 │ │ ├── zad1.cpp │ │ ├── zad2.cpp │ │ ├── zad3.cpp │ │ └── zad4.cpp │ ├── Katrin_Lilova_7MI0400333 │ │ ├── main.cpp │ │ ├── task1.cpp │ │ ├── task1.hpp │ │ ├── task2.cpp │ │ ├── task2.hpp │ │ ├── task3.cpp │ │ ├── task3.hpp │ │ ├── task4.cpp │ │ └── task4.hpp │ ├── Kremena_Dimitrova_3MI0400312 │ │ ├── zad1.cpp │ │ ├── zad2.cpp │ │ ├── zad3.cpp │ │ └── zad4.cpp │ ├── Melisa_Chausheva_4MI0400232 │ │ ├── firstTask.cpp │ │ ├── fourthTask.cpp │ │ ├── secondTask.cpp │ │ └── thirdTask.cpp │ ├── Miumiun_Izmirliev_7MI0400320 │ │ ├── Zad1.cpp │ │ ├── Zad2.cpp │ │ ├── Zad3.cpp │ │ └── Zad4.cpp │ ├── Nick_Raichev_3MI0400004 │ │ ├── HW1.cpp │ │ ├── HW2.cpp │ │ ├── HW3.cpp │ │ └── HW4.cpp │ ├── Nikol_Bonjolova_1MI0400376 │ │ ├── hm1.cpp │ │ ├── hm2.cpp │ │ ├── hm3.cpp │ │ └── hm4.cpp │ ├── Nikolai_Nejkov_9MI0400310 │ │ ├── Task 1 │ │ │ ├── main.cpp │ │ │ ├── triangle.cpp │ │ │ └── triangle.hpp │ │ └── Task 2 │ │ │ └── main.cpp │ ├── Petar_Angelov_5MI0700079 │ │ ├── task1.cpp │ │ ├── task2.cpp │ │ ├── task3.cpp │ │ └── task4.cpp │ ├── Petar_Doinov_6MI0400289 │ │ ├── 6MI0400289_gr1_pr1.cpp │ │ ├── 6MI0400289_gr1_pr2.cpp │ │ ├── 6MI0400289_gr1_pr3.cpp │ │ └── 6MI0400289_gr1_pr4.cpp │ ├── Stoyan_Georgiev_9MI0400349 │ │ ├── zad_1.cpp │ │ ├── zad_2.cpp │ │ ├── zad_3.cpp │ │ └── zad_4.cpp │ ├── Veronika_Nikolova_9MI0400234 │ │ ├── ex1.cpp │ │ ├── ex2.cpp │ │ └── ex3.cpp │ └── Yasen_Rusinov_5MI0400328 │ │ ├── 01.cpp │ │ ├── 02.cpp │ │ └── 03.cpp └── Solutions │ ├── Task1.cpp │ ├── Task2.cpp │ ├── Task3.cpp │ └── Task4.cpp ├── Week 02 ├── Example problems │ ├── Task1.cpp │ ├── Task2.cpp │ ├── Task3.cpp │ └── Task4.cpp ├── Examples for binary files │ ├── array_of_students_read.cpp │ ├── array_of_students_write.cpp │ ├── simple_struct_binary.cpp │ ├── students.csv │ └── students_read_write_binary.cpp ├── README.md ├── Solutions │ ├── Task1.cpp │ ├── Task2.cpp │ ├── myData.dat │ └── students.csv └── fileStreams.md ├── Week 03 ├── Compiler Examples │ ├── compiler_options.bat │ └── main.cpp ├── Dynamic Library Example │ ├── Library │ │ ├── compile_library.bat │ │ ├── test.cpp │ │ └── test.hpp │ ├── compile_executable.bat │ └── main.cpp ├── README.md └── Static Library Example │ ├── Library │ ├── compile_library.bat │ ├── test.cpp │ └── test.hpp │ ├── compile_executable.bat │ └── main.cpp ├── Week 04 ├── Example │ ├── Animal.cpp │ ├── Animal.hpp │ ├── Person.cpp │ ├── Person.hpp │ └── main.cpp ├── README.md ├── Solutions │ ├── Task1.cpp │ └── Task2.cpp ├── Task1_structure.hpp └── Task2_structure.hpp ├── Week 05 ├── Athlete │ ├── Athlete.cpp │ ├── Athlete.hpp │ └── main.cpp └── README.md ├── Week 06 ├── Examples │ ├── MemoryBlock │ │ ├── MemoryBlock.h │ │ └── main.cpp │ ├── MyClass.h │ ├── Person │ │ ├── Person.cpp │ │ ├── Person.hpp │ │ └── test.cpp │ ├── String │ │ ├── String.cpp │ │ ├── String.hpp │ │ └── main.cpp │ ├── lvalues_and_rvalues2.cpp │ ├── main.cpp │ ├── named-reference.cpp │ ├── reference-overload.cpp │ ├── reference_declarator.cpp │ └── rule_of_three_five_zero │ │ ├── rule_of_five.cpp │ │ ├── rule_of_three.cpp │ │ └── rule_of_zero.cpp ├── README.md └── generateRandomNumber.cpp ├── Week 07 ├── Examples │ └── Friends │ │ ├── examples.cpp │ │ └── when_can_and_when_should_friend.cpp └── README.md ├── Week 08 ├── Examples │ ├── ArraySubscriptOperator.md │ ├── AssignmentOperators.md │ ├── Comaprison.md │ ├── Comparison.cpp │ ├── CriteriaExample.cpp │ ├── Examples.cpp │ ├── FunctionCallOperator.cpp │ ├── IncrementAndDecrement.md │ └── StreamExtractionAndInsertion.md ├── README.md ├── Smart Pointers │ ├── shared_ptr.cpp │ ├── shared_ptr.hpp │ ├── unique_ptr.cpp │ └── unique_ptr.hpp └── String │ ├── String.cpp │ ├── String.hpp │ └── main.cpp ├── Week 09 ├── Examples │ ├── Person, Student, Teacher │ │ ├── Person │ │ │ ├── Person.cpp │ │ │ └── Person.hpp │ │ ├── Source.cpp │ │ ├── Student │ │ │ ├── Student.cpp │ │ │ └── Student.hpp │ │ └── Teacher │ │ │ ├── Teacher.cpp │ │ │ └── Teacher.hpp │ └── forwardDeclaration │ │ ├── A.hpp │ │ └── B.hpp └── README.md ├── Week 10 ├── Examples │ ├── passingAsParams.cpp │ ├── polymorphism.cpp │ ├── shape_polymorphism │ │ ├── Circle.cpp │ │ ├── Circle.h │ │ ├── Rectangle.cpp │ │ ├── Rectangle.h │ │ ├── Shape.cpp │ │ ├── Shape.h │ │ ├── Triangle.cpp │ │ ├── Triangle.h │ │ └── main.cpp │ ├── virtual_functions_playground.cpp │ ├── virtual_inheritance_layout.cpp │ └── vtables.cpp └── README.md ├── Week 11 ├── Examples │ ├── Farm │ │ ├── Animals │ │ │ ├── Animal.hpp │ │ │ ├── Cat.cpp │ │ │ ├── Cat.hpp │ │ │ ├── Dog.cpp │ │ │ ├── Dog.hpp │ │ │ ├── Mouse.cpp │ │ │ └── Mouse.hpp │ │ ├── Collection │ │ │ ├── Farm.cpp │ │ │ └── Farm.hpp │ │ ├── Factory │ │ │ ├── Factory.cpp │ │ │ └── Factory.hpp │ │ └── source.cpp │ ├── ShapeCollection │ │ ├── Factory │ │ │ └── Factory.hpp │ │ ├── ShapeCollection │ │ │ ├── ShapeCollection.cpp │ │ │ └── ShapeCollection.hpp │ │ ├── Shapes │ │ │ ├── Circle.cpp │ │ │ ├── Circle.hpp │ │ │ ├── Rectangle.cpp │ │ │ ├── Rectangle.hpp │ │ │ ├── Shape.cpp │ │ │ ├── Shape.hpp │ │ │ ├── Triangle.cpp │ │ │ └── Triangle.hpp │ │ └── main.cpp │ └── Students │ │ ├── Factory │ │ ├── Factory.cpp │ │ └── Factory.hpp │ │ ├── Major │ │ ├── Major.cpp │ │ └── Major.hpp │ │ ├── Student Types │ │ ├── LazyStudent.cpp │ │ ├── LazyStudent.hpp │ │ ├── MotivatedStudent.cpp │ │ ├── MotivatedStudent.hpp │ │ ├── Student.cpp │ │ └── Student.hpp │ │ └── main.cpp └── README.md └── Week 12 └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Compiled Object files 5 | *.slo 6 | *.lo 7 | *.o 8 | *.obj 9 | 10 | # Precompiled Headers 11 | *.gch 12 | *.pch 13 | 14 | # Compiled Dynamic libraries 15 | *.so 16 | *.dylib 17 | *.dll 18 | 19 | # Fortran module files 20 | *.mod 21 | *.smod 22 | 23 | # Compiled Static libraries 24 | *.lai 25 | *.la 26 | *.a 27 | *.lib 28 | 29 | # Executables 30 | *.exe 31 | *.out 32 | *.app 33 | 34 | .vscode 35 | 36 | # Setup 37 | **/file_hashes.txt -------------------------------------------------------------------------------- /Misc/Tutorials/README.md: -------------------------------------------------------------------------------- 1 | # How to debug multiple C++ source files in VSCode 2 | 3 | [Video tutorial](https://www.youtube.com/watch?v=DVyYnOHP4nY) 4 | 5 | ## In short: 6 | 7 | ### :warning: You must put all source files in the same directory for this to work 8 | 9 | ### :one: Launch the debugger from the main file. This will fail, but it will also create a `launch.json` or `tasks.json` file in the `.vscode` directory 10 | 11 | ### :two: Edit the config json file to include all source files: in the `args` section search for a line with something like `"${file}"` and replace it with `"${workspaceFolder}/*.cpp"` or simply `"*.cpp"` 12 | 13 | -------------------------------------------------------------------------------- /Practicum/Week 02/Examples/city_types.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | enum class BuildingType { 5 | UNKNOWN, 6 | RESIDENTIAL, 7 | HOSPITAL, 8 | POLICE, 9 | FIRE_STATION 10 | }; 11 | 12 | enum class EmergencyLevel { 13 | UNKNOWN, 14 | LOW, 15 | MEDIUM, 16 | HIGH 17 | }; 18 | 19 | BuildingType getBuildingTypeFromUser(); 20 | EmergencyLevel getEmergencyLevelFromUser(); -------------------------------------------------------------------------------- /Practicum/Week 02/Examples/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "smartcity.hpp" 3 | 4 | int main() { 5 | Building building; 6 | Event event; 7 | 8 | std::cout << "=== Enter building details ===\n"; 9 | inputBuildingData(building); 10 | 11 | std::cout << "\n=== Building info ===\n"; 12 | printBuildingInfo(building); 13 | 14 | std::cout << "\n=== Enter event details ===\n"; 15 | inputEventData(event); 16 | 17 | std::cout << "\n=== Event info ===\n"; 18 | printEventInfo(event); 19 | 20 | return 0; 21 | } -------------------------------------------------------------------------------- /Practicum/Week 02/Examples/smartcity.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "city_types.hpp" 3 | 4 | struct Location { 5 | int x; 6 | int y; 7 | }; 8 | 9 | struct BuildingStatus { 10 | unsigned int isOperational : 1; // works or not 11 | unsigned int powerStatus : 2; // level of power supply (0-3) 12 | unsigned int occupancy : 2; // level of occupancy (0-3) 13 | }; 14 | 15 | struct Building { 16 | char name[32]; 17 | BuildingType type; 18 | Location loc; 19 | BuildingStatus status; 20 | }; 21 | 22 | struct Event { 23 | EmergencyLevel level; 24 | Location loc; 25 | char description[64]; 26 | }; 27 | 28 | void printBuildingInfo(const Building& b); 29 | void inputBuildingData(Building& b); 30 | void printEventInfo(const Event& e); 31 | void inputEventData(Event& e); 32 | 33 | -------------------------------------------------------------------------------- /Practicum/Week 05/Examples/main.cpp: -------------------------------------------------------------------------------- 1 | #include "test_weapon.hpp" 2 | #include "test_player.hpp" 3 | #include 4 | 5 | // Function to display menu and get choice 6 | int getMenuChoice() { 7 | int choice; 8 | std::cout << "\n=== Elden Ring Class System Tests ===\n" 9 | << "1. Run all tests\n" 10 | << "2. Run Weapon tests\n" 11 | << "3. Run Player basic tests\n" 12 | << "4. Run Player flask tests\n" 13 | << "0. Exit\n" 14 | << "Enter your choice: "; 15 | std::cin >> choice; 16 | return choice; 17 | } 18 | 19 | int main() { 20 | int choice; 21 | bool running = true; 22 | 23 | while (running) { 24 | choice = getMenuChoice(); 25 | 26 | switch (choice) { 27 | case 1: 28 | // Run all tests 29 | WeaponTest::runAllTests(); 30 | std::cout << "\n-----------------------------\n" << std::endl; 31 | PlayerTest::runAllTests(); 32 | break; 33 | case 2: 34 | // Run Weapon tests 35 | WeaponTest::runAllTests(); 36 | break; 37 | case 3: 38 | // Run Player basic tests 39 | PlayerTest::runBasicTests(); 40 | break; 41 | case 4: 42 | // Run Player flask tests 43 | PlayerTest::runFlaskTests(); 44 | break; 45 | case 0: 46 | running = false; 47 | std::cout << "Exiting program...\n"; 48 | break; 49 | default: 50 | std::cout << "Invalid choice! Try again.\n"; 51 | break; 52 | } 53 | } 54 | 55 | return 0; 56 | } -------------------------------------------------------------------------------- /Practicum/Week 05/Examples/test_weapon.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "weapon.hpp" 3 | #include 4 | 5 | namespace WeaponTest { 6 | void runBasicTests() { 7 | // Create and initialize weapons 8 | Weapon longSword; 9 | longSword.initialize("Longsword", 80, 5.0f, 12); 10 | 11 | Weapon club; 12 | club.initialize("Club", 60, 3.5f, 8); 13 | 14 | Weapon dagger; 15 | dagger.initialize("Dagger", 45, 1.5f, 5); 16 | 17 | Weapon greatsword; 18 | greatsword.initialize("Greatsword", 120, 12.0f, 20); 19 | 20 | // Print weapon information 21 | std::cout << "Testing weapon functionality:\n" << std::endl; 22 | 23 | longSword.printInfo(); 24 | std::cout << std::endl; 25 | 26 | club.printInfo(); 27 | std::cout << std::endl; 28 | 29 | dagger.printInfo(); 30 | std::cout << std::endl; 31 | 32 | greatsword.printInfo(); 33 | } 34 | 35 | void runValidationTests() { 36 | // Test validation 37 | std::cout << "\nTesting validation with invalid values:" << std::endl; 38 | 39 | Weapon invalidWeapon; 40 | invalidWeapon.initialize("Invalid Weapon", -10, -2.0f, -5); 41 | invalidWeapon.printInfo(); 42 | 43 | // Test long name 44 | std::cout << "\nTesting long name truncation:" << std::endl; 45 | 46 | Weapon longNameWeapon; 47 | longNameWeapon.initialize("This is an extremely long weapon name that should be truncated", 50, 5.0f, 10); 48 | longNameWeapon.printInfo(); 49 | } 50 | 51 | void runAllTests() { 52 | std::cout << "=== Running Weapon Tests ===\n" << std::endl; 53 | runBasicTests(); 54 | runValidationTests(); 55 | std::cout << "\n=== Weapon Tests Completed ===\n" << std::endl; 56 | } 57 | } -------------------------------------------------------------------------------- /Practicum/Week 11/Examples/Demo/inheritance.cpp: -------------------------------------------------------------------------------- 1 | // source: https://leimao.github.io/blog/CPP-Virtual-Table/ 2 | class Drug 3 | { 4 | public: 5 | Drug(int property) : m_property{property} {}; 6 | virtual ~Drug() = default; 7 | virtual void foo() = 0; 8 | virtual void baz() = 0; 9 | int m_property; 10 | }; 11 | 12 | class Fruit 13 | { 14 | public: 15 | Fruit(double size, int id, char country) 16 | : m_size{size}, m_id{id}, m_country{country} {}; 17 | virtual ~Fruit() = default; 18 | virtual void foo() = 0; 19 | virtual void bar(){}; 20 | double m_size; 21 | int m_id; 22 | char m_country; 23 | }; 24 | 25 | class Apple : public Fruit 26 | { 27 | public: 28 | Apple(double size, int id, char country, int color) 29 | : Fruit{size, id, country}, m_color{color} {}; 30 | ~Apple() = default; 31 | void foo() override {} 32 | void get_color() const {} 33 | virtual void apple_foo() {} 34 | int m_color; 35 | }; 36 | 37 | class Orange : public Fruit, public Drug 38 | { 39 | public: 40 | Orange(double size, int id, char country, double weight) 41 | : Fruit{size, id, country}, Drug{4}, m_weight{weight} {}; 42 | ~Orange() = default; 43 | // Overriding Fruit virtual functions. 44 | void foo() override {} 45 | void bar() override {} 46 | // Overriding Drug virtual functions. 47 | void baz() override {} 48 | // Orange non-virtual functions. 49 | void get_weight() const {} 50 | // Orange virtual functions. 51 | virtual void orange_bar() {} 52 | double m_weight; 53 | }; 54 | 55 | int main() 56 | { 57 | double const apple_size{1.0}; 58 | int const apple_id{1}; 59 | char const apple_country{'c'}; 60 | int const apple_color{2}; 61 | double const orange_size{0.8}; 62 | int const orange_id{2}; 63 | char const orange_country{'n'}; 64 | double const orange_weight{0.6}; 65 | Apple apple{apple_size, apple_id, apple_country, apple_color}; 66 | Orange orange{orange_size, orange_id, orange_country, orange_weight}; 67 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Data alignment/dataAlignment.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // Alignment requirements 4 | // (typical 32 bit machine) 5 | 6 | // char 1 byte 7 | // short int 2 bytes 8 | // int 4 bytes 9 | // double 8 bytes 10 | 11 | // structure A 12 | struct structA 13 | { 14 | char c; 15 | short int s; 16 | }; 17 | 18 | // structure B 19 | struct structB 20 | { 21 | short int s; 22 | char c; 23 | int i; 24 | }; 25 | 26 | // structure C 27 | struct structC 28 | { 29 | char c; 30 | double d; 31 | int s; 32 | }; 33 | 34 | // structure D 35 | struct structD 36 | { 37 | double d; 38 | int s; 39 | char c; 40 | }; 41 | 42 | struct A 43 | { 44 | int i; 45 | char c; 46 | double d; 47 | }; 48 | 49 | int main() 50 | { 51 | std::cout << "Size of structA " << sizeof(structA) << std::endl; 52 | std::cout << "Size of structB " << sizeof(structB) << std::endl; 53 | std::cout << "Size of structC " << sizeof(structC) << std::endl; 54 | std::cout << "Size of structD " << sizeof(structD) << std::endl; 55 | 56 | long A = 100.69; 57 | std::cout << "Size of A (struct) " << sizeof(struct A) << std::endl; 58 | std::cout << "Size of A (variable) " << sizeof(A) << std::endl; 59 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Data alignment/padding.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | // Disable padding 8 | #pragma pack(push, 1) 9 | struct no_padding{ 10 | 11 | int16_t a = 1; 12 | int32_t b = 2; 13 | int16_t c = 3; 14 | 15 | }/*__attribute__((packed))*/; // Another way to disable 16 | #pragma pack(pop) 17 | 18 | struct with_padding{ 19 | 20 | int16_t a; 21 | int32_t b; 22 | int16_t c; 23 | 24 | }; 25 | 26 | int main(){ 27 | 28 | std::cout << sizeof(no_padding) << '\n'; 29 | std::cout << sizeof(with_padding) << '\n'; 30 | 31 | std::size_t const SIZE = 100'000; 32 | 33 | { 34 | 35 | auto start = std::chrono::steady_clock::now(); 36 | 37 | with_padding array[SIZE]; 38 | for(std::size_t i = 0; i < SIZE; ++i){ 39 | 40 | array[i].a = 1; 41 | array[i].b = 2; 42 | array[i].c = 3; 43 | 44 | } 45 | 46 | auto end = std::chrono::steady_clock::now(); 47 | auto diffGlobal = end - start; 48 | 49 | std::cout << '\n' << std::string(23, '=') << "\nCode ran for: " << std::chrono::duration>(diffGlobal).count() << "s\n"; 50 | 51 | } 52 | 53 | { 54 | 55 | auto start = std::chrono::steady_clock::now(); 56 | 57 | no_padding array[SIZE]; 58 | for(std::size_t i = 0; i < SIZE; ++i){ 59 | 60 | array[i].a = 1; 61 | array[i].b = 2; 62 | array[i].c = 3; 63 | 64 | } 65 | 66 | auto end = std::chrono::steady_clock::now(); 67 | auto diffGlobal = end - start; 68 | 69 | std::cout << '\n' << std::string(23, '=') << "\nCode ran for: " << std::chrono::duration>(diffGlobal).count() << "s\n"; 70 | 71 | } 72 | 73 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Examples/Enums.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 | // examples of bad use of plain enums: 11 | Color color = Color::red; 12 | Card card = Card::green_card; 13 | 14 | int num = color; // no problem 15 | 16 | if (color == Card::red_card) // no problem (bad) 17 | std::cout << "bad\n"; 18 | 19 | if (card == Color::green) // no problem (bad) 20 | std::cout << "bad\n"; 21 | 22 | // examples of good use of enum classes (safe) 23 | Animal a = Animal::deer; 24 | Mammal m = Mammal::deer; 25 | 26 | int num2 = a; // error 27 | if (m == a) // error (good) 28 | std::cout << "bad\n"; 29 | 30 | if (a == Mammal::deer) // error (good) 31 | std::cout << "bad\n"; 32 | 33 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Examples/Little_endianess_test.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | bool isLittleEndian(){ 4 | 5 | union{ // Anonymous union 6 | uint32_t n = 1; // 1 * 4bytes 7 | unsigned char bytes[4]; // 4 * 1bytes 8 | }myTest; // Variable 9 | 10 | // If little endian n -> 0x01000000 11 | // If big endian n -> 0x00000001 12 | 13 | // Check the first byte 14 | return myTest.bytes[0]; 15 | 16 | } 17 | 18 | int main(){ 19 | 20 | std::cout << isLittleEndian() << '\n'; 21 | 22 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Examples/Namespaces.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | 5 | namespace mine{ 6 | 7 | template 8 | class vector{}; 9 | 10 | } 11 | 12 | using namespace std; 13 | using namespace mine; 14 | 15 | namespace A 16 | { 17 | int i; 18 | } 19 | 20 | namespace B 21 | { 22 | int i; 23 | int j; 24 | 25 | namespace C 26 | { 27 | namespace D 28 | { 29 | using namespace A; // all names from A injected into global namespace 30 | 31 | int j; 32 | int k; 33 | int a = i; // i is B::i, because A::i is hidden by B::i 34 | } 35 | 36 | using namespace D; // names from D are injected into C 37 | // names from A are injected into global namespace 38 | 39 | int k = 89; // OK to declare name identical to one introduced by a using 40 | int l = k; // ambiguous: C::k or D::k 41 | int m = i; // ok: B::i hides A::i 42 | int n = j; // ok: D::j hides B::j 43 | } 44 | } 45 | 46 | namespace Q 47 | { 48 | namespace V // V is a member of Q, and is fully defined within Q 49 | { // namespace Q::V // C++17 alternative to the lines above 50 | class C // C is a member of V and is fully defined within V 51 | { 52 | void m(); // C::m is only declared 53 | }; 54 | void f(); // f is a member of V, but is only declared here 55 | } 56 | 57 | void V::C::m() // definition of V::C::m outside of the namespace (and the class body) 58 | {} // enclosing namespaces are the global namespace, Q, and Q::V 59 | } 60 | 61 | int main(){ 62 | 63 | vector vec; // Ambiguous because we don't know which one we want to address. 64 | 65 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Examples/Structs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | 5 | struct Rational{ 6 | 7 | int nom; 8 | int denom; 9 | 10 | }; 11 | 12 | bool isValid(Rational const &rat){ 13 | return rat.denom != 0; 14 | } 15 | 16 | void printRational(Rational const &rat){ 17 | std::cout << rat.nom << " / " << rat.denom << '\n'; 18 | } 19 | 20 | unsigned getGcd(unsigned a, unsigned b){ 21 | 22 | if(a < b) std::swap(a, b); 23 | 24 | while(b != 0){ 25 | 26 | int remainder = a % b; 27 | a = b; 28 | b = remainder; 29 | 30 | } 31 | 32 | return a; 33 | 34 | } 35 | 36 | void rationalize(Rational &rat){ 37 | 38 | assert(isValid(rat)); 39 | 40 | unsigned gcd = getGcd((unsigned int)rat.nom, (unsigned int)rat.denom); 41 | 42 | rat.nom /= gcd; 43 | rat.denom /= gcd; 44 | 45 | } 46 | 47 | Rational &plusEq(Rational &lhs, Rational const &rhs){ 48 | 49 | assert(isValid(lhs) && isValid(rhs)); 50 | 51 | lhs.nom *= rhs.denom; 52 | lhs.nom += rhs.nom*lhs.denom; 53 | lhs.denom *= rhs.denom; 54 | 55 | rationalize(lhs); 56 | 57 | return lhs; 58 | 59 | } 60 | 61 | Rational plusRationals(Rational const &lhs, Rational const &rhs){ 62 | 63 | assert(isValid(lhs) && isValid(rhs)); 64 | 65 | Rational lhsCopy = lhs; 66 | plusEq(lhsCopy, rhs); 67 | 68 | return lhsCopy; 69 | 70 | } 71 | 72 | int main(){ 73 | 74 | Rational r1{1,4}; 75 | Rational r2{1,3}; 76 | 77 | Rational r3 = plusRationals(r1, r2); 78 | 79 | printRational(r3); 80 | 81 | plusEq(r3, r1); 82 | 83 | printRational(r3); 84 | 85 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Alina_Blagoeva_7MI0400318/domashnoZad3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct ComplexNumber { 4 | int a; 5 | int b; 6 | }; 7 | 8 | ComplexNumber addComplex(ComplexNumber num1,ComplexNumber num2) { 9 | int realPart = num1.a + num2.a; 10 | int imaginaryPart = num1.b + num2.b; 11 | 12 | return ComplexNumber{ realPart, imaginaryPart }; 13 | } 14 | 15 | ComplexNumber subtractComplex(ComplexNumber num1, ComplexNumber num2) { 16 | int realPart = num1.a - num2.a; 17 | int imaginaryPart = num1.b - num2.b; 18 | 19 | return ComplexNumber{ realPart, imaginaryPart }; 20 | } 21 | 22 | 23 | ComplexNumber multiplyComplex(ComplexNumber num1, ComplexNumber num2) { 24 | int a = num1.a, b = num1.b; 25 | int c = num2.a, d = num2.b; 26 | 27 | int realPart = a*c - b*d; 28 | int imaginaryPart = a*d + b*c; 29 | 30 | return ComplexNumber{ realPart, imaginaryPart }; 31 | } 32 | 33 | 34 | void printComplex(ComplexNumber num) { 35 | int a = num.a, b = num.b; 36 | 37 | 38 | if (b > 0 && a != 0) { 39 | std::cout << num.a << "+" << num.b << "i" << std::endl; 40 | } 41 | else if (b < 0 && a != 0) { 42 | std::cout << num.a << num.b << "i" << std::endl; 43 | } 44 | else if (b == 0 && a != 0) { 45 | std::cout << num.a << std::endl; 46 | } 47 | else if (b != 0 && a == 0) { 48 | std::cout << num.b << "i" << std::endl; 49 | } 50 | else { 51 | std::cout << num.a << "+" << num.b << "i" << std::endl; 52 | } 53 | } 54 | 55 | //to do create input function for complex numbers 56 | int main() 57 | { 58 | ComplexNumber num1 = {6, -4 }; 59 | ComplexNumber num2 = { 10, 7 }; 60 | 61 | printComplex(addComplex(num1,num2)); 62 | printComplex(subtractComplex(num1, num2)); 63 | printComplex(multiplyComplex(ComplexNumber{0,0},num2)); 64 | 65 | } 66 | -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Alina_Blagoeva_7MI0400318/domashnozad2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // Бих предпочел коефициентите да са double(реални числа), както е по условие. 4 | struct QuadraticEquation { 5 | int a; 6 | int b; 7 | int c; 8 | }; 9 | 10 | void readEquation(QuadraticEquation &equation) { 11 | int a, b, c; 12 | 13 | //TO DO: validation of the input 14 | std::cout << "enter a b c for quadratic equation\n-100 <= a, b, c <= 100\na = " << std::endl; 15 | std::cin >> a; 16 | std::cout << "b = " << std::endl; 17 | std::cin >> b; 18 | std::cout << "c = " << std::endl; 19 | std::cin >> c; 20 | 21 | equation.a = a; 22 | equation.b = b; 23 | equation.c= c; 24 | } 25 | 26 | void findSolutions(const QuadraticEquation &equation) { 27 | int a = equation.a, b = equation.b, c = equation.c; 28 | 29 | // Нямаш cmath! 30 | double d = sqrt(b*b - 4*a*c); 31 | 32 | if (d > 0) { 33 | double x1 = (-b + d) / (2 * a); 34 | double x2 = (-b - d) / (2 * a); 35 | 36 | //to do: format the output better 37 | std::cout << "x1 = " << x1 << " x2 = " << x2 << std::endl; 38 | } 39 | else if (d == 0) { 40 | double x1 = (- b)/(2*a); 41 | std::cout << "x1 = x2 = " << x1 << std::endl; 42 | } 43 | else { 44 | std::cout << "The equation does not have real solutions!" << std::endl; 45 | } 46 | 47 | } 48 | 49 | 50 | int main() 51 | { 52 | QuadraticEquation test; 53 | 54 | readEquation(test); 55 | findSolutions(test); 56 | } 57 | 58 | -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Angel_Filipov_9MI0700313/Task2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | // Тази библиотека ви е строго забранено да я ползвате, 3 | // освен ако не е казано изрично, че можете. 4 | #include 5 | // Тази библиотека няма да ви е разрешена освен, ако не е опоменато. 6 | // За базови сортиращи алгоритми трябва да сте говорили по УП. 7 | #include //sort 8 | #include //setprecision 9 | // Липсва cmath библиотеката! 10 | 11 | // Задача 2 12 | struct QuadraticEquation { 13 | double a, b, c; 14 | 15 | // Отново, методи не са учени, но е добре написано. 16 | // Това го казвам, защото при контролните най-вече не е добре да се използва материал, който не е учен, 17 | // защото предизвиква съмнения за преписване и също така започва разпитване от преподавателите. 18 | // Така че се придържаме към това, което е учено до момента! 19 | void solve() const { 20 | double D = b * b - 4 * a * c; 21 | if (D > 0) 22 | { 23 | double x1 = (-b - std::sqrt(D)) / (2 * a); 24 | double x2 = (-b - std::sqrt(D)) / (2 * a); 25 | if (x1 > x2) 26 | { 27 | std::swap(x1, x2); 28 | } 29 | std::cout << "x1 = " << x1 << ", x2 = " << x2 << std::endl; 30 | 31 | } 32 | else if (D == 0) 33 | { 34 | double x = -b / (2 * a); 35 | std::cout << "x1 = x2 = " << std::fixed << std::setprecision(6) << x << std::endl; 36 | } 37 | else if(D < 0) 38 | { 39 | std::cout << "The equation does not have real solutions!" << std::endl; 40 | } 41 | } 42 | }; 43 | 44 | int main() 45 | { 46 | QuadraticEquation eq; 47 | std::cin >> eq.a >> eq.b >> eq.c; 48 | eq.solve(); 49 | return 0; 50 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Angel_Filipov_9MI0700313/Task3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | // Тази библиотека ви е строго забранено да я ползвате, 3 | // освен ако не е казано изрично, че можете. 4 | #include 5 | // Тази библиотека няма да ви е разрешена освен, ако не е опоменато. 6 | // За базови сортиращи алгоритми трябва да сте говорили по УП. 7 | #include //sort 8 | #include //setprecision 9 | // Липсва cmath библиотеката! 10 | 11 | //Задача 3 12 | struct Complex { 13 | int real, im; 14 | 15 | //За operator+ съм използвал помощта на chatGPT и другите два ги направих като горния с променен знак. 16 | // Отново наблягам на това, че е добре написано, но материалът не е взиман и е хубаво да се въздържаме от такива неща. 17 | Complex operator+(const Complex& other) const { 18 | return { real + other.real, im + other.im }; 19 | } 20 | 21 | Complex operator-(const Complex& other) const { 22 | return { real - other.real, im - other.im }; 23 | } 24 | 25 | Complex operator*(const Complex& other) const { 26 | return { 27 | real * other.real - im * other.im, 28 | real * other.im + im * other.real 29 | }; 30 | } 31 | 32 | void print() const { 33 | if (im == 0) { 34 | std::cout << real << std::endl; 35 | } 36 | 37 | else if (im > 0) { 38 | std::cout << real << "+" << im << "i" << std::endl; 39 | } 40 | else { 41 | // Този print е тотално грешен. 42 | std::cout << real << im << "i" << std::endl; 43 | } 44 | } 45 | }; 46 | 47 | int main() { 48 | int a, b, c, d; 49 | std::cin >> a >> b >> c >> d; 50 | 51 | Complex z1 = { a, b }; 52 | Complex z2 = { c, d }; 53 | 54 | (z1 + z2).print(); 55 | (z1 - z2).print(); 56 | (z1 * z2).print(); 57 | 58 | return 0; 59 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Antonio_Boyadjiev_8MI0400192/Task2.cpp: -------------------------------------------------------------------------------- 1 | // Идеално разписана задача 2 | #include 3 | #include 4 | /* 5 | ������ 2: ������������ ���������, ����� �������� ��������� ���������. ����������� ��������� �� �������� � 3 ����������� a, b, c, 6 | ����� �� ���������� ������ �����. �������� ������ �� ���������� �� ��������� ��� ��� ������ ������. 7 | 8 | Input Format 9 | �� ������� ��� �� �������� 3 ������ ����� a, b � c. 10 | 11 | Constraints 12 | -100 <= a, b, c <= 100 13 | Output Format 14 | �� ���� ��� �� ������������ �����, �� �� ������ ���� �� �������� ��� ����, � ���������� �� ��������� �� ����������� ���������: - 15 | ���� ������ -> "The equation does not have real solutions!" - ��� 2 ������� ������ -> x1 = x2 = "{�����}" - ��� 2 �������� ������ -> x1 = "{����� 1}" 16 | , x2 = "{����� 2}" � ���������� ������ ���� x1 < x2. 17 | 18 | Sample Input 0 19 | 1 -3 2 20 | Sample Output 0 21 | x1 = 1, x2 = 2 22 | Explanation 0 23 | ��� ����� ����������� ���������� x^2-3x+2=0 � ���������� �������� 1 � 2. 24 | 25 | Sample Input 1 26 | -60 -3 -59 27 | Sample Output 1 28 | The equation does not have real solutions! 29 | 30 | Sample Input 2 31 | 1 4 4 32 | Sample Output 2 33 | x1 = x2 = -2 34 | */ 35 | 36 | struct Equation 37 | { 38 | double x, y, z; 39 | 40 | void solve()const { 41 | if (x == 0) { 42 | std::cout << "Equation does not have real solutions!" << std::endl; 43 | return; 44 | } 45 | double discriminant = (pow(y, 2) - 4*x*z); 46 | if (discriminant < 0) { 47 | std::cout << "The equation does not have real solutions!" << std::endl; 48 | return; 49 | } 50 | else if (discriminant == 0) { 51 | int result = (- y + sqrt(discriminant)) / 2 * x; 52 | std::cout << "The equation has two identical roots -> x1 = x2 = {" << result << "}" << std::endl; 53 | return; 54 | } 55 | else { 56 | int x1 = (- y - sqrt(discriminant)) / 2 * x; 57 | int x2 = (- y + sqrt(discriminant)) / 2 * x; 58 | std::cout << "The equation has two roots -> x1 = {" << x1 << "} and x2 = {" << x2 << "}" << std::endl; 59 | return; 60 | } 61 | } 62 | 63 | }; 64 | 65 | int main() { 66 | Equation eq; 67 | std::cin >> eq.x >> eq.y >> eq.z; 68 | eq.solve(); 69 | 70 | return 0; 71 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Boyan_Sinilkov_1MI0400220/Zadacha2.txt: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | const double MIN_NUMBER_VALUE = -100; 5 | const double MAX_NUMBER_VALUE = 100; 6 | 7 | struct QuadraticEq { 8 | double a, b, c; 9 | 10 | void solve() { 11 | if (a == 0) { //тогава не е квадратно. 12 | std::cout << "The equation does not have real solutions!" << std::endl; 13 | return; 14 | } 15 | 16 | double D = b * b - 4 * a * c; 17 | 18 | if (D < 0) { 19 | std::cout << "The equation does not have real solutions!" << std::endl; 20 | } 21 | else if (D == 0) { 22 | double x = (-1 * b) / (2 * a); 23 | std::cout << "x1 = x2 = " << x << std::endl; 24 | } 25 | else { 26 | double x1 = (-1 * b - std::sqrt(D)) / (2 * a); 27 | double x2 = (-1 * b + std::sqrt(D)) / (2 * a); 28 | if (x1 > x2) { 29 | double temp = x1; 30 | x1 = x2; 31 | x2 = temp; 32 | } 33 | std::cout << "x1 = " << x1 << ", x2 = " << x2 << std::endl; 34 | } 35 | } 36 | }; 37 | 38 | bool isValid(double n) { 39 | return n >= MIN_NUMBER_VALUE && n <= MAX_NUMBER_VALUE; 40 | } 41 | 42 | double getValidNum() { 43 | double n; 44 | do { 45 | std::cin >> n; 46 | if (!isValid(n)) { 47 | std::cout << "Bad numbers. Min: " << MIN_NUMBER_VALUE << " Max: " << MAX_NUMBER_VALUE << std::endl; 48 | } 49 | } while (!isValid(n)); 50 | return n; 51 | } 52 | 53 | int main() { 54 | QuadraticEq equation; 55 | 56 | equation.a = getValidNum(); 57 | equation.b = getValidNum(); 58 | equation.c = getValidNum(); 59 | 60 | equation.solve(); 61 | return 0; 62 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Boyan_Sinilkov_1MI0400220/Zadacha3.txt: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | const int MIN_NUMBER_VALUE = -1000; 4 | const int MAX_NUMBER_VALUE = 1000; 5 | 6 | struct ComplexNum { 7 | double Re, Im; 8 | 9 | ComplexNum add(const ComplexNum& other) const { 10 | return { Re + other.Re, Im + other.Im }; 11 | } 12 | 13 | ComplexNum subtract(const ComplexNum& other) const { 14 | return { Re - other.Re, Im - other.Im }; 15 | } 16 | 17 | ComplexNum multiply(const ComplexNum& other) const { 18 | return { Re * other.Re - Im * other.Im, Re * other.Im + Im * other.Re }; 19 | } 20 | }; 21 | 22 | void printComplexNum(const ComplexNum& num) { 23 | if (num.Im == 0) { 24 | std::cout << num.Re << std::endl; 25 | } 26 | else if (num.Re == 0) { 27 | std::cout << num.Im << "i" << std::endl; 28 | } 29 | else { 30 | std::cout << num.Re; 31 | if (num.Im > 0) std::cout << "+"; 32 | std::cout << num.Im << "i" << std::endl; 33 | } 34 | } 35 | 36 | bool isValid(double n) { 37 | return n >= MIN_NUMBER_VALUE && n <= MAX_NUMBER_VALUE; 38 | } 39 | 40 | double getValidNum() { 41 | double n; 42 | do { 43 | std::cin >> n; 44 | if (!isValid(n)) { 45 | std::cout << "Bad numbers. Min: " << MIN_NUMBER_VALUE << " Max: " << MAX_NUMBER_VALUE << std::endl; 46 | } 47 | } while (!isValid(n)); 48 | return n; 49 | } 50 | 51 | int main() { 52 | ComplexNum z1, z2; 53 | 54 | z1.Re = getValidNum(); 55 | z1.Im = getValidNum(); 56 | z2.Re = getValidNum(); 57 | z2.Im = getValidNum(); 58 | 59 | printComplexNum(z1.add(z2)); 60 | printComplexNum(z1.subtract(z2)); 61 | printComplexNum(z1.multiply(z2)); 62 | 63 | return 0; 64 | } 65 | -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Dimitar_Kolev_1MI0400363/1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | // Размерът е хубаво да бъде unsigned число(за предпочитане size_t). 5 | int n; 6 | std::cin >> n; 7 | 8 | // Нямаш валидация за n!!! Какво става, ако въведа отрицателна стойност или 0? 9 | 10 | // Нямаш std::nothrow за new, това е възможно да crash-не програмата, което е проблем. 11 | // Това се счита за сериозна грешки и се таксува тежко на контролни и изпит. 12 | int *a = new int[n]; 13 | for(int i = 0; i < n; i++) { 14 | // Къде е структурата, която се изискваше да направите по условие? 15 | // Това не би се зачело като решение на контролно/изпит, че даже и на проект. 16 | // Този курс се учим да пишем правилно структуриран код, а не такъв, който просто "работи"! 17 | int x1, y1, x2, y2, x3, y3; 18 | std::cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3; 19 | a[i] = abs(x1*(y2-y3) + x2*(y3-y1) + x3*(y1-y2)); 20 | } 21 | 22 | for(int i = 1; i < n; i++) 23 | for(int j = i; j > 0 && a[j-1] > a[j]; j--) 24 | std::swap(a[j-1], a[j]); 25 | 26 | for(int i = 0; i < n; i++) 27 | std::cout << a[i]/2.0 << " "; 28 | std::cout << std::endl; 29 | 30 | // Не освобождаваш заделената памет за a!!!!!!! 31 | // При две такива допуснати на контролно/изпит работата директно се анулира. 32 | 33 | return 0; 34 | } 35 | 36 | -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Dimitar_Kolev_1MI0400363/2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct QuadPoly { 5 | float a, b, c; 6 | 7 | // tuple е stl-ска структура, която е забранена за употреба освен, ако не е упоменато в условието изрично, че можете. 8 | std::tuple solve() { 9 | // Използвай само английски символи в кода си, защото някои компилатори не разчитат други и е възможно човекът, 10 | // който ти проверява работата на контролно/изпит да не му тръгне и да ти ореже точките. 11 | float Δ = b*b - 4*a*c; 12 | 13 | if(Δ < 0) return std::make_tuple(NAN, NAN); 14 | if(Δ == 0) return std::make_tuple(-b/(2*a), NAN); 15 | 16 | float x1 = (-b + sqrt(Δ))/(2*a); 17 | float x2 = (-b - sqrt(Δ))/(2*a); 18 | if(x1 > x2) std::swap(x1, x2); 19 | return std::make_tuple(x1, x2); 20 | } 21 | }; 22 | 23 | // Това е материал, който предстои да вземем, така че се въздържаме от употребата му, докато не стигнем до там. 24 | std::istream &operator>>(std::istream &is, QuadPoly &p) { 25 | is >> p.a >> p.b >> p.c; 26 | return is; 27 | } 28 | 29 | int main() { 30 | QuadPoly p; 31 | std::cin >> p; 32 | 33 | float x1, x2; 34 | // Това преобразуване между типове също не би се харесало на никой от екипа! 35 | std::tie(x1, x2) = p.solve(); 36 | 37 | if(std::isnan(x1)) std::cout << "The equation does not have real solutions!" << std::endl; 38 | else if(std::isnan(x2)) std::cout << "x1 = x2 = " << x1 << std::endl; 39 | else std::cout << "x1 = " << x1 << ", x2 = " << x2 << std::endl; 40 | 41 | return 0; 42 | } 43 | 44 | -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Dimitar_Kolev_1MI0400363/3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct Complex { 4 | int a, b; 5 | 6 | // Отново за оператори е предвидено да се говори, така че до тогава гледаме да не ги ползваме. 7 | Complex operator+(Complex const &n) { 8 | return { a + n.a, b + n.b }; 9 | } 10 | 11 | Complex operator-(Complex const &n) { 12 | return { a - n.a, b - n.b }; 13 | } 14 | 15 | Complex operator*(Complex const &n) { 16 | return { a*n.a - b*n.b, a*n.b + b*n.a }; 17 | } 18 | }; 19 | 20 | std::istream &operator>>(std::istream &is, Complex &n) { 21 | is >> n.a >> n.b; 22 | return is; 23 | } 24 | 25 | std::ostream &operator<<(std::ostream &os, const Complex &n) { 26 | if(n.a != 0) os << n.a; 27 | if(n.b != 0) os << std::showpos << n.b << "i" << std::noshowpos; 28 | if(n.a == 0 && n.b == 0) os << 0; 29 | return os; 30 | } 31 | 32 | int main() { 33 | Complex x, y; 34 | std::cin >> x >> y; 35 | std::cout 36 | << x + y << std::endl 37 | << x - y << std::endl 38 | << x * y << std::endl; 39 | 40 | return 0; 41 | } 42 | 43 | -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Dimitar_Kolev_1MI0400363/4.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct Student { 4 | int fn; 5 | int course; 6 | float grade; 7 | }; 8 | 9 | std::istream &operator>>(std::istream &is, Student &o) { 10 | is >> o.fn >> o.course >> o.grade; 11 | return is; 12 | } 13 | 14 | std::ostream &operator<<(std::ostream &os, const Student &o) { 15 | os 16 | << "FN: " << o.fn << std::endl 17 | << "COURSE: " << o.course << std::endl 18 | << "GRADE: " << o.grade; 19 | return os; 20 | } 21 | 22 | struct Group { 23 | Student *students; 24 | int n; 25 | float grade; 26 | 27 | int stipend(float m) { 28 | int x = 0; 29 | for(int i = 0; i < n; i++) 30 | x += students[i].grade > m; 31 | return x; 32 | } 33 | }; 34 | 35 | int main() { 36 | int n; 37 | std::cin >> n; 38 | 39 | // Липсва валидация на n! 40 | // Не се подсигуряваме за коректен размер. 41 | 42 | // Липсва std::nothrow при заделянето на масив, което може да предизвика crash. 43 | // Другият вариант е да се обработи потенциалната грешка, но трябва да стигнем до там като материал. 44 | Group group = { new Student[n], n, 0 }; 45 | for(int i = 0; i < n; i++) { 46 | std::cin >> group.students[i]; 47 | group.grade += group.students[i].grade; 48 | } 49 | group.grade /= n; 50 | 51 | float m; 52 | std::cin >> m; 53 | 54 | std::cout << group.grade << " " << group.stipend(m) << std::endl; 55 | 56 | // Паметта, която си заделил не е освободена!!! 57 | // Това се счита отново за груба грешка и при две такива на контролно или изпит работата се анулира. 58 | 59 | return 0; 60 | } 61 | 62 | -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Evgeni_Darmanchev_1MI8000019/zad1.cpp: -------------------------------------------------------------------------------- 1 | // Като изключим забележките съм много доволен как е написана задачата. 2 | #include 3 | #include 4 | // Тази библиотека ви е забранена за използване, освен ако не е казано противно в условието. 5 | #include 6 | #include 7 | 8 | // Структурата е добре написана, но нека не избързваме с материала. 9 | // Модификатори за достъп, конструктори и методи ще учим нататък в курса. 10 | // Желателно е да се придържаш към материала, който сме взели особено на контролно/изпит, 11 | // защото иначе ще започнат едни неудобни въпроси от наша страна. 12 | struct Triangle 13 | { 14 | private: 15 | int x1, y1, x2, y2, x3, y3; 16 | 17 | public: 18 | Triangle(int x1, int y1, int x2, int y2, int x3, int y3) { 19 | this->x1 = x1; 20 | this->y1 = y1; 21 | this->x2 = x2; 22 | this->y2 = y2; 23 | this->x3 = x3; 24 | this->y3 = y3; 25 | } 26 | 27 | double area() { 28 | return std::abs(x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0; 29 | } 30 | 31 | 32 | }; 33 | 34 | 35 | int main() { 36 | 37 | unsigned n; 38 | std::cin >> n; 39 | 40 | if (n < 1 || n > 1000) return -1; 41 | 42 | // В условието се изискваше да се сортират триъгълници, а не просто лица. 43 | // Това е същото като да ти дам за задача да сортираш шишета на рафт спрямо височината им и ти се върнеш с един лист, 44 | // на който си написал височините в сортиран ред. Реално заобикаляш проблема. 45 | // За такива уточнения на контролно и изпит е напълно възможно да ти се анулира задачата, защото не е по условието. 46 | double* areasPtr = new(std::nothrow) double[n]; 47 | 48 | if (!areasPtr) { 49 | std::cout << "Allocation problem" << std::endl; 50 | return -1; 51 | } 52 | 53 | for (unsigned i = 0; i < n; i++) { 54 | int x1, y1, x2, y2, x3, y3; 55 | std::cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3; 56 | Triangle triangle(x1, y1, x2, y2, x3, y3); 57 | areasPtr[i] = triangle.area(); 58 | } 59 | 60 | std::sort(areasPtr, areasPtr + n); 61 | 62 | for (unsigned i = 0; i < n; i++) { 63 | std::cout << areasPtr[i] << " "; 64 | 65 | } 66 | 67 | delete[] areasPtr; 68 | 69 | return 0; 70 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Evgeni_Darmanchev_1MI8000019/zad2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | 5 | struct QuadraticEquation { 6 | double a, b, c; 7 | 8 | // Същата забележка както 1ва задача. Придържай се към материала! 9 | void solve() { 10 | 11 | double discriminant = b * b - 4 * a * c; 12 | 13 | if (discriminant < 0) { 14 | std::cout << "The equation does not have real solutions!"; 15 | return; 16 | } 17 | else if (discriminant == 0) { 18 | double root = -b / (2 * a); 19 | std::cout << "x1 = x2 = " << root; 20 | return; 21 | } 22 | else { 23 | double sqrtDisc = std::sqrt(discriminant); 24 | double root1 = (-b - sqrtDisc) / (2 * a); 25 | double root2 = (-b + sqrtDisc) / (2 * a); 26 | 27 | if (root1 > root2) std::swap(root1, root2); 28 | std::cout << "x1 = " << root1 << ", x2 = " << root2; 29 | return; 30 | } 31 | } 32 | }; 33 | 34 | int main() { 35 | double a, b, c; 36 | std::cin >> a >> b >> c; 37 | 38 | QuadraticEquation eq{ a, b, c }; 39 | eq.solve(); 40 | 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Evgeni_Darmanchev_1MI8000019/zad3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // Същата забележка и тук! 4 | struct Complex { 5 | int real; 6 | int imag; 7 | 8 | Complex add(const Complex& other) { 9 | return { real + other.real, imag + other.imag }; 10 | } 11 | 12 | Complex subtract(const Complex& other) { 13 | return { real - other.real, imag - other.imag }; 14 | } 15 | 16 | Complex multiply(const Complex& other) { 17 | int newReal = real * other.real - imag * other.imag; 18 | int newImag = real * other.imag + imag * other.real; 19 | return { newReal, newImag }; 20 | } 21 | 22 | void print() { 23 | if (real == 0 && imag != 0) { 24 | std::cout << imag << "i"; 25 | } 26 | else if (imag == 0) { 27 | std::cout << real; 28 | } 29 | else { 30 | std::cout << real; 31 | if (imag > 0) 32 | std::cout << "+" << imag << "i"; 33 | else 34 | std::cout << imag << "i"; 35 | } 36 | std::cout << "\n"; 37 | } 38 | }; 39 | 40 | int main() { 41 | Complex z1, z2; 42 | std::cin >> z1.real >> z1.imag >> z2.real >> z2.imag; 43 | 44 | Complex sum = z1.add(z2); 45 | Complex diff = z1.subtract(z2); 46 | Complex prod = z1.multiply(z2); 47 | 48 | sum.print(); 49 | diff.print(); 50 | prod.print(); 51 | 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Georgi_Komerdjanov_3MI0400017/hw1_task2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // Отново, това е лоша практика! 5 | using namespace std; 6 | 7 | struct QuadraticEquation { 8 | 9 | double a, b, c; 10 | 11 | // Методи все още не са учени, така че се въздържаме от употребата им. 12 | void computate() { 13 | 14 | double discriminant = b * b - 4 * a * c; 15 | 16 | if (discriminant < 0) { 17 | 18 | cout << "The equation does not have real solutions!" << endl; 19 | } 20 | else if (discriminant == 0) { 21 | 22 | double root = -b / (2 * a); 23 | cout << "x1 = x2 = " << root << endl; 24 | } 25 | else { 26 | 27 | double root1 = (-b - sqrt(discriminant)) / (2 * a); 28 | double root2 = (-b + sqrt(discriminant)) / (2 * a); 29 | if (root1 > root2) swap(root1, root2); 30 | cout << "x1 = " << root1 << ", x2 = " << root2 << endl; 31 | } 32 | } 33 | }; 34 | 35 | int main() { 36 | 37 | double a, b, c; 38 | cin >> a >> b >> c; 39 | QuadraticEquation equation = { a, b, c }; 40 | equation.computate(); 41 | return 0; 42 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Georgi_Komerdjanov_3MI0400017/hw1_task3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // Лоша практика! 4 | using namespace std; 5 | 6 | struct ComplexNumber { 7 | 8 | int real, imaginery; 9 | 10 | ComplexNumber(int r, int i) : real(r), imaginery(i) {} 11 | 12 | ComplexNumber operator+(const ComplexNumber& other) { 13 | 14 | return ComplexNumber(real + other.real, imaginery + other.imaginery); 15 | } 16 | 17 | ComplexNumber operator-(const ComplexNumber& other) { 18 | 19 | return ComplexNumber(real - other.real, imaginery - other.imaginery); 20 | } 21 | 22 | ComplexNumber operator*(const ComplexNumber& other) { 23 | 24 | return ComplexNumber(real * other.real - imaginery * other.imaginery, real * other.imaginery + imaginery * other.real); 25 | } 26 | 27 | void print() { 28 | 29 | if (imaginery == 0) { 30 | 31 | cout << real << endl; 32 | } 33 | else if (imaginery > 0) { 34 | 35 | cout << real << "+" << imaginery << "i" << endl; 36 | } 37 | else { 38 | 39 | cout << real << imaginery << "i" << endl; 40 | } 41 | } 42 | }; 43 | 44 | int main() { 45 | 46 | int a, b, c, d; 47 | cin >> a >> b >> c >> d; 48 | 49 | if (a < -1000 || a > 1000 || b < -1000 || b > 1000 || 50 | c < -1000 || c > 1000 || d < -1000 || d > 1000) { 51 | 52 | cerr << "Error. Values must be: [-1000, 1000]." << endl; 53 | return 1; 54 | } 55 | 56 | ComplexNumber z1(a, b), z2(c, d); 57 | 58 | (z1 + z2).print(); 59 | (z1 - z2).print(); 60 | (z1 * z2).print(); 61 | 62 | return 0; 63 | } 64 | -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Georgi_Naumov_2MI0400329/zad2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // По условие пишеше да се използват реални числа(double). 5 | // Такова уточнение би ти коствало точки на контролно/изпит. 6 | struct QuadraticEquation 7 | { 8 | int a; 9 | int b; 10 | int c; 11 | }; 12 | 13 | void inputCoefficients(QuadraticEquation &equation); 14 | void calculate(QuadraticEquation &equation); 15 | 16 | int main() 17 | { 18 | QuadraticEquation equation; 19 | std::cout << "Enter the coefficients of the quadratic equation:" << std::endl; 20 | inputCoefficients(equation); 21 | 22 | calculate(equation); 23 | 24 | return 0; 25 | } 26 | 27 | void inputCoefficients(QuadraticEquation &equation) 28 | { 29 | bool valid; 30 | 31 | do 32 | { 33 | valid = true; 34 | std::cin >> equation.a >> equation.b >> equation.c; 35 | if (!((equation.a >= -100 && equation.a <= 100) && 36 | (equation.b >= -100 && equation.b <= 100) && 37 | (equation.c >= -100 && equation.c <= 100))) 38 | { 39 | std::cout << "Wrong input! Try again:" << std::endl; 40 | valid = false; 41 | } 42 | } while (valid == false); 43 | } 44 | 45 | void calculate(QuadraticEquation &equation) 46 | { 47 | int discriminant = equation.b * equation.b - 4 * equation.a * equation.c; 48 | 49 | if (discriminant < 0) 50 | { 51 | std::cout << "The equation does not have real solitions!" << std::endl; 52 | } 53 | else if (discriminant == 0) 54 | { 55 | double solution = (-equation.b) / (2 * equation.a); 56 | std::cout << "x1 = x2 = " << solution << std::endl; 57 | } 58 | else 59 | { 60 | double solution1 = (-equation.b + sqrt(discriminant)) / (2 * equation.a); 61 | double solution2 = (-equation.b - sqrt(discriminant)) / (2 * equation.a); 62 | 63 | if (solution1 < solution2) 64 | { 65 | std::cout << "x1 = " << solution1 << ", x2 = " << solution2 << std::endl; 66 | } 67 | else 68 | { 69 | std::cout << "x1 = " << solution2 << ", x2 = " << solution1 << std::endl; 70 | } 71 | } 72 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Georgi_Radev_9MI0400247/prob01.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct Point { 4 | int x; 5 | int y; 6 | }; 7 | 8 | float readTriangleArea(); 9 | float mod(float x); 10 | void sortAreas(float * areas, size_t size); 11 | void printAreas(float * areas, size_t size); 12 | 13 | int main() { 14 | size_t size = 0; 15 | std::cin >> size; 16 | // По условие ти се изисква да създаваш и сортираш триъгълници, а не лица. 17 | // Имай го предвид, защото на контролни и изпит е твърде възможно да ти се заядат за някакъв такъв детайл. 18 | float * areas = new(std::nothrow) float[size]; 19 | if (!areas) { 20 | std::cerr << "Out of memory" << std::endl; 21 | return 0; 22 | } 23 | 24 | for (size_t i = 0; i < size; ++i) { 25 | areas[i] = readTriangleArea(); 26 | } 27 | 28 | sortAreas(areas, size); 29 | printAreas(areas, size); 30 | 31 | delete[] areas; 32 | return 0; 33 | } 34 | 35 | float readTriangleArea() { 36 | Point a, b, c; 37 | std::cin 38 | >> a.x >> a.y 39 | >> b.x >> b.y 40 | >> c.x >> c.y; 41 | 42 | // Можеш да използваш std::abs. 43 | return mod((a.x*b.y + a.y*c.x + b.x*c.y - a.y*b.x - a.x*c.y - b.y*c.x) / 2.0f); 44 | } 45 | 46 | float mod(float x) { 47 | return x < 0 ? -x : x; 48 | } 49 | 50 | void sortAreas(float * areas, size_t size) { 51 | float m = 0.0; 52 | for (size_t i = 0; i < size - 1; ++i) { 53 | for (size_t j = i + 1; j < size; ++j) { 54 | if (areas[i] > areas[j]) { 55 | m = areas[j]; 56 | areas[j] = areas[i]; 57 | areas[i] = m; 58 | } 59 | } 60 | } 61 | } 62 | 63 | void printAreas(float * areas, size_t size) { 64 | // Това просто изглежда грешно, макар и да е вярно XD. 65 | // Аз лично бих го вкарал в цикъла и да кажа следното: 66 | // if (i) std::cout << ' '; 67 | // std::cout << areas[i]; 68 | if (size) { 69 | std::cout << areas[0]; 70 | } 71 | for (size_t i = 1; i < size; ++i) { 72 | std::cout << " " << areas[i]; 73 | } 74 | std::cout << std::endl; 75 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Georgi_Radev_9MI0400247/prob02.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | const double EPS = 1e-9; 5 | 6 | struct QuadraticEquation { 7 | double a; 8 | double b; 9 | double c; 10 | }; 11 | 12 | void readEquation(QuadraticEquation& eq); 13 | void printSolution(const QuadraticEquation& eq); 14 | double mod(double a); 15 | 16 | int main() { 17 | QuadraticEquation equation; 18 | readEquation(equation); 19 | printSolution(equation); 20 | 21 | return 0; 22 | } 23 | 24 | void readEquation(QuadraticEquation& eq) { 25 | std::cin >> eq.a >> eq.b >> eq.c; 26 | } 27 | void printSolution(const QuadraticEquation& eq) { 28 | double d = eq.b*eq.b - 4 * eq.a*eq.c; 29 | if (d < 0) { 30 | std::cout << "The equation does not have real solutions!"; 31 | } 32 | else if ((mod(d) - EPS) < 0) { 33 | std::cout << "x1 = x2 = " << - eq.b/(2* eq.a); 34 | } 35 | else { 36 | double s = sqrt(d); 37 | std::cout << "x1 = " << (-eq.b - s) / 2 * eq.a << 38 | " x2 = " << (-eq.b + s) / 2 * eq.a; 39 | } 40 | std::cout << std::endl; 41 | } 42 | 43 | double mod(double a) { 44 | return a < 0 ? -a : a; 45 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Georgi_Radev_9MI0400247/prob03.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // Защо? 5 | const double EPS = 1e-9; 6 | 7 | struct Complex { 8 | double re; 9 | double im; 10 | }; 11 | 12 | Complex plus(Complex a, Complex b); 13 | Complex minus(Complex a, Complex b); 14 | Complex mult(Complex a, Complex b); 15 | 16 | int main() { 17 | // Липсва каквато и да е логика 18 | return 0; 19 | } 20 | 21 | Complex plus(Complex a, Complex b) { 22 | Complex r; 23 | r.re = a.re + b.re; 24 | r.im = a.im + b.im; 25 | return r; 26 | } 27 | Complex minus(Complex a, Complex b) { 28 | Complex r; 29 | r.re = a.re - b.re; 30 | r.im = a.im - b.im; 31 | return r; 32 | } 33 | Complex mult(Complex a, Complex b) { 34 | Complex r; 35 | r.re = a.re*b.re - a.im*b.im; 36 | r.im = a.re*b.im + b.im*a.re; 37 | return r; 38 | } 39 | 40 | double mod(double a) { 41 | return a < 0 ? -a : a; 42 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Giorgi_Begalinoski_3MI8000065/Domasno1_zad1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Point { 5 | int x, y; 6 | }; 7 | 8 | struct Triangle{ 9 | Point p1, p2, p3; 10 | 11 | // Методи все още не са учени. 12 | // Макар и да е добре написан се въздържаме от употребата им докато не ги вземем, 13 | // за да избегнем кофти коментари и неудобни въпроси от преподаватели. 14 | double area() const { 15 | return std::abs((p1.x * (p2.y - p3.y) + p2.x * (p3.y - p1.y) + p3.x * (p1.y - p2.y)) / 2.0); 16 | } 17 | }; 18 | 19 | void sortTriangles(Triangle *triangles,int n) { 20 | for (int i = 0; i < n - 1; i++) { 21 | for (int j = 0; j < n - i - 1; j++) { 22 | if (triangles[j].area() > triangles[j + 1].area()) { 23 | Triangle temp = triangles[j]; 24 | triangles[j] = triangles[j + 1]; 25 | triangles[j + 1] = temp; 26 | } 27 | } 28 | } 29 | } 30 | 31 | int main() { 32 | int n; 33 | do { 34 | std::cin >> n; 35 | } while (n < 1 || n > 1000); 36 | // Защо да въвеждаме размер, като винаги ще имаме 10 елемента?!? 37 | // Тук трябва задължително да се използва динамична памет. 38 | Triangle triangles[10]; 39 | for (int i = 0; i < n; i++) { 40 | std::cin >> triangles[i].p1.x >> triangles[i].p1.y 41 | >> triangles[i].p2.x >> triangles[i].p2.y 42 | >> triangles[i].p3.x >> triangles[i].p3.y; 43 | } 44 | 45 | sortTriangles(triangles, n); 46 | 47 | for (int i = 0; i < n; i++) { 48 | std::cout << triangles[i].area() << " "; 49 | } 50 | 51 | return 0; 52 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Giorgi_Begalinoski_3MI8000065/Domasno1_zad2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct QuadraticEquation { 5 | double a, b, c; 6 | 7 | // Отново същият коментар и тук. 8 | void solve() { 9 | if (a == 0) { 10 | std::cout << "The equation does not have real solutions!" << std::endl; 11 | return; 12 | } 13 | 14 | double discr = b * b - 4 * a * c; 15 | 16 | if (discr < 0) { 17 | std::cout << "The equation does not have real solutions!" << std::endl; 18 | } 19 | else if (discr == 0){ 20 | double x = -b / (2 * a); 21 | std::cout << "x1 = x2 = " << x << std::endl; 22 | } 23 | else { 24 | double x1 = (-b - std::sqrt(discr)) / (2 * a); 25 | double x2 = (-b + std::sqrt(discr)) / (2 * a); 26 | std::cout << "x1 = " << x1 << ", x2 = " << x2 << std::endl; 27 | } 28 | } 29 | }; 30 | 31 | int main() { 32 | 33 | double a, b, c; 34 | std::cin >> a >> b >> c; 35 | 36 | if (a < -100 || a > 100 || b < -100 || b > 100 || c < -100 || c > 100) { 37 | std::cout << "Invalid input! Constrains : -100 <= a, b, c <= 100!" << std::endl; 38 | return 0; 39 | } 40 | 41 | QuadraticEquation equation{ a, b, c }; 42 | equation.solve(); 43 | 44 | return 0; 45 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Giorgi_Begalinoski_3MI8000065/Domasno1_zad3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct ComplexNumber { 5 | int realPart; 6 | int imagineryPart; 7 | 8 | void print() { 9 | std::cout << realPart; 10 | if (imagineryPart != 0) { 11 | std::cout << (imagineryPart > 0 ? " + " : " - ") << std::abs(imagineryPart) << "i"; 12 | } 13 | std::cout << std::endl; 14 | } 15 | }; 16 | 17 | // Идеята на следващите три функции не е да показват само резултатът от действието, 18 | // ами да връщат обект, който го репрезентира. 19 | // Какво става ако искам да събера 3 комплексни числа? 20 | // Искам да направя z4 = add(z1, z2) и после result = add(z3, z4). 21 | void addComplexNumbers(ComplexNumber z1, ComplexNumber z2) { 22 | ComplexNumber newZ; 23 | newZ.realPart = z1.realPart + z2.realPart; 24 | newZ.imagineryPart = z1.imagineryPart + z2.imagineryPart; 25 | newZ.print(); 26 | } 27 | 28 | void subtractComplexNumbers(ComplexNumber z1, ComplexNumber z2) { 29 | ComplexNumber newZ; 30 | newZ.realPart = z1.realPart - z2.realPart; 31 | newZ.imagineryPart = z1.imagineryPart - z2.imagineryPart; 32 | newZ.print(); 33 | } 34 | 35 | void multiplyComplexNumbers(ComplexNumber z1, ComplexNumber z2) { 36 | ComplexNumber newZ; 37 | newZ.realPart = z1.realPart * z2.realPart - z1.imagineryPart * z2.imagineryPart; 38 | newZ.imagineryPart = z1.realPart * z2.imagineryPart + z1.imagineryPart * z2.realPart; 39 | newZ.print(); 40 | } 41 | 42 | 43 | int main() { 44 | 45 | ComplexNumber z1; 46 | std::cin >> z1.realPart >> z1.imagineryPart; 47 | ComplexNumber z2; 48 | std::cin >> z2.realPart >> z2.imagineryPart; 49 | 50 | addComplexNumbers(z1, z2); 51 | subtractComplexNumbers(z1, z2); 52 | multiplyComplexNumbers(z1, z2); 53 | return 0; 54 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Hristina_Zehireva_2MI0400242/areaoftriangles.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Point{ 5 | int x; 6 | int y; 7 | }; 8 | 9 | struct Triangle{ 10 | Point A; 11 | Point B; 12 | Point C; 13 | double area; 14 | }; 15 | 16 | double distance(const Point &A, const Point &B) 17 | { 18 | return sqrt((A.x - B.x) * (A.x - B.x) + (A.y - B.y) * (A.y - B.y)); 19 | 20 | } 21 | 22 | void calculateArea(Triangle &trian) 23 | { 24 | double a = distance(trian.A, trian.B); 25 | double b = distance(trian.A, trian.C); 26 | double c = distance(trian.B, trian.C); 27 | 28 | double halfperimeter = (a + b + c) / 2; 29 | trian.area = sqrt(halfperimeter * (halfperimeter - a) * 30 | (halfperimeter - b) * (halfperimeter - c)); 31 | 32 | 33 | } 34 | 35 | void sortArea(Triangle *trian, const int size) // bubble sort 36 | { 37 | for (int i = 0; i < size - 1; i++) 38 | { 39 | for (int j = i + 1; j < size; j++) 40 | { 41 | if (trian[i].area > trian[j].area) 42 | { 43 | std::swap(trian[i],trian[j]); 44 | } 45 | 46 | } 47 | 48 | } 49 | 50 | } 51 | 52 | 53 | int main() 54 | { 55 | int n; 56 | do 57 | { 58 | std::cin >> n; 59 | } while (n <= 1 && n >= 1000); 60 | 61 | // Липсва std::nothrow като аргумент на оператора new, което може да 62 | // доведе до crash на програмата и се води като голяма грешка! 63 | Triangle *trian = new Triangle[n]; 64 | 65 | // Липсва валидация за указателя, което може да доведе до проблеми при по-нататъчната му употреба! 66 | 67 | 68 | for (int i = 0; i < n; i++) 69 | { 70 | std::cin >> trian[i].A.x >> trian[i].A.y 71 | >> trian[i].B.x >> trian[i].B.y 72 | >> trian[i].C.x >> trian[i].C.y; 73 | 74 | calculateArea(trian[i]); 75 | } 76 | 77 | sortArea(trian,n); 78 | 79 | for (int i = 0; i < n; i++) 80 | { 81 | std::cout << trian[i].area << ' '; 82 | } 83 | 84 | delete[] trian; 85 | 86 | 87 | return 0; 88 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Hristina_Zehireva_2MI0400242/complex.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | 4 | struct Complex 5 | { 6 | int real; 7 | int imag; 8 | 9 | // За методи не е говорено, така че нека не бързаме с материала! 10 | Complex add(const Complex& other) const{ 11 | Complex result; 12 | result.real = real + other.real; 13 | result.imag = imag + other.real; 14 | return result; 15 | } 16 | 17 | Complex substract(const Complex &other) const{ 18 | Complex result; 19 | result.real = real - other.real; 20 | result.imag = imag - other.imag; 21 | return result; 22 | } 23 | 24 | Complex multiply(const Complex &other) const{ 25 | Complex result; 26 | result.real = real * other.real - imag * other.imag; 27 | result.imag = real * other.imag + imag * other.real; 28 | return result; 29 | } 30 | 31 | void print() const{ 32 | if (imag >= 0) 33 | std::cout << real << "+" << imag << "i" << '\n'; 34 | else 35 | std::cout << real << imag << "i" << '\n'; 36 | 37 | } 38 | 39 | }; 40 | 41 | int main() 42 | { 43 | int a, b, c, d; 44 | std::cin >> a >> b >> c >> d; 45 | 46 | if (a < -1000 || a > 1000 || b < -1000 || b > 1000 || c < -1000 || c > 1000) 47 | { 48 | std::cerr << "error"; 49 | return 1; 50 | } 51 | 52 | 53 | Complex z1; 54 | z1.real = a; 55 | z1.imag = b; 56 | 57 | Complex z2; 58 | z2.real = c; 59 | z2.imag = d; 60 | 61 | Complex sum = z1.add(z2); 62 | Complex difference = z1.substract(z2); 63 | Complex product = z1.multiply(z2); 64 | 65 | sum.print(); 66 | difference.print(); 67 | product.print(); 68 | 69 | return 0; 70 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Hristina_Zehireva_2MI0400242/quadratic.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct quadraticEquation 5 | { 6 | double a; 7 | double b; 8 | double c; 9 | 10 | // За методи не е говорено, така че нека не бързаме с материала! 11 | void solve() const{ 12 | if (a < -100 || a > 100 || b < -100 || b > 100 || c < -100 || c > 100) 13 | { 14 | std::cerr << "Error!\n"; 15 | } 16 | 17 | double discriminant = b*b - 4*a*c; 18 | if (discriminant > 0) 19 | { 20 | double root1 = (-b + sqrt(discriminant)) / (2 * a); 21 | double root2 = (-b - sqrt(discriminant)) / (2 * a); 22 | if (root1 > root2) 23 | { 24 | std::swap(root1,root2); 25 | } 26 | std::cout << "x1 = " << root1 << ", x2 = " << root2 << '\n'; 27 | } 28 | else if(discriminant == 0) 29 | { 30 | double root = -b / (2*a); 31 | std::cout << "x1 = x2 = " << root << '\n'; 32 | } 33 | else{ 34 | std::cout << "The equation does not have real solutions!" << std::endl; 35 | } 36 | 37 | 38 | } 39 | }; 40 | 41 | 42 | int main() 43 | { 44 | quadraticEquation equation; 45 | double a, b, c; 46 | std::cin >> a >> b >> c; 47 | 48 | equation.a = a; 49 | equation.b = b; 50 | equation.c = c; 51 | equation.solve(); 52 | 53 | 54 | return 0; 55 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Ivo_Kisiov_5MI0400254/zad2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct quadEquation 5 | { 6 | double a, b, c; 7 | double d; 8 | double x1, x2; 9 | }; 10 | 11 | // Тук можеш да го подадеш като референция, за да си спестиш дереференцирането. 12 | void findDiscriminat(quadEquation* q) 13 | { 14 | (*q).d = pow((*q).b, 2) - 4 * (*q).a * (*q).c; 15 | } 16 | 17 | // Същата забележка и тук. 18 | void findSolutions(quadEquation* q) 19 | { 20 | findDiscriminat(q); 21 | if((*q).d < 0) 22 | { 23 | std::cout << "The equation does not have real solutions!"; 24 | return; 25 | } 26 | else if((*q).d == 0) 27 | { 28 | (*q).x1 = (*q).x2 = -(*q).b / (2 * (*q).a); 29 | std::cout << "x1 = x2 = " << (*q).x1; 30 | return; 31 | } 32 | else 33 | { 34 | (*q).x1 = (-(*q).b + sqrt((*q).d)) / (2 * (*q).a); 35 | (*q).x2 = (-(*q).b - sqrt((*q).d)) / (2 * (*q).a); 36 | if((*q).x1 > (*q).x2) 37 | { 38 | double temp = (*q).x1; 39 | (*q).x1 = (*q).x2; 40 | (*q).x2 = temp; 41 | } 42 | std::cout << "x1 = " << (*q).x1 << ", " << "x2 = " << (*q).x2; 43 | return; 44 | } 45 | } 46 | 47 | int main() 48 | { 49 | quadEquation q; 50 | std::cin >> q.a >> q.b >> q.c; 51 | if(q.a < -100 || q.a > 100 || q.b < -100 || q.b > 100 || q.c < -100 || q.c > 100) 52 | { 53 | std::cout << "Invalid data"; 54 | return -1; 55 | } 56 | findSolutions(&q); 57 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Ivo_Kisiov_5MI0400254/zad3.cpp: -------------------------------------------------------------------------------- 1 | // Преговори референциите! 2 | #include 3 | 4 | struct complexNum 5 | { 6 | int a, b, c, d; 7 | int z1, z2; 8 | }; 9 | 10 | void printResult(complexNum* c) 11 | { 12 | if(c->z2 == 0) 13 | { 14 | std::cout << c->z1 << std::endl; 15 | } 16 | else if(c->z1 == 0) 17 | { 18 | std::cout << c->z2 << "i" << std::endl; 19 | } 20 | else 21 | { 22 | if(c->z2 > 0) 23 | { 24 | std::cout << c->z1 << "+" << c->z2 << "i" << std::endl; 25 | } 26 | else 27 | { 28 | std::cout << c->z1 << c->z2 << "i" << std::endl; 29 | } 30 | } 31 | } 32 | 33 | 34 | // От функции като add, subtract, multiply и т.н. 35 | // очаквам само да направят операцията и да ми върнат резултат. 36 | // Не очаквам и да го принтират също. 37 | // Тогава трябваше да се казват AddAndPrint. 38 | void addition(complexNum* c) 39 | { 40 | c->z1 = (c->a + c->c); 41 | c->z2 = (c->b + c->d); 42 | printResult(c); 43 | } 44 | 45 | void subtraction(complexNum* c) 46 | { 47 | c->z1 = (c->a - c->c); 48 | c->z2 = (c->b - c->d); 49 | 50 | printResult(c); 51 | } 52 | 53 | void multiplication(complexNum* c) 54 | { 55 | c->z1 = (c->a * c->c - c->b * c->d); 56 | c->z2 = (c->a * c->d + c->b * c->c); 57 | 58 | printResult(c); 59 | } 60 | 61 | int main() 62 | { 63 | complexNum c; 64 | std::cin >> c.a >> c.b >> c.c >> c.d; 65 | if(c.a < -1000 || c.a > 1000 || c.b < -1000 || c.b > 1000 || c.c < -1000 || c.c > 1000 || c.d < -1000 || c.d > 1000) 66 | { 67 | std::cout << "Invalid data"; 68 | return -1; 69 | } 70 | 71 | addition(&c); 72 | subtraction(&c); 73 | multiplication(&c); 74 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Katrin_Lilova_7MI0400333/main.cpp: -------------------------------------------------------------------------------- 1 | #include "task1.hpp" 2 | #include "task2.hpp" 3 | #include "task3.hpp" 4 | #include "task4.hpp" 5 | 6 | int main() { 7 | int res = Task1::run(); 8 | 9 | // res = Task2::run(); 10 | // res = Task3::run(); 11 | // res = Task4::run(); 12 | 13 | return res; 14 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Katrin_Lilova_7MI0400333/task1.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | namespace Task1 { 4 | const unsigned int TRIANGLE_COUNT_MAX = 1000; 5 | const unsigned int TRIANGLE_COUNT_MIN = 1; 6 | 7 | const unsigned int TRIANGLE_VERTEX_COUNT = 3; 8 | 9 | const int COORD_VALUE_MAX = 100; 10 | const int COORD_VALUE_MIN = -100; 11 | 12 | struct Vertex { 13 | int x; 14 | int y; 15 | }; 16 | 17 | struct Triangle { 18 | double area; 19 | Vertex vertexes[TRIANGLE_VERTEX_COUNT]; 20 | }; 21 | 22 | int run(); 23 | void readVertexes(Triangle* triangles, unsigned int count); 24 | 25 | double getArea(const Triangle& triangle); 26 | void printAreas(const Triangle* triangles, unsigned int count); 27 | void sortAreas(Triangle* triangles, unsigned int count); 28 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Katrin_Lilova_7MI0400333/task2.cpp: -------------------------------------------------------------------------------- 1 | // Идеално разписана задача 2 | #include "task2.hpp" 3 | #include 4 | #include 5 | 6 | namespace Task2 { 7 | bool hasRealRoots(const QuadraticEquation& eq) { 8 | return eq.discriminant >= 0; 9 | } 10 | 11 | void findRoots(QuadraticEquation& eq) { 12 | if (eq.discriminant == 0) { 13 | double x = -eq.b / (2 * eq.a); 14 | eq.root1 = x; 15 | eq.root2 = x; 16 | } 17 | else { 18 | double x1 = (-eq.b + std::sqrt(eq.discriminant)) / (2 * eq.a); 19 | eq.root1 = x1; 20 | 21 | double x2 = (-eq.b - std::sqrt(eq.discriminant)) / (2 * eq.a); 22 | eq.root2 = x2; 23 | } 24 | } 25 | 26 | void setDiscriminant(QuadraticEquation& eq) { 27 | double d = eq.b * eq.b - 4 * eq.a * eq.c; 28 | eq.discriminant = d; 29 | } 30 | 31 | int run() { 32 | QuadraticEquation eq; 33 | std::cout << "Enter coefficients:" << "\n"; 34 | 35 | do { 36 | std::cin >> eq.a >> eq.b >> eq.c; 37 | } while (eq.a < COEF_VALUE_MIN || eq.a > COEF_VALUE_MAX || 38 | eq.b < COEF_VALUE_MIN || eq.b > COEF_VALUE_MAX || 39 | eq.c < COEF_VALUE_MIN || eq.c > COEF_VALUE_MAX); 40 | 41 | setDiscriminant(eq); 42 | 43 | if (!hasRealRoots(eq)) { 44 | std::cout << "No real roots." << "\n"; 45 | 46 | return 1; 47 | } 48 | 49 | findRoots(eq); 50 | std::cout << "x1 = " << eq.root1 << ", x2 = " << eq.root2 << "\n"; 51 | 52 | return 0; 53 | } 54 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Katrin_Lilova_7MI0400333/task2.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | namespace Task2 { 4 | const double COEF_VALUE_MAX = 100; 5 | const double COEF_VALUE_MIN = -100; 6 | 7 | // Единствена забележка имам тук, че бих пазил по-малко данни в самата структура. 8 | // Например дискриминантата е нещо, което се изчислява за линейно време и ти трябва само 9 | // във функцията за намиране на корените. Така че може само там да я смятаме и да е като временна променлива. 10 | struct QuadraticEquation { 11 | double a; 12 | double b; 13 | double c; 14 | double discriminant; 15 | double root1; 16 | double root2; 17 | }; 18 | 19 | int run(); 20 | 21 | bool hasRealRoots(const QuadraticEquation& eq); 22 | void findRoots(QuadraticEquation& eq); 23 | void setDiscriminant(QuadraticEquation& eq); 24 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Katrin_Lilova_7MI0400333/task3.cpp: -------------------------------------------------------------------------------- 1 | // Идеално разписана задача 2 | #include "task3.hpp" 3 | #include 4 | 5 | namespace Task3 { 6 | ComplexNumber add(const ComplexNumber& z1, const ComplexNumber& z2) { 7 | return { z1.real + z2.real, z1.imaginary + z2.imaginary }; 8 | } 9 | 10 | ComplexNumber multiply(const ComplexNumber& z1, const ComplexNumber& z2) { 11 | return { 12 | z1.real * z2.real - z1.imaginary * z2.imaginary, 13 | z1.real * z2.imaginary + z1.imaginary * z2.real 14 | }; 15 | } 16 | 17 | ComplexNumber subtract(const ComplexNumber& z1, const ComplexNumber& z2) { 18 | return { z1.real - z2.real, z1.imaginary - z2.imaginary }; 19 | } 20 | 21 | void print(const ComplexNumber& num) { 22 | std::cout << num.real; 23 | 24 | if (num.imaginary >= 0) { 25 | std::cout << "+" << num.imaginary << "i\n"; 26 | } 27 | else { 28 | std::cout << "-" << -num.imaginary << "i\n"; 29 | } 30 | } 31 | 32 | int run() { 33 | int a, b, c, d; 34 | std::cout << "Enter coefficients:" << "\n"; 35 | 36 | do { 37 | std::cin >> a >> b >> c >> d; 38 | } while (a < COEF_VALUE_MIN || a > COEF_VALUE_MAX || 39 | b < COEF_VALUE_MIN || b > COEF_VALUE_MAX || 40 | c < COEF_VALUE_MIN || c > COEF_VALUE_MAX || 41 | d < COEF_VALUE_MIN || d > COEF_VALUE_MAX); 42 | 43 | ComplexNumber z1, z2; 44 | 45 | z1.real = a; 46 | z1.imaginary = b; 47 | 48 | z2.real = c; 49 | z2.imaginary = d; 50 | 51 | print(add(z1, z2)); 52 | print(subtract(z1, z2)); 53 | 54 | print(multiply(z1, z2)); 55 | return 0; 56 | } 57 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Katrin_Lilova_7MI0400333/task3.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | namespace Task3 { 4 | const int COEF_VALUE_MAX = 1000; 5 | const int COEF_VALUE_MIN = -1000; 6 | 7 | struct ComplexNumber { 8 | int real; 9 | int imaginary; 10 | }; 11 | 12 | int run(); 13 | void print(const ComplexNumber& num); 14 | 15 | ComplexNumber add(const ComplexNumber& z1, const ComplexNumber& z2); 16 | ComplexNumber multiply(const ComplexNumber& z1, const ComplexNumber& z2); 17 | ComplexNumber subtract(const ComplexNumber& z1, const ComplexNumber& z2); 18 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Katrin_Lilova_7MI0400333/task4.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | namespace Task4 { 4 | const unsigned int STUDENT_COUNT_MAX = 500; 5 | const unsigned int STUDENT_COUNT_MIN = 1; 6 | 7 | const unsigned int FACULTY_NUMBER_MAX = 99999; 8 | const unsigned int FACULTY_NUMBER_MIN = 10000; 9 | 10 | const float GRADE_MAX = 6.0; 11 | const float GRADE_MIN = 2.0; 12 | 13 | enum Course { 14 | FIRST = 1, 15 | SECOND, 16 | THIRD, 17 | FOURTH 18 | }; 19 | 20 | struct Student { 21 | unsigned int facultyNumber; 22 | Course course; 23 | float averageGrade; 24 | }; 25 | 26 | struct Group { 27 | float averageGrade; 28 | unsigned int studentCount; 29 | Student* students; 30 | }; 31 | 32 | int run(); 33 | 34 | float calculateGroupAverage(const Group& group); 35 | unsigned int countScholarshipStudents(const Group& group, float minGrade); 36 | void initStudent(Student& s); 37 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Kremena_Dimitrova_3MI0400312/zad2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // По условие се изискваше да пазите реални числа, а не цели! 5 | struct QuadraticEquation 6 | { 7 | int a; 8 | int b; 9 | int c; 10 | }; 11 | 12 | void readElements(QuadraticEquation& equation) { 13 | std::cin >> equation.a >> equation.b >> equation.c; 14 | } 15 | void checkIfCoefficientsAreValid(QuadraticEquation& equation) { 16 | if (equation.a < -100 || equation.a > 100 17 | || equation.b < -100 || equation.b > 100 18 | || equation.c < -100 || equation.c > 100) 19 | { 20 | std::cout << "Invalid input! Coefficients must be greater than -100 and less than 100!" << std::endl; 21 | // Отново същата забележка с exit. 22 | exit(1); 23 | } 24 | } 25 | 26 | int findTheDiscriminant(QuadraticEquation& equation) { 27 | return (equation.b * equation.b) - 4 * (equation.a * equation.c); 28 | } 29 | 30 | double findX1(QuadraticEquation& equation, int theDiscriminant) { 31 | return ((-equation.b) - sqrt(theDiscriminant)) / (2 * equation.a); 32 | } 33 | 34 | double findX2(QuadraticEquation& equation, int theDiscriminant) { 35 | return ((-equation.b) + sqrt(theDiscriminant)) / (2 * equation.a); 36 | } 37 | 38 | int main() { 39 | QuadraticEquation equation; 40 | 41 | std::cout << "Please enter exactly 3 coefficients: " << std::endl; 42 | 43 | readElements(equation); 44 | checkIfCoefficientsAreValid(equation); 45 | 46 | int theDiscriminant = findTheDiscriminant(equation); 47 | 48 | if (theDiscriminant < 0) { 49 | std::cout << "The equation does not have real solutions!" << std::endl; 50 | return 0; 51 | } else if (theDiscriminant == 0) { 52 | std::cout << "x1 = x2 = " << (- equation.b) / (2.0 * equation.a) << std::endl; 53 | } else { 54 | double x1 = findX1(equation, theDiscriminant); 55 | double x2 = findX2(equation, theDiscriminant); 56 | 57 | if (x1 < x2) 58 | std::cout << "x1 = " << x1 << ", x2 = " << x2 << std::endl; 59 | else 60 | std::cout << "x1 = " << x2 << ", x2 = " << x1 << std::endl; 61 | } 62 | 63 | return 0; 64 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Melisa_Chausheva_4MI0400232/fourthTask.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct Student 4 | { 5 | int facNum; 6 | int year; 7 | float grade; 8 | }; 9 | 10 | // По условие ти се иска да се въвежда размер, 11 | // защото целта е да се заделя динамична памет. 12 | const int size = 100; 13 | 14 | struct Group 15 | { 16 | Student students[size]; 17 | int count; 18 | float grade; 19 | 20 | void calculateGroupAvg() 21 | { 22 | float totalGrade = 0.0; 23 | for (int i = 0; i < count; i++) 24 | { 25 | totalGrade += students[i].grade; 26 | } 27 | grade = totalGrade / count; 28 | } 29 | 30 | int calculateRecipients(float minGrade) 31 | { 32 | int count = 0; 33 | for (int i = 0; i < this->count; i++) 34 | { 35 | if (students[i].grade >= minGrade) 36 | { 37 | count++; 38 | } 39 | } 40 | return count; 41 | } 42 | }; 43 | 44 | // На теория можеш да си създадеш обекта и във функцията и направо да върнеш студента. 45 | // Поне на мен ми изглежда по-логично, защото така се използва и конструктора, който се опитваме да имитираме. 46 | void Studentt(Student& s, int facNum, int year, float grade) 47 | { 48 | s.facNum = facNum; 49 | s.year = year; 50 | s.grade = grade; 51 | } 52 | 53 | void printStudent(const Student& s) 54 | { 55 | std::cout << s.facNum << s.year << s.grade << std::endl; 56 | } 57 | 58 | int main() 59 | { 60 | Group group; 61 | int n; 62 | std::cin >> n; 63 | if (n<1 || n>500) 64 | { 65 | std::cout << "Invalid input!" << std::endl; 66 | return 1; 67 | } 68 | 69 | group.count = n; 70 | 71 | for (int i = 0; i < n; i++) 72 | { 73 | int facNum, year; 74 | float grade; 75 | std::cin >> facNum >> year >> grade; 76 | if (facNum<10000 || facNum>100000 || year<1 || 77 | year>4 || grade<2 || grade>6) 78 | { 79 | std::cout << "Invalid input!" << std::endl; 80 | return 1; 81 | } 82 | 83 | Studentt(group.students[i], facNum, year, grade); 84 | } 85 | 86 | float minGrade; 87 | std::cin >> minGrade; 88 | 89 | 90 | group.calculateGroupAvg(); 91 | std::cout << group.grade << std::endl; 92 | 93 | int count = group.calculateRecipients(minGrade); 94 | std::cout << count << std::endl; 95 | 96 | return 0; 97 | } 98 | -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Melisa_Chausheva_4MI0400232/secondTask.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | 5 | struct QuadraticEquation 6 | { 7 | double a, b, c; 8 | 9 | // Отново, нека не избързваме с материала. 10 | double discriminant() 11 | { 12 | return pow(b, 2) - 4 * a * c; 13 | } 14 | 15 | void swap(double* a, double* b) 16 | { 17 | double temp = *a; 18 | *a = *b; 19 | *b = temp; 20 | } 21 | 22 | void solve() 23 | { 24 | double d = discriminant(); 25 | 26 | if (d<0) 27 | { 28 | std::cout << "The equation does not have real solutions!"<x2) 41 | { 42 | swap(&x1,&x2); 43 | } 44 | std::cout << x1 <<" "<< x2 << std::endl; 45 | } 46 | } 47 | 48 | }; 49 | 50 | 51 | int main() 52 | { 53 | double a, b, c; 54 | std::cin >> a >> b >> c; 55 | 56 | if (a<-100 || b<-100 || c<-100 || 57 | a>100 ||b>100 ||c>100) 58 | { 59 | std::cout << "Imvalid input!"; 60 | return 1; 61 | } 62 | 63 | QuadraticEquation equation = { a,b,c }; 64 | 65 | equation.solve(); 66 | 67 | 68 | return 0; 69 | } 70 | -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Melisa_Chausheva_4MI0400232/thirdTask.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // Защо със C синтаксис? 4 | typedef struct 5 | { 6 | int real; 7 | int imag; 8 | } Complex; 9 | 10 | Complex add(Complex z1, Complex z2) 11 | { 12 | Complex result; 13 | result.real = z1.real + z2.real; 14 | result.imag = z1.imag + z2.imag; 15 | return result; 16 | } 17 | 18 | Complex subtract(Complex z1, Complex z2) 19 | { 20 | Complex result; 21 | result.real = z1.real - z2.real; 22 | result.imag = z1.imag - z2.imag; 23 | return result; 24 | } 25 | 26 | Complex multiply(Complex z1, Complex z2) 27 | { 28 | Complex result; 29 | result.real = z1.real * z2.real - z1.imag * z2.imag; 30 | result.imag = z1.real * z2.imag + z1.imag * z2.real; 31 | return result; 32 | } 33 | 34 | void printComplex(Complex z) 35 | { 36 | bool realPrinted = false, imagPrinted = false; 37 | 38 | if (z.real != 0) 39 | { 40 | std::cout << z.real; 41 | realPrinted = true; 42 | } 43 | 44 | if (z.imag != 0) 45 | { 46 | if (realPrinted) 47 | { 48 | if (z.imag > 0) 49 | { 50 | std::cout << " + " << z.imag << "i"; 51 | } 52 | else 53 | { 54 | std::cout << " - " << -z.imag << "i"; 55 | } 56 | } 57 | else 58 | { 59 | std::cout << z.imag << "i"; 60 | } 61 | } 62 | else if (!realPrinted) 63 | { 64 | std::cout << "0"; 65 | } 66 | 67 | std::cout << std::endl; 68 | } 69 | 70 | int main() 71 | { 72 | int a, b, c, d; 73 | std::cin >> a >> b >> c >> d; 74 | 75 | if (a < -1000 || b < -1000 || c < -1000 || 76 | a>1000 || b>1000 || c>1000) 77 | { 78 | std::cout << "Imvalid input!"< 2 | // Липсва cmath библиотеката 3 | 4 | 5 | // Отново задачата не е по условието, тъй като не се използват никакви структури! 6 | 7 | void readQuadraticParams(int& a, int& b, int& c) { 8 | std::cin >> a; 9 | std::cin >> b; 10 | std::cin >> c; 11 | 12 | while (-100 > a || 100 < a || -100 > b || 100 < b || -100 > c || 100 < c) { 13 | std::cout << "Invalid input!!! \n a,b,c must be >= -100 and <= 100 !" << std::endl; 14 | std::cin >> a; 15 | std::cin >> b; 16 | std::cin >> c; 17 | } 18 | } 19 | 20 | int getQuadraticSolutions(int a ,int b ,int c, double* result) { 21 | double d = b * b - 4 * a * c; 22 | if (d < 0) { 23 | return 0; 24 | } 25 | if (d == 0) { 26 | double x1 = (-b + d) / (2 * a); 27 | result[0] = x1; 28 | return 1; 29 | } 30 | d = sqrt(d); 31 | double x1 = (-b + d) / (2 * a); 32 | double x2 = (-b - d) / (2 * a); 33 | 34 | if (x1 > x2) { 35 | result[0] = x2; 36 | result[1] = x1; 37 | } 38 | else { 39 | result[0] = x1; 40 | result[1] = x2; 41 | } 42 | return 2; 43 | } 44 | 45 | int main2() { 46 | int a, b, c; 47 | readQuadraticParams(a,b,c); 48 | 49 | double result[2]; 50 | int answers = getQuadraticSolutions(a,b,c,result); 51 | 52 | if (answers == 0) { 53 | std::cout << "The equation does not have real solutions!" << std::endl; 54 | } 55 | else if (answers == 1) { 56 | std::cout << "x1 = x2 = " << result[0] << std::endl; 57 | } 58 | else { 59 | std::cout << "x1 = " << result[0] << ", x2 = " << result[1] << std::endl; 60 | } 61 | return 0; 62 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Miumiun_Izmirliev_7MI0400320/Zad3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // Отново задачата не е по условието, тъй като не се използват никакви структури! 4 | 5 | void readComplexNumbers(int& a, int& b, int& c, int&d) { 6 | std::cin >> a; 7 | std::cin >> b; 8 | std::cin >> c; 9 | std::cin >> d; 10 | 11 | while (-1000 > a || 1000 < a || -1000 > b || 1000 < b || -1000 > c || 1000 < c || -1000 > d || 1000 < d) { 12 | std::cout << "Invalid input!!! \n a,b,c,d must be >= -1000 and <= 1000 !" << std::endl; 13 | std::cin >> a; 14 | std::cin >> b; 15 | std::cin >> c; 16 | std::cin >> d; 17 | } 18 | } 19 | 20 | void addComplexNumbers(int a, int b, int c, int d, int& r1, int& r2) { 21 | r1 = a + c; 22 | r2 = b + d; 23 | } 24 | 25 | void subtractComplexNumbers(int a, int b, int c, int d, int& r1, int& r2) { 26 | r1 = a - c; 27 | r2 = b - d; 28 | } 29 | 30 | void multiplyComplexNumbers(int a, int b, int c, int d, int& r1, int& r2) { 31 | //(a + bi) * (c + di) 32 | r1 = a * c - b * d; 33 | r2 = a * d + b * c; 34 | } 35 | 36 | void printComplexNumber(int a, int b) { 37 | if (b == 0) { 38 | std::cout << a << std::endl; 39 | return; 40 | } 41 | if (a == 0) { 42 | std::cout << b << "i" << std::endl; 43 | return; 44 | } 45 | if (b < 0) { 46 | std::cout << a << b << "i" << std::endl; 47 | return; 48 | } 49 | std::cout << a << "+" << b << "i" << std::endl; 50 | } 51 | 52 | int main3() { 53 | int a, b, c, d; 54 | readComplexNumbers(a,b,c,d); 55 | 56 | int r1, r2; 57 | addComplexNumbers(a, b, c, d, r1, r2); 58 | printComplexNumber(r1, r2); 59 | subtractComplexNumbers(a, b, c, d, r1, r2); 60 | printComplexNumber(r1, r2); 61 | multiplyComplexNumbers(a, b, c, d, r1, r2); 62 | printComplexNumber(r1, r2); 63 | 64 | return 0; 65 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Nick_Raichev_3MI0400004/HW3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct Complex { 4 | int real, imag; 5 | }; 6 | 7 | Complex add(const Complex& z1, const Complex& z2) { 8 | return { z1.real + z2.real, z1.imag + z2.imag }; 9 | } 10 | 11 | Complex subtract(const Complex& z1, const Complex& z2) { 12 | return { z1.real - z2.real, z1.imag - z2.imag }; 13 | } 14 | 15 | Complex multiply(const Complex& z1, const Complex& z2) { 16 | return { 17 | z1.real * z2.real - z1.imag * z2.imag, 18 | z1.real * z2.imag + z1.imag * z2.real 19 | }; 20 | } 21 | 22 | void printComplex(const Complex& z) { 23 | if (z.imag == 0) { 24 | std::cout << z.real << std::endl; 25 | } 26 | else if (z.real == 0) { 27 | std::cout << z.imag << "i" << std::endl; 28 | } 29 | else { 30 | std::cout << z.real; 31 | if (z.imag > 0) { 32 | std::cout << "+" << z.imag << "i" << std::endl; 33 | } 34 | else { 35 | std::cout << z.imag << "i" << std::endl; 36 | } 37 | } 38 | } 39 | 40 | int main() { 41 | Complex z1, z2; 42 | std::cin >> z1.real >> z1.imag >> z2.real >> z2.imag; 43 | 44 | printComplex(add(z1, z2)); 45 | printComplex(subtract(z1, z2)); 46 | printComplex(multiply(z1, z2)); 47 | 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Nick_Raichev_3MI0400004/HW4.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct Student { 4 | int facultyNumber; 5 | int course; 6 | double averageGrade; 7 | }; 8 | 9 | void initStudent(Student& student) { 10 | std::cin >> student.facultyNumber >> student.course >> student.averageGrade; 11 | } 12 | 13 | void printStudent(const Student& student) { 14 | std::cout << "FN: " << student.facultyNumber << ", Course: " << student.course 15 | << ", Avg Grade: " << student.averageGrade << std::endl; 16 | } 17 | 18 | struct Group { 19 | int studentCount; 20 | // Това трябва да е динамичен масив, чиито размер въвеждаме през конзолата. 21 | Student students[500]; // Maximum of 500 students 22 | double averageGroupGrade; 23 | }; 24 | 25 | // Function to calculate the group's average grade 26 | double calculateAverageGrade(const Group& group) { 27 | double total = 0; 28 | for (int i = 0; i < group.studentCount; i++) { 29 | total += group.students[i].averageGrade; 30 | } 31 | return total / group.studentCount; 32 | } 33 | 34 | int countScholarshipStudents(const Group& group, double minScholarshipGrade) { 35 | int count = 0; 36 | for (int i = 0; i < group.studentCount; i++) { 37 | if (group.students[i].averageGrade >= minScholarshipGrade) { 38 | count++; 39 | } 40 | } 41 | return count; 42 | } 43 | 44 | int main() { 45 | Group group; 46 | std::cin >> group.studentCount; 47 | 48 | for (int i = 0; i < group.studentCount; i++) { 49 | initStudent(group.students[i]); 50 | } 51 | 52 | group.averageGroupGrade = calculateAverageGrade(group); 53 | 54 | double minScholarshipGrade; 55 | std::cin >> minScholarshipGrade; 56 | 57 | int scholarshipCount = countScholarshipStudents(group, minScholarshipGrade); 58 | 59 | std::cout << group.averageGroupGrade << " " << scholarshipCount << std::endl; 60 | 61 | return 0; 62 | } 63 | -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Nikol_Bonjolova_1MI0400376/hm1.cpp: -------------------------------------------------------------------------------- 1 | // STL библиотеки(като vector и algorithm) са ви забранени за използване, 2 | // освен ако не ви е казано изрично, че можете. 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | // Лоша практика е употребата на този ред. 9 | using namespace std; 10 | 11 | // Това е изцяло материал, който предстои да учим. 12 | // Нека не избързваме с употребата на неща, които не са взети, защото е възможно да се таксуват на контролно/изпит. 13 | class Triangle { 14 | public: 15 | int x1, y1, x2, y2, x3, y3; 16 | 17 | Triangle(int x1, int y1, int x2, int y2, int x3, int y3) 18 | : x1(x1), y1(y1), x2(x2), y2(y2), x3(x3), y3(y3) { 19 | } 20 | 21 | double area() const { 22 | return abs(x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0; 23 | } 24 | }; 25 | 26 | int main() { 27 | int N; 28 | cin >> N; 29 | // Нямаш валидация за N. 30 | // Какво ще стане ако въведа отрицателно число? 31 | vector triangles; 32 | 33 | for (int i = 0; i < N; i++) { 34 | int x1, y1, x2, y2, x3, y3; 35 | cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3; 36 | triangles.push_back(Triangle(x1, y1, x2, y2, x3, y3)); 37 | } 38 | 39 | // По условие се искаше да направите и сортирате ТРИЪГЪЛНИЦИ спрямо лицата им, а не само лицата им. 40 | // Това е същото като да ти дам за задача да сортираш шишета на рафт спрямо височината им и ти се върнеш с един лист, 41 | // на който си написал височините в сортиран ред. Реално заобикаляш проблема. 42 | // За такива уточнения на контролно и изпит е напълно възможно да ти се анулира задачата, защото не е по условието. 43 | vector areas; 44 | // auto ви е строго забранена ключова дума! 45 | for (const auto& t : triangles) { 46 | areas.push_back(t.area()); 47 | } 48 | 49 | sort(areas.begin(), areas.end()); 50 | 51 | for (size_t i = 0; i < areas.size(); i++) { 52 | cout << areas[i]; 53 | if (i != areas.size() - 1) cout << " "; 54 | } 55 | 56 | return 0; 57 | } 58 | -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Nikol_Bonjolova_1MI0400376/hm2.cpp: -------------------------------------------------------------------------------- 1 | // Същите забележки както на 1ва задача. 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | struct QuadraticEquation { 9 | double a, b, c; 10 | 11 | QuadraticEquation(double a, double b, double c) : a(a), b(b), c(c) {} 12 | 13 | void solve() { 14 | double discriminant = b * b - 4 * a * c; 15 | 16 | if (discriminant < 0) { 17 | cout << "The equation does not have real solutions!" << endl; 18 | } 19 | else if (discriminant == 0) { 20 | double x = -b / (2 * a); 21 | cout << "x1 = x2 = " << fixed << setprecision(6) << x << endl; 22 | } 23 | else { 24 | double x1 = (-b + sqrt(discriminant)) / (2 * a); 25 | double x2 = (-b - sqrt(discriminant)) / (2 * a); 26 | if (x1 > x2) swap(x1, x2); 27 | cout << "x1 = " << fixed << setprecision(6) << x1 << ", x2 = " << fixed << setprecision(6) << x2 << endl; 28 | } 29 | } 30 | }; 31 | 32 | int main() { 33 | double a, b, c; 34 | cin >> a >> b >> c; 35 | 36 | QuadraticEquation eq(a, b, c); 37 | eq.solve(); 38 | 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Nikol_Bonjolova_1MI0400376/hm3.cpp: -------------------------------------------------------------------------------- 1 | // Същите забележки както на първа задача. 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | struct ComplexNumber { 8 | int real, imag; 9 | 10 | ComplexNumber(int real, int imag) : real(real), imag(imag) {} 11 | 12 | ComplexNumber operator+(const ComplexNumber& other) const { 13 | return ComplexNumber(real + other.real, imag + other.imag); 14 | } 15 | 16 | ComplexNumber operator-(const ComplexNumber& other) const { 17 | return ComplexNumber(real - other.real, imag - other.imag); 18 | } 19 | 20 | ComplexNumber operator*(const ComplexNumber& other) const { 21 | return ComplexNumber(real * other.real - imag * other.imag, real * other.imag + imag * other.real); 22 | } 23 | 24 | void print() const { 25 | if (imag >= 0) 26 | cout << real << "+" << imag << "i"; 27 | else 28 | cout << real << "" << imag << "i"; 29 | } 30 | }; 31 | 32 | int main() { 33 | int a, b, c, d; 34 | cin >> a >> b >> c >> d; 35 | 36 | ComplexNumber z1(a, b), z2(c, d); 37 | 38 | ComplexNumber sum = z1 + z2; 39 | ComplexNumber diff = z1 - z2; 40 | ComplexNumber prod = z1 * z2; 41 | 42 | sum.print(); 43 | cout << endl; 44 | diff.print(); 45 | cout << endl; 46 | prod.print(); 47 | cout << endl; 48 | 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Nikol_Bonjolova_1MI0400376/hm4.cpp: -------------------------------------------------------------------------------- 1 | // Същите забележки както на първа задача. 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | struct Student { 9 | int facultyNumber; 10 | int year; 11 | double averageGrade; 12 | 13 | Student(int facultyNumber, int year, double averageGrade) 14 | : facultyNumber(facultyNumber), year(year), averageGrade(averageGrade) { 15 | } 16 | }; 17 | 18 | struct Group { 19 | vector students; 20 | 21 | double averageGrade() const { 22 | double sum = 0; 23 | for (const auto& student : students) { 24 | sum += student.averageGrade; 25 | } 26 | return sum / students.size(); 27 | } 28 | 29 | int countScholarship(double minGrade) const { 30 | int count = 0; 31 | for (const auto& student : students) { 32 | if (student.averageGrade >= minGrade) { 33 | count++; 34 | } 35 | } 36 | return count; 37 | } 38 | }; 39 | 40 | int main() { 41 | int N; 42 | cin >> N; 43 | 44 | Group group; 45 | for (int i = 0; i < N; i++) { 46 | int facultyNumber, year; 47 | double averageGrade; 48 | cin >> facultyNumber >> year >> averageGrade; 49 | group.students.push_back(Student(facultyNumber, year, averageGrade)); 50 | } 51 | 52 | double minGrade; 53 | cin >> minGrade; 54 | 55 | cout << fixed << setprecision(4) << group.averageGrade() << " " << group.countScholarship(minGrade) << endl; 56 | 57 | return 0; 58 | } 59 | -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Nikolai_Nejkov_9MI0400310/Task 1/main.cpp: -------------------------------------------------------------------------------- 1 | // Добре разписана задача 2 | #include 3 | #include "triangle.hpp" 4 | 5 | int validateInput() { 6 | int n; 7 | std::cout << "Enter the number of triangles." << std::endl; 8 | std::cout << "N = "; 9 | std::cin >> n; 10 | 11 | while (n < 1 || n > 1000) { 12 | std::cout << "Input must be in range 1 <= N <= 1000" << std::endl; 13 | std::cout << "N = "; 14 | std::cin >> n; 15 | } 16 | 17 | return n; 18 | } 19 | 20 | int main() { 21 | int n = validateInput(); 22 | Triangle* triangles = new (std::nothrow) Triangle[n]; 23 | 24 | if (!triangles) { 25 | std::cout << "Memory allocation error!" << std::endl; 26 | return 1; 27 | } 28 | 29 | for (int i = 0; i < n; i++) { 30 | std::cout << "Triangle " << i + 1 << std::endl; 31 | triangleBuilder(triangles[i]); 32 | } 33 | 34 | for (int i = 0; i < n - 1; i++) { 35 | bool flag = false; 36 | for (int j = 0; j < n - i - 1; j++) { 37 | if (triangles[j].area > triangles[j + 1].area) { 38 | Triangle temp = triangles[j]; 39 | triangles[j] = triangles[j + 1]; 40 | triangles[j + 1] = temp; 41 | 42 | flag = true; 43 | } 44 | } 45 | 46 | if (!flag) { 47 | break; 48 | } 49 | } 50 | 51 | for (int i = 0; i < n; i++) { 52 | std::cout << triangles[i].area << std::endl; 53 | } 54 | 55 | delete[] triangles; 56 | return 0; 57 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Nikolai_Nejkov_9MI0400310/Task 1/triangle.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "triangle.hpp" 4 | 5 | double twoDotsDistance(double Ax, double Ay, double Bx, double By) { 6 | return sqrt((Ax - Bx) * (Ax - Bx) + (Ay - By) * (Ay - By)); 7 | }; 8 | 9 | void triangleArea(Triangle& triangle) { 10 | double a = twoDotsDistance(triangle.Bx, triangle.By, triangle.Cx, triangle.Cy); 11 | double b = twoDotsDistance(triangle.Ax, triangle.Ay, triangle.Cx, triangle.Cy); 12 | double c = twoDotsDistance(triangle.Ax, triangle.Ay, triangle.Bx, triangle.By); 13 | 14 | //std::cout << a << std::endl; 15 | //std::cout << b << std::endl; 16 | //std::cout << c << std::endl; 17 | 18 | 19 | if (a + b <= c || a + c <= b || b + c <= a) { 20 | std::cout << "Invalid triangle coordinates" << std::endl; 21 | triangle.area = -1; 22 | return; 23 | } 24 | 25 | double p = (a + b + c) / 2; 26 | double area = sqrt(p * (p - a) * (p - b) * (p - c)); 27 | //area = std::round(area * 1000) / 1000; 28 | triangle.area = area; 29 | }; 30 | 31 | double validateCoordinates(const char name[3]) { 32 | double temp = -1; 33 | std::cout << name << ": "; 34 | std::cin >> temp; 35 | 36 | while (temp < -100 || temp > 100) { 37 | std::cout << "Invalid input! Try again!" << std::endl; 38 | std::cout << name << ": "; 39 | std::cin >> temp; 40 | } 41 | 42 | return temp; 43 | } 44 | 45 | void triangleBuilder(Triangle& triangle) { 46 | std::cout << "Enter the coordinates of the triangle's dots.\nConstraints: -100 <= xi, yi <= 100" << std::endl; 47 | triangle.Ax = validateCoordinates("Ax"); 48 | triangle.Ay = validateCoordinates("Ay"); 49 | triangle.Bx = validateCoordinates("Bx"); 50 | triangle.By = validateCoordinates("By"); 51 | triangle.Cx = validateCoordinates("Cx"); 52 | triangle.Cy = validateCoordinates("Cy"); 53 | 54 | triangleArea(triangle); 55 | }; 56 | -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Nikolai_Nejkov_9MI0400310/Task 1/triangle.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | // Защо просто не направи още една структура Point, която да пази отделните координати? 4 | struct Triangle { 5 | double Ax = 0; 6 | double Ay = 0; 7 | double Bx = 0; 8 | double By = 0; 9 | double Cx = 0; 10 | double Cy = 0; 11 | double area = 0; 12 | }; 13 | 14 | void triangleArea(Triangle& triangle); 15 | 16 | double twoDotsDistance(double Ax, double Ay, double Bx, double By); 17 | 18 | void triangleBuilder(Triangle& triangle); -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Nikolai_Nejkov_9MI0400310/Task 2/main.cpp: -------------------------------------------------------------------------------- 1 | // Добре разписана задача 2 | #include 3 | #include 4 | #define e 0.0001 //I wanted to use ε but idk if it will compile on other PCs :/ 5 | 6 | struct Equation { 7 | double a = 0; 8 | double b = 0; 9 | double c = 0; 10 | }; 11 | 12 | double validateInput(char parameter) { 13 | double temp; 14 | std::cout << parameter << ": "; 15 | std::cin >> temp; 16 | while (temp < -100 || temp > 100) { 17 | std::cout << "Parameter must be in range -100 <= param <= 100" << std::endl; 18 | std::cout << parameter << ": "; 19 | std::cin >> temp; 20 | } 21 | 22 | return temp; 23 | } 24 | 25 | void findRoots(Equation& equation) { 26 | double d = equation.b * equation.b - 4 * equation.a * equation.c; 27 | if (d < 0) { 28 | std::cout << "The equation does not have real solutions!" << std::endl; 29 | return; 30 | } 31 | double x1 = (-1 * equation.b + sqrt(d)) / (2 * equation.a); 32 | double x2 = (-1 * equation.b - sqrt(d)) / (2 * equation.a); 33 | 34 | if (d - 0 < e) { 35 | std::cout << "x1 = x2 = " << x1 << std::endl; 36 | return; 37 | } 38 | 39 | if (x1 > x2) { 40 | x1 += x2; 41 | x2 = x1 - x2; 42 | x1 -= x2; 43 | } 44 | std::cout << "x1 = " << x1 << ", x2 = " << x2 << std::endl; 45 | } 46 | 47 | int main() { 48 | double a = validateInput('a'); 49 | double b = validateInput('b'); 50 | double c = validateInput('c'); 51 | 52 | Equation eqution = { a, b, c }; 53 | findRoots(eqution); 54 | 55 | return 0; 56 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Petar_Angelov_5MI0700079/task1.cpp: -------------------------------------------------------------------------------- 1 | // STL библиотеки(като vector и algorithm) са ви забранени за използване, 2 | // освен ако не ви е казано изрично, че можете. 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | // Този ред е много лоша практика! 9 | using namespace std; 10 | 11 | double triangleArea(int x1, int y1, int x2, int y2, int x3, int y3) { 12 | return fabs(x1*(y2-y3) + x2*(y3-y1) + x3*(y1-y2)) / 2.0; 13 | } 14 | 15 | int main(){ 16 | int n; 17 | cin >> n; 18 | // Нямаш валидация за n. 19 | // Какво става ако въведа отрицателно число? 20 | 21 | 22 | // По условие се искаше да направите и сортирате ТРИЪГЪЛНИЦИ спрямо лицата им, а не само лицата им. 23 | // Това е същото като да ти дам за задача да сортираш шишета на рафт спрямо височината им и ти се върнеш с един лист, 24 | // на който си написал височините в сортиран ред. Реално заобикаляш проблема. 25 | // За такива уточнения на контролно и изпит е напълно възможно да ти се анулира задачата, защото не е по условието. 26 | vector areas(n); 27 | for (int i = 0; i < n; i++){ 28 | int x1, y1, x2, y2, x3, y3; 29 | cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3; 30 | areas[i] = triangleArea(x1, y1, x2, y2, x3, y3); 31 | } 32 | sort(areas.begin(), areas.end()); 33 | for (int i = 0; i < n; i++){ 34 | cout << areas[i]; 35 | if(i < n-1) cout << " "; 36 | } 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Petar_Angelov_5MI0700079/task2.cpp: -------------------------------------------------------------------------------- 1 | // Същите забележки като първа задача! 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | struct Quadratic { 7 | double a, b, c; 8 | }; 9 | 10 | int main(){ 11 | Quadratic eq; 12 | cin >> eq.a >> eq.b >> eq.c; 13 | // Можеш да разделиш кода си по функции, за да е малко по-разбираемо какво правиш, 14 | // вместо всичко да е в main функцията. 15 | double discriminant = eq.b * eq.b - 4 * eq.a * eq.c; 16 | if(discriminant < 0) { 17 | cout << "The equation does not have real solutions!"; 18 | } else if(discriminant == 0) { 19 | double root = -eq.b / (2 * eq.a); 20 | cout << "x1 = x2 = " << root; 21 | } else { 22 | double sqrtD = sqrt(discriminant); 23 | double x1 = (-eq.b - sqrtD) / (2 * eq.a); 24 | double x2 = (-eq.b + sqrtD) / (2 * eq.a); 25 | if(x1 > x2) std::swap(x1, x2); 26 | cout << "x1 = " << x1 << ", x2 = " << x2; 27 | } 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Petar_Angelov_5MI0700079/task3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | // Този ред е много лоша практика! 3 | using namespace std; 4 | 5 | struct Complex { 6 | int real; 7 | int imag; 8 | }; 9 | 10 | Complex add(const Complex &z1, const Complex &z2) { 11 | return {z1.real + z2.real, z1.imag + z2.imag}; 12 | } 13 | 14 | Complex subtract(const Complex &z1, const Complex &z2) { 15 | return {z1.real - z2.real, z1.imag - z2.imag}; 16 | } 17 | 18 | Complex multiply(const Complex &z1, const Complex &z2) { 19 | return {z1.real * z2.real - z1.imag * z2.imag, z1.real * z2.imag + z1.imag * z2.real}; 20 | } 21 | 22 | void printComplex(const Complex &z) { 23 | if(z.real == 0 && z.imag == 0) { 24 | cout << "0"; 25 | } else if(z.imag == 0) { 26 | cout << z.real; 27 | } else if(z.real == 0) { 28 | if(z.imag == 1) 29 | cout << "i"; 30 | else if(z.imag == -1) 31 | cout << "-i"; 32 | else 33 | cout << z.imag << "i"; 34 | } else { 35 | cout << z.real; 36 | if(z.imag > 0) 37 | cout << "+" << (z.imag == 1 ? "i" : to_string(z.imag) + "i"); 38 | else 39 | cout << (z.imag == -1 ? "-i" : to_string(z.imag) + "i"); 40 | } 41 | } 42 | 43 | int main(){ 44 | Complex z1, z2; 45 | cin >> z1.real >> z1.imag >> z2.real >> z2.imag; 46 | Complex sum = add(z1, z2); 47 | Complex diff = subtract(z1, z2); 48 | Complex prod = multiply(z1, z2); 49 | printComplex(sum); 50 | cout << "\n"; 51 | printComplex(diff); 52 | cout << "\n"; 53 | printComplex(prod); 54 | return 0; 55 | } 56 | -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Petar_Angelov_5MI0700079/task4.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | // Този ред е много лоша практика! 4 | using namespace std; 5 | 6 | struct Student { 7 | int facNum; 8 | int course; 9 | double grade; 10 | }; 11 | 12 | struct Group { 13 | Student* students; 14 | int count; 15 | double avgGrade; 16 | }; 17 | 18 | void initStudent(Student &s) { 19 | cin >> s.facNum >> s.course >> s.grade; 20 | } 21 | 22 | int countScholarship(const Group &g, double minGrade) { 23 | int count = 0; 24 | for (int i = 0; i < g.count; i++){ 25 | if(g.students[i].grade >= minGrade) 26 | count++; 27 | } 28 | return count; 29 | } 30 | 31 | int main(){ 32 | int n; 33 | cin >> n; 34 | // Нямаш валидация за n. 35 | // Какво ще стане ако въведа отрицателно число? 36 | Group group; 37 | group.count = n; 38 | // Липсва ти std::nothrow като аргумент на оператора new. 39 | // Това потенциално може да доведе до crash в програмата ти и се счита за сериозна грешка! 40 | group.students = new Student[n]; 41 | // Нямаш валидация за това дали масивът се е заделил коректно, отново се счита за голяма грешка. 42 | double sum = 0; 43 | for (int i = 0; i < n; i++){ 44 | initStudent(group.students[i]); 45 | sum += group.students[i].grade; 46 | } 47 | group.avgGrade = sum / n; 48 | double minGrade; 49 | cin >> minGrade; 50 | int scholarshipCount = countScholarship(group, minGrade); 51 | cout << fixed << setprecision(4) << group.avgGrade << " " << scholarshipCount; 52 | delete[] group.students; 53 | return 0; 54 | } 55 | -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Stoyan_Georgiev_9MI0400349/zad_2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | // Липсва библиотеката cmath 3 | 4 | // Този ред е лоша практика! 5 | using namespace std; 6 | 7 | // Тази структура би следвало да се казва Equation 8 | // или нещо от този род, а не Points! 9 | // Също така трябваше да ползваме реални числа(float/double) по условие. 10 | struct Points{ 11 | int x; 12 | int y; 13 | int z; 14 | }; 15 | 16 | //function to calculate the result 17 | void calculateResult(int x, int y, int z){ 18 | int result = 0; 19 | int d = 0; 20 | 21 | d = pow(y,2) - 4*x*z; 22 | 23 | if (d < 0){ 24 | cout<< "There are no real roots" << endl; 25 | 26 | } else if (d == 0){ 27 | cout << "There is one real root (x1 = x2)" << endl; 28 | result = -y / (2*x); 29 | cout << "The root is: " << result << endl; 30 | 31 | } else{ 32 | cout << "There are two real roots" << endl; 33 | result = (-y + sqrt(d)) / (2*x); 34 | cout << "The first root is (x1): " << result << endl; 35 | result = (-y - sqrt(d)) / (2*x); 36 | cout << "The second root is (x2): " << result << endl; 37 | } 38 | } 39 | 40 | int main(){ 41 | 42 | // enter the number of points 43 | Points Points; 44 | cin >> Points.x >> Points.y >> Points.z; 45 | 46 | calculateResult(Points.x, Points.y, Points.z); 47 | 48 | 49 | 50 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Stoyan_Georgiev_9MI0400349/zad_3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // Този ред е лоша практика! 4 | using namespace std; 5 | 6 | // Това е грешна структура. 7 | // Комплексно число се описва от реална и имагинерна част, което са 2 числа, а не 4! 8 | struct ComplexNumbers{ 9 | int a, b ,c ,d; 10 | }; 11 | 12 | //function to enter the complex number 13 | void enterComplexNumber(ComplexNumbers &number){ 14 | cin >> number.a >> number.b; 15 | cin >> number.c >> number.d; 16 | } 17 | 18 | // Следващите 3 функции следва да имат функционалността да направят 19 | // действие върху 2 комплексни числа и да върнат резултат, който е ново комплексно число. 20 | //function to add the complex numbers 21 | void addComplexNumbers(ComplexNumbers number){ 22 | int real = number.a + number.c; 23 | int imaginary = number.b + number.d; 24 | 25 | if (real == 0) cout << imaginary << "i" << endl; 26 | else if (imaginary == 0) cout << real << endl; 27 | else cout << real << " + " << imaginary << "i" << endl; 28 | } 29 | 30 | //function to subtract the complex numbers 31 | void subtractComplexNumbers(ComplexNumbers number){ 32 | int real = number.a - number.c; 33 | int imaginary = number.b - number.d; 34 | 35 | if (real == 0) cout << imaginary << "i" << endl; 36 | else if (imaginary == 0) cout << real << endl; 37 | else cout << real << " + " << imaginary << "i" << endl; 38 | } 39 | 40 | //function to multiply the complex numbers 41 | void multiplyComplexNumbers(ComplexNumbers number){ 42 | int real = (number.a * number.c) - (number.b * number.d); 43 | int imaginary = (number.a * number.d) + (number.b * number.c); 44 | 45 | if (real == 0) cout << imaginary << "i" << endl; 46 | else if (imaginary == 0) cout << real << endl; 47 | else cout << real << " + " << imaginary << "i" << endl; 48 | } 49 | 50 | 51 | int main(){ 52 | ComplexNumbers number; 53 | 54 | enterComplexNumber(number); 55 | 56 | addComplexNumbers(number); 57 | subtractComplexNumbers(number); 58 | multiplyComplexNumbers(number); 59 | 60 | return 0; 61 | } 62 | -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Veronika_Nikolova_9MI0400234/ex2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // Отново това е лоша практика 5 | using namespace std; 6 | 7 | struct QuadraticEquation { 8 | double a, b, c; 9 | 10 | double discriminant() const{ 11 | return pow(b, 2) - 4*a*c; 12 | } 13 | 14 | void findRoots() { 15 | double d = discriminant(); 16 | if(d > 0) { 17 | double x1 = (-b - sqrt(d))/(2*a); 18 | double x2 = (-b + sqrt(d))/(2*a); 19 | std::cout << "x1 = " << x1 << " x2 = " << x2 << endl; 20 | } else if (d == 0){ 21 | double x = -b/(2*a); 22 | std::cout << "x1 = x2 = " << x << endl; 23 | } else { 24 | std::cout << "The equation does not have real solutions!" << endl; 25 | } 26 | } 27 | }; 28 | 29 | 30 | 31 | 32 | 33 | int main() { 34 | double a, b, c; 35 | std::cin >> a >> b >> c; 36 | 37 | QuadraticEquation eq = {a, b, c}; 38 | eq.findRoots(); 39 | return 0; 40 | 41 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Veronika_Nikolova_9MI0400234/ex3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // Лоша практика! 5 | using namespace std; 6 | 7 | 8 | struct ComplexNum { 9 | double real; 10 | double imag; 11 | 12 | void print() const{ 13 | if (imag >= 0) 14 | { 15 | // Защо на едно място го пишеш с std:: на друго без. 16 | // Изглежда неконсистентно и объркващо на моменти. 17 | std::cout << real << " + " << imag << "i" << endl; 18 | } 19 | else 20 | { 21 | std::cout << real << " - " << imag << "i" << endl; 22 | } 23 | } 24 | }; 25 | 26 | ComplexNum multiply(const ComplexNum& a, const ComplexNum& b) { 27 | return {a.real * b.real - a.imag * b.imag, a.real * b.imag + a.imag * b.real}; 28 | } 29 | 30 | ComplexNum addition(const ComplexNum& a, const ComplexNum& b) { 31 | return {a.real + b.real, a.imag + b.imag}; 32 | } 33 | 34 | ComplexNum substract(const ComplexNum& a, const ComplexNum& b) { 35 | return {a.real - b.real, a.imag - b.imag}; 36 | } 37 | 38 | ComplexNum read() { 39 | ComplexNum number; 40 | std::cin >> number.real; 41 | std::cin >> number.imag; 42 | return number; 43 | } 44 | 45 | int main() { 46 | ComplexNum number1 = read(); 47 | ComplexNum number2 = read(); 48 | 49 | ComplexNum sum = addition(number1, number2); 50 | sum.print(); 51 | 52 | ComplexNum difference = substract(number1, number2); 53 | difference.print(); 54 | 55 | ComplexNum product = multiply(number1, number2); 56 | product.print(); 57 | 58 | return 0; 59 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Yasen_Rusinov_5MI0400328/02.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Equation { 5 | double a; 6 | double b; 7 | double c; 8 | }; 9 | 10 | double findDiscriminant(const Equation &equation){ 11 | return pow(equation.b, 2) - 4 * equation.a * equation.c; 12 | } 13 | 14 | void calculateRoots(Equation equation, double &x1, double &x2, const double &D){ 15 | x1 = (-equation.b + sqrt(D)) / (2 * equation.a); 16 | x2 = (-equation.b - sqrt(D)) / (2 * equation.a); 17 | } 18 | 19 | void calculateRootsD0(Equation equation, double &x1, double &x2, const double &D){ 20 | x1 = (-equation.b) / (2 * equation.a); 21 | x2 = (-equation.b) / (2 * equation.a); 22 | } 23 | 24 | int main(){ 25 | Equation equation; 26 | std::cin >> equation.a; 27 | if (equation.a > 100 || equation.a < -100) { 28 | std::cout << "All coefficients must be between -100 and 100." << std::endl; 29 | return 0; 30 | } 31 | std::cin >> equation.b; 32 | if (equation.b > 100 || equation.b < -100) { 33 | std::cout << "All coefficients must be between -100 and 100." << std::endl; 34 | return 0; 35 | } 36 | std::cin >> equation.c; 37 | if (equation.c > 100 || equation.c < -100) { 38 | std::cout << "All coefficients must be between -100 and 100." << std::endl; 39 | return 0; 40 | } 41 | 42 | double x1, x2 = 0; 43 | double D = findDiscriminant(equation); 44 | 45 | if (D < 0) { 46 | std::cout << "This equation has no real roots." << std::endl; 47 | return 0; 48 | } 49 | else if (D == 0) { 50 | calculateRootsD0(equation, x1, x2, D); 51 | std::cout << "x1 = x2 = " << x1 << std::endl; 52 | } 53 | else if (D > 0) { 54 | calculateRoots(equation, x1, x2, D); 55 | std::cout << "x1 = " << x1 << ", x2 = " << x2 << std::endl; 56 | } 57 | 58 | return 0; 59 | } 60 | -------------------------------------------------------------------------------- /Seminar/Week 01/Reviews/Yasen_Rusinov_5MI0400328/03.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // Това е грешна структура! 4 | // Първо, би било логично да се казва ComplexNumber. 5 | // Второ, едно комплексно число се описва от реална и имагинерна част, 6 | // което е 2 числа, а не 4! 7 | struct Imag { 8 | int a; 9 | int b; 10 | int c; 11 | int d; 12 | }; 13 | 14 | // Константна референция!!! 15 | // Липсват скоби също така! 16 | // Тези функции би следвало да взимат две комплексни числа и да връщат 17 | // ново комплексно число, което е резултатът от операцията!! 18 | void addition(Imag &number) 19 | std::cout << number.a + number.c << "+" << number.b + number.d << "i" << std::endl; 20 | } 21 | void subtraction(Imag &number) 22 | std::cout << number.a - number.c << "+" << number.b - number.d << "i" << std::endl; 23 | } 24 | void multiplication(Imag &number) 25 | std::cout << number.a * number.c - number.b * number.d << "+" << number.a * number.d + number.b * number.c << "i" << std::endl; 26 | } 27 | 28 | int main(){ 29 | Imag number; 30 | std::cin >> number.a; 31 | if (!(-1000 <= number.a <= 1000)) { 32 | std::cout << "All coefficient must be between -1000 and 1000." << std::endl; 33 | return 1; 34 | } 35 | std::cin >> number.b; 36 | if (!(-1000 <= number.b <= 1000)) { 37 | std::cout << "All coefficient must be between -1000 and 1000." << std::endl; 38 | return 1; 39 | } 40 | std::cin >> number.c; 41 | if (!(-1000 <= number.c <= 1000)) { 42 | std::cout << "All coefficient must be between -1000 and 1000." << std::endl; 43 | return 1; 44 | } 45 | std::cin >> number.d; 46 | if (!(-1000 <= number.d <= 1000)) { 47 | std::cout << "All coefficient must be between -1000 and 1000." << std::endl; 48 | return 1; 49 | } 50 | 51 | addition(number); 52 | subtraction(number); 53 | multiplication(number); 54 | 55 | return 0; 56 | } 57 | -------------------------------------------------------------------------------- /Seminar/Week 01/Solutions/Task1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | struct Point{ 6 | double x, y; 7 | }; 8 | 9 | struct Triangle{ 10 | Point A, B, C; 11 | double area; 12 | }; 13 | 14 | double FindDistance(Point const &A, Point const &B){ 15 | return sqrt((A.x - B.x) * (A.x - B.x) + (A.y - B.y) * (A.y - B.y)); 16 | } 17 | 18 | void FindArea(Triangle &trie){ 19 | trie.area = std::abs((trie.A.x * (trie.B.y - trie.C.y) + trie.B.x * (trie.C.y - trie.A.y) + trie.C.x * (trie.A.y - trie.B.y)) / 2.0); 20 | } 21 | 22 | void Sort(Triangle *tries, size_t const size){ 23 | 24 | for(size_t i = 0; i < size - 1; ++i){ 25 | 26 | size_t minIndex = i; 27 | 28 | for(size_t j = i + 1; j < size; ++j) 29 | if(tries[i].area > tries[j].area) 30 | minIndex = j; 31 | 32 | if(i != minIndex) std::swap(tries[i], tries[minIndex]); 33 | 34 | } 35 | 36 | } 37 | 38 | int main(){ 39 | 40 | size_t n; 41 | std::cin >> n; 42 | 43 | Triangle *tries = new(std::nothrow) Triangle[n]; 44 | if(!tries){ 45 | 46 | std::cout << "Memory error\n"; 47 | return -1; 48 | 49 | } 50 | 51 | for(size_t i = 0; i < n; ++i){ 52 | 53 | std::cin >> tries[i].A.x >> tries[i].A.y 54 | >> tries[i].B.x >> tries[i].B.y 55 | >> tries[i].C.x >> tries[i].C.y; 56 | FindArea(tries[i]); 57 | 58 | } 59 | 60 | Sort(tries, n); 61 | 62 | for(size_t i = 0; i < n; ++i) 63 | std::cout << tries[i].area << ' '; 64 | std::cout << '\n'; 65 | 66 | delete[] tries; 67 | 68 | return 0; 69 | 70 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Solutions/Task2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | size_t const UINT64_MAX_VALUE = UINT64_MAX; 7 | double const NAN_CASTED = *(double *)&UINT64_MAX_VALUE; 8 | 9 | struct Quadratic{ 10 | double a, b, c, d, x1, x2; 11 | }; 12 | 13 | void FindDiscriminant(Quadratic &equation){ 14 | equation.d = equation.b * equation.b - 4 * equation.a * equation.c; 15 | } 16 | 17 | void Solve(Quadratic &equation){ 18 | 19 | if(equation.d < 0) equation.x1 = equation.x2 = NAN_CASTED; 20 | else if(equation.d == 0) equation.x1 = equation.x2 = -equation.b / (2 * equation.a); 21 | else{ 22 | 23 | equation.x1 = (-equation.b - sqrt(equation.d)) / (2 * equation.a); 24 | equation.x2 = (-equation.b + sqrt(equation.d)) / (2 * equation.a); 25 | 26 | if(equation.x1 > equation.x2) std::swap(equation.x1, equation.x2); 27 | 28 | } 29 | 30 | } 31 | 32 | int main(){ 33 | 34 | Quadratic equation; 35 | 36 | std::cin >> equation.a >> equation.b >> equation.c; 37 | 38 | FindDiscriminant(equation); 39 | Solve(equation); 40 | 41 | if(equation.x1 == NAN_CASTED) std::cout << "The equation does not have real solutions!\n"; 42 | else if(equation.x1 == equation.x2) std::cout << "x1 = x2 = " << equation.x1 << '\n'; 43 | else std::cout << "x1 = " << equation.x1 << ", x2 = " << equation.x2 << '\n'; 44 | 45 | return 0; 46 | 47 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Solutions/Task3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct Complex{ 4 | int real, imag; 5 | }; 6 | 7 | Complex add(Complex const a, Complex const b){ 8 | 9 | Complex result; 10 | 11 | result.real = a.real + b.real; 12 | result.imag = a.imag + b.imag; 13 | 14 | return result; 15 | 16 | } 17 | 18 | Complex subtract(Complex const a, Complex const b){ 19 | 20 | Complex result; 21 | 22 | result.real = a.real - b.real; 23 | result.imag = a.imag - b.imag; 24 | 25 | return result; 26 | 27 | } 28 | 29 | Complex multiply(Complex const a, Complex const b){ 30 | 31 | Complex result; 32 | 33 | result.real = a.real * b.real - a.imag * b.imag; 34 | result.imag = a.real * b.imag + b.real * a.imag; 35 | 36 | return result; 37 | 38 | } 39 | 40 | void print(Complex const a){ 41 | 42 | if(a.real) std::cout << a.real; 43 | if(a.imag > 0) std::cout << '+'; 44 | if(a.imag != 0) std::cout << a.imag << 'i'; 45 | std::cout << '\n'; 46 | 47 | } 48 | 49 | int main(){ 50 | 51 | Complex a, b; 52 | 53 | std::cin >> a.real >> a.imag >> b.real >> b.imag; 54 | 55 | print(add(a, b)); 56 | print(subtract(a, b)); 57 | print(multiply(a, b)); 58 | 59 | return 0; 60 | 61 | } -------------------------------------------------------------------------------- /Seminar/Week 01/Solutions/Task4.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct Student{ 4 | 5 | int fn, course; 6 | double grade; 7 | 8 | }; 9 | 10 | struct Group{ 11 | 12 | Student *students; 13 | size_t size; 14 | double avgGrade; 15 | 16 | }; 17 | 18 | Student InitStudent(const int &fn, const int &course, const double &grade){ 19 | 20 | Student newStudent; 21 | 22 | newStudent.fn = fn; 23 | newStudent.course = course; 24 | newStudent.grade = grade; 25 | 26 | return newStudent; 27 | 28 | } 29 | 30 | void FindAverage(Group &myGroup){ 31 | 32 | for(size_t i = 0; i < myGroup.size; ++i) 33 | myGroup.avgGrade += myGroup.students[i].grade; 34 | 35 | myGroup.avgGrade /= myGroup.size; 36 | 37 | } 38 | 39 | size_t FindMoreThanAvg(const Group &myGroup){ 40 | 41 | size_t counter = 0; 42 | 43 | for(size_t i = 0; i < myGroup.size; ++i) 44 | counter += myGroup.students[i].grade >= myGroup.avgGrade; 45 | 46 | return counter; 47 | 48 | } 49 | 50 | int main(){ 51 | 52 | Group myGroup; 53 | std::cin >> myGroup.size; 54 | myGroup.students = new(std::nothrow) Student[myGroup.size]; 55 | 56 | if(!myGroup.students){ 57 | 58 | std::cout << "Memory error\n"; 59 | return -1; 60 | 61 | } 62 | 63 | int fn, course; 64 | double grade; 65 | 66 | for(size_t i = 0; i < myGroup.size; ++i){ 67 | 68 | std::cin >> fn >> course >> grade; 69 | myGroup.students[i] = InitStudent(fn, course, grade); 70 | 71 | } 72 | 73 | std::cin >> grade; 74 | 75 | FindAverage(myGroup); 76 | 77 | std::cout << myGroup.avgGrade << ' ' << FindMoreThanAvg(myGroup) << '\n'; 78 | 79 | delete[] myGroup.students; 80 | 81 | return 0; 82 | 83 | } -------------------------------------------------------------------------------- /Seminar/Week 02/Example problems/Task1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void PrintCurrentFile(){ 5 | 6 | std::ifstream ifs("test.cpp"); 7 | 8 | if(!ifs.is_open()) return; 9 | 10 | while(!ifs.eof()){ 11 | 12 | char c = ifs.get(); 13 | 14 | std::cout << c; 15 | 16 | } 17 | 18 | ifs.close(); 19 | 20 | } 21 | 22 | int main(){ 23 | 24 | PrintCurrentFile(); 25 | return 0; 26 | 27 | } -------------------------------------------------------------------------------- /Seminar/Week 02/Example problems/Task2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void CopyFile(char const *from, char const *to){ 5 | 6 | std::ifstream ifs(from); 7 | if(!ifs.is_open()) return; 8 | 9 | std::ofstream ofs(to, std::ios::trunc); 10 | if(!ofs.is_open()){ 11 | 12 | ifs.close(); 13 | return; 14 | 15 | } 16 | 17 | while(!ifs.eof()){ 18 | 19 | char c = ifs.get(); 20 | ofs << c; 21 | 22 | } 23 | 24 | ifs.close(); 25 | ofs.close(); 26 | 27 | } 28 | 29 | int main(){ 30 | 31 | CopyFile("test.cpp", "otherTest.cpp"); 32 | return 0; 33 | 34 | } -------------------------------------------------------------------------------- /Seminar/Week 02/Example problems/Task3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | size_t SizeOfFile(std::ifstream &f){ 6 | 7 | size_t position = f.tellg(); 8 | 9 | f.seekg(0, std::ios::end); 10 | size_t size = f.tellg(); 11 | f.seekg(position); 12 | 13 | return size; 14 | 15 | } 16 | 17 | int main(){ 18 | 19 | std::ifstream ifs("test.txt"); 20 | std::cout << SizeOfFile(ifs) << '\n'; 21 | return 0; 22 | 23 | } -------------------------------------------------------------------------------- /Seminar/Week 02/Example problems/Task4.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(){ 5 | 6 | std::ifstream ifs("test.txt"); 7 | if(!ifs.is_open()) return -1; 8 | 9 | std::ofstream ofs("result.txt"); 10 | if(!ofs.is_open()){ 11 | 12 | ifs.close(); 13 | return -1; 14 | 15 | } 16 | 17 | char from, to; 18 | std::cin >> from >> to; 19 | 20 | while(!ifs.eof()){ 21 | 22 | char c = ifs.get(); 23 | if(c == from) c = to; 24 | ofs << c; 25 | 26 | } 27 | 28 | ifs.close(); 29 | ofs.close(); 30 | 31 | return 0; 32 | 33 | } -------------------------------------------------------------------------------- /Seminar/Week 02/Examples for binary files/array_of_students_read.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | struct Student{ 6 | 7 | char name[24]; 8 | int age; 9 | int fn; 10 | 11 | }; 12 | 13 | void ReadStudent(Student &student, std::ifstream &f){ 14 | 15 | size_t nameLen; 16 | 17 | f.read((char *)&nameLen, sizeof(size_t)); // First we read the size of the name! 18 | 19 | f.read(student.name, nameLen); 20 | student.name[nameLen] = '\0'; 21 | 22 | f.read((char *)&student.fn, sizeof(int)); 23 | f.read((char *)&student.age, sizeof(int)); 24 | f.read((char *)&student.fn, sizeof(double)); 25 | 26 | } 27 | 28 | Student *ReadFromFile(size_t &studentsCount, std::ifstream &f){ 29 | 30 | size_t numberOfStudents; 31 | f.seekg(0, std::ios::beg); 32 | f.read((char *)&numberOfStudents, sizeof(size_t)); 33 | 34 | Student *ptr = new(std::nothrow) Student[studentsCount]; 35 | if(!ptr) return nullptr; 36 | 37 | for(size_t i = 0; i < numberOfStudents; ++i) ReadStudent(ptr[i], f); 38 | 39 | return ptr; 40 | 41 | } 42 | 43 | 44 | int main(){ 45 | 46 | std::ifstream file("students.dat", std::ios::binary); 47 | 48 | if(!file.is_open()){ 49 | 50 | std::cout << "Error while opening the file!\n"; 51 | return -1; 52 | 53 | } 54 | 55 | size_t count; 56 | Student *students = ReadFromFile(count, file); 57 | 58 | if(!students){ 59 | 60 | std::cout << "Memory error\n"; 61 | file.close(); 62 | return -1; 63 | 64 | } 65 | 66 | for(size_t i = 0; i < count; i++) 67 | std::cout << "Name: " << students[i].name << ", age: " << students[i].age << ", fn: " << students[i].fn << '\n'; 68 | 69 | delete[] students; 70 | file.close(); 71 | 72 | return 0; 73 | 74 | } 75 | -------------------------------------------------------------------------------- /Seminar/Week 02/Examples for binary files/array_of_students_write.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | struct Student{ 7 | 8 | char name[24]; 9 | int age; 10 | int fn; 11 | 12 | }; 13 | 14 | void InitStudent(Student& st, char const *name, int const age, int const fn){ 15 | 16 | strcpy(st.name, name); 17 | st.age = age; 18 | st.fn = fn; 19 | 20 | } 21 | 22 | void SaveToFile(Student const *students, size_t const count, std::ofstream &file){ 23 | 24 | file.write((char const *)&count, sizeof(size_t)); 25 | 26 | for(size_t i = 0; i < count; ++i){ 27 | 28 | size_t nameSize = strlen(students[i].name); 29 | file.write((char const *)&nameSize, sizeof(size_t)); 30 | file.write(students[i].name, nameSize); 31 | file.write((char const *)&students[i].age, sizeof(int)); 32 | file.write((char const *)&students[i].fn, sizeof(int)); 33 | 34 | } 35 | 36 | } 37 | 38 | 39 | int main(){ 40 | 41 | size_t const STUDENTS_SIZE = 4; 42 | 43 | Student* students = new(std::nothrow) Student[STUDENTS_SIZE]; 44 | if(!students){ 45 | 46 | std::cout << "Memory error\n"; 47 | return -1; 48 | 49 | } 50 | 51 | InitStudent(students[0], "ivan", 44, 1234); 52 | InitStudent(students[1], "petur", 12, 765); 53 | InitStudent(students[2], "alex", 15, 44); 54 | InitStudent(students[3], "katerina", 19, 12134); 55 | 56 | std::ofstream file("students.dat", std::ios::binary | std::ios::trunc); 57 | 58 | if(!file.is_open()){ 59 | 60 | std::cout << "Error while opening the file!\n"; 61 | delete[] students; 62 | return -1; 63 | 64 | } 65 | 66 | SaveToFile(students, STUDENTS_SIZE, file); 67 | 68 | delete[] students; 69 | file.close(); 70 | 71 | return 0; 72 | 73 | } 74 | -------------------------------------------------------------------------------- /Seminar/Week 02/Examples for binary files/simple_struct_binary.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Test{ 5 | 6 | bool b; 7 | int x; 8 | 9 | }; 10 | 11 | int main(){ 12 | 13 | { // write 14 | 15 | Test t = { true, 45 }; 16 | std::ofstream file("testObj.bat", std::ios::binary | std::ios::trunc); 17 | 18 | if(!file.is_open()) return -1; 19 | 20 | file.write((const char*)&t, sizeof(t)); 21 | 22 | file.close(); 23 | 24 | } 25 | 26 | { // read 27 | 28 | Test t; 29 | std::ifstream file("testObj.bat", std::ios::binary); 30 | 31 | if(!file.is_open()) return -1; 32 | 33 | file.read((char*)&t, sizeof(t)); 34 | 35 | std::cout << t.b << " " << t.x << '\n'; 36 | 37 | file.close(); 38 | 39 | } 40 | 41 | return 0; 42 | 43 | } 44 | -------------------------------------------------------------------------------- /Seminar/Week 02/Examples for binary files/students.csv: -------------------------------------------------------------------------------- 1 | Ime,Familiya,Fakulteten nomer,Imeyl adres 2 | Antonio,Petrov,0MI0600123,antoniosg@abv.bg.bg 3 | Ekaterina,Dimova,2MI0800100,kati@mail.bg 4 | Katerina,Vassileva,1MI0800555,katerina@gmail.com 5 | -------------------------------------------------------------------------------- /Seminar/Week 02/Solutions/myData.dat: -------------------------------------------------------------------------------- 1 | Hello worldgg -------------------------------------------------------------------------------- /Seminar/Week 02/Solutions/students.csv: -------------------------------------------------------------------------------- 1 | Ime,Familiya,Fakulteten nomer,Imeyl adres 2 | Antonio,Petrov,0MI0600123,antoniosg@abv.bg.bg 3 | Ekaterina,Dimova,2MI0800100,kati@mail.bg 4 | Katerina,Vassileva,1MI0800555,katerina@gmail.com -------------------------------------------------------------------------------- /Seminar/Week 02/fileStreams.md: -------------------------------------------------------------------------------- 1 |

File Streams:

2 | 3 |

Type of streams for files

4 | 5 | std::ofstream - This data type represents the output file stream and is used to create files and to write 6 | information to files. 7 | 8 | std::ifstream - This data type represents the input file stream and is used to read information from files. 9 | 10 | std::fstream - This data type represents the file stream generally, and has the capabilities of both 11 | ofstream and ifstream which means it can create files, write information to files, and read 12 | information from files. 13 | 14 | 15 |

Type of flags

16 | 17 | std::ios::app - Append mode. All output to that file to be appended to the end. 18 | std::ios::ate - Open a file for output and move the read/write control to the end of the file. 19 | std::ios::in - Open a file for reading. 20 | std::ios::out - Open a file for writing. 21 | std::ios::trunc - If the file already exists, its contents will be truncated before opening the file. 22 | std::ios::binary - Open a binary file 23 | 24 |

read & write BINARY

25 | 26 | std::ofstream outFile("", std::ios::binary); 27 | 28 | outFile.write((const char*), sizeof()); 29 | 30 | outFile.seekp(); //beg, end, cur - sets the position where the next character is to be inserted 31 | outFile.tellp(); - gets the position from the beginning of the file 32 | 33 | std::ifstream inFile("", std::ios::binary); 34 | 35 | inFile.seekg(); //beg, end, cur - sets the position where the next character is to be read 36 | inFile.tellg(); - gets the position from the beginning of the file 37 | 38 | inFile.read((char*), sizeof()); -------------------------------------------------------------------------------- /Seminar/Week 03/Compiler Examples/compiler_options.bat: -------------------------------------------------------------------------------- 1 | g++ -E main.cpp > main.ii @REM Preprocessing only. This expands all directives like define, include, etc. 2 | g++ -S main.cpp @REM Compile only without assembling and linking. Gives an assembly file main.s 3 | g++ -c main.cpp @REM Compile and assemble without linking. Gives an object file main.o 4 | g++ main.o -o main.exe @REM Link the object files and create an output executable. 5 | g++ main.cpp -o main.exe @REM Preprocess, compile, assemble and link to create main.exe -------------------------------------------------------------------------------- /Seminar/Week 03/Compiler Examples/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(){ 4 | std::cout << "Hello World!\n"; 5 | } -------------------------------------------------------------------------------- /Seminar/Week 03/Dynamic Library Example/Library/compile_library.bat: -------------------------------------------------------------------------------- 1 | g++ -c test.cpp -o mylib.o 2 | g++ -shared -o mylib.dll mylib.o -Wl,--out-implib,libmylib.a -------------------------------------------------------------------------------- /Seminar/Week 03/Dynamic Library Example/Library/test.cpp: -------------------------------------------------------------------------------- 1 | #include "test.hpp" 2 | #include 3 | 4 | extern "C"{ 5 | DLLExport void func(){ 6 | std::cout << "Here\n"; 7 | } 8 | } -------------------------------------------------------------------------------- /Seminar/Week 03/Dynamic Library Example/Library/test.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #ifdef _WIN32 4 | #define DLLExport __declspec(dllexport) 5 | #else 6 | #define DLLExport 7 | #endif 8 | 9 | extern "C"{ 10 | DLLExport void func(); 11 | } -------------------------------------------------------------------------------- /Seminar/Week 03/Dynamic Library Example/compile_executable.bat: -------------------------------------------------------------------------------- 1 | g++ main.cpp -o main.exe -LLibrary -lmylib -------------------------------------------------------------------------------- /Seminar/Week 03/Dynamic Library Example/main.cpp: -------------------------------------------------------------------------------- 1 | #include "Library/test.hpp" 2 | 3 | int main(){ 4 | 5 | func(); 6 | return 0; 7 | 8 | } -------------------------------------------------------------------------------- /Seminar/Week 03/Static Library Example/Library/compile_library.bat: -------------------------------------------------------------------------------- 1 | g++ -c test.cpp -o mylib.o 2 | ar rcs libmylib.a mylib.o -------------------------------------------------------------------------------- /Seminar/Week 03/Static Library Example/Library/test.cpp: -------------------------------------------------------------------------------- 1 | #include "test.hpp" 2 | #include 3 | 4 | void func(){ 5 | std::cout << "Here\n"; 6 | } -------------------------------------------------------------------------------- /Seminar/Week 03/Static Library Example/Library/test.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | void func(); -------------------------------------------------------------------------------- /Seminar/Week 03/Static Library Example/compile_executable.bat: -------------------------------------------------------------------------------- 1 | g++ main.cpp -o main.exe -LLibrary -lmylib -------------------------------------------------------------------------------- /Seminar/Week 03/Static Library Example/main.cpp: -------------------------------------------------------------------------------- 1 | #include "Library/test.hpp" 2 | 3 | int main(){ 4 | 5 | func(); 6 | return 0; 7 | 8 | } -------------------------------------------------------------------------------- /Seminar/Week 04/Example/Animal.cpp: -------------------------------------------------------------------------------- 1 | #include "Animal.hpp" 2 | #include 3 | #include 4 | 5 | void Animal::Init(char const *name, unsigned age, Type type){ 6 | 7 | this -> age = age; 8 | this -> type = type; 9 | SetName(name); 10 | 11 | } 12 | 13 | void Animal::Speak(){ 14 | 15 | switch (type) 16 | { 17 | case Animal::Type::Dog: 18 | std::cout << "Bow wou\n"; 19 | break; 20 | 21 | case Animal::Type::Cat: 22 | std::cout << "Meow meow\n"; 23 | break; 24 | 25 | case Animal::Type::Fish: 26 | std::cout << "brrrrr\n"; 27 | break; 28 | 29 | case Animal::Type::Monkey: 30 | std::cout << "U Agh U agh\n"; 31 | break; 32 | 33 | default: 34 | break; 35 | } 36 | 37 | } 38 | void Animal::SetName(char const *name){ 39 | 40 | if(this -> name) Deallocate(); 41 | this -> name = new(std::nothrow) char[strlen(name) + 1]; 42 | strcpy(this -> name, name); 43 | 44 | } 45 | 46 | char const *Animal::GetName() const{ 47 | return name; 48 | } 49 | unsigned Animal::GetAge() const{ 50 | return age; 51 | } 52 | Animal::Type Animal::GetType() const{ 53 | return type; 54 | } 55 | 56 | void Animal::Deallocate(){ 57 | delete[] name; 58 | name = nullptr; 59 | } -------------------------------------------------------------------------------- /Seminar/Week 04/Example/Animal.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | class Animal{ 4 | 5 | public: 6 | // Enum for types 7 | enum class Type{ 8 | Cat, 9 | Dog, 10 | Fish, 11 | Monkey 12 | }; 13 | 14 | // Initializing an animal and freeing it's memory 15 | void Init(char const *name, unsigned age, Type type); 16 | void Deallocate(); 17 | 18 | // Speak 19 | void Speak(); 20 | 21 | // Setters 22 | void SetName(char const *name); 23 | void SetAge(unsigned const age); 24 | void SetType(Type const type); 25 | 26 | // Getters 27 | char const *GetName() const; 28 | unsigned GetAge() const; 29 | Type GetType() const; 30 | 31 | private: 32 | // Fields 33 | char *name = nullptr; 34 | unsigned age = 0; 35 | Type type = Type::Cat; 36 | 37 | }; -------------------------------------------------------------------------------- /Seminar/Week 04/Example/Person.cpp: -------------------------------------------------------------------------------- 1 | #include "Person.hpp" 2 | #include 3 | #include 4 | 5 | void Person::Init(char const *name, unsigned age, Animal pet){ 6 | 7 | this -> age = age; 8 | SetName(name); 9 | SetPet(pet); 10 | 11 | } 12 | 13 | void Person::SetName(char const *name){ 14 | 15 | if(this -> name) Deallocate(); 16 | this -> name = new(std::nothrow) char[strlen(name) + 1]; 17 | strcpy(this -> name, name); 18 | 19 | } 20 | void Person::SetPet(Animal const pet){ 21 | this -> pet.Init(pet.GetName(), pet.GetAge(), pet.GetType()); 22 | } 23 | 24 | char const *Person::GetName() const{ 25 | return name; 26 | } 27 | unsigned Person::GetAge() const{ 28 | return age; 29 | } 30 | Animal Person::GetPet() const{ 31 | return pet; 32 | } 33 | 34 | void Person::Deallocate(){ 35 | delete[] name; 36 | name = nullptr; 37 | } -------------------------------------------------------------------------------- /Seminar/Week 04/Example/Person.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "Animal.hpp" 3 | 4 | class Person{ 5 | 6 | public: 7 | void Init(char const *name, unsigned age, Animal pet); 8 | 9 | void SetName(char const *name); 10 | void SetPet(Animal const pet); 11 | 12 | char const *GetName() const; 13 | unsigned GetAge() const; 14 | Animal GetPet() const; 15 | 16 | void Deallocate(); 17 | 18 | private: 19 | char *name = nullptr; 20 | unsigned age = 0; 21 | Animal pet; 22 | 23 | }; -------------------------------------------------------------------------------- /Seminar/Week 04/Example/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "Person.hpp" 3 | 4 | int main(){ 5 | 6 | Animal a; 7 | a.Init("Penka", 3, Animal::Type::Cat); 8 | Animal b; 9 | b.Init("Toshko", 7, Animal::Type::Dog); 10 | 11 | Person p; 12 | p.Init("Gosho", 10, a); 13 | 14 | p.GetPet().Speak(); 15 | 16 | p.SetPet(b); 17 | p.GetPet().Speak(); 18 | 19 | std::cout << p.GetPet().GetName() << '\n'; 20 | 21 | p.Deallocate(); 22 | a.Deallocate(); 23 | b.Deallocate(); 24 | return 0; 25 | 26 | } -------------------------------------------------------------------------------- /Seminar/Week 04/Solutions/Task2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | class Car{ 4 | 5 | public: 6 | int getGas() const; 7 | int getHorsePower() const; 8 | int getDistanceTraveled() const; 9 | 10 | void setGas(const int &); 11 | void setHorsePower(const int &); 12 | void setDistanceTraveled(const int &); 13 | 14 | void upgrade(); 15 | void fill(); 16 | void drive(const int &); 17 | 18 | private: 19 | int gas, horsePower, distanceTraveled; 20 | 21 | }; 22 | 23 | int Car::getGas() const{ 24 | return gas; 25 | } 26 | 27 | int Car::getHorsePower() const{ 28 | return horsePower; 29 | } 30 | 31 | int Car::getDistanceTraveled() const{ 32 | return distanceTraveled; 33 | } 34 | 35 | void Car::setGas(const int &gas){ 36 | this -> gas = gas; 37 | } 38 | 39 | void Car::setHorsePower(const int &horsePower){ 40 | this -> horsePower = horsePower; 41 | } 42 | 43 | void Car::setDistanceTraveled(const int &distanceTraveled){ 44 | this -> distanceTraveled = distanceTraveled; 45 | } 46 | 47 | void Car::upgrade(){ 48 | 49 | if(horsePower == 150) return; 50 | horsePower = std::min(150, horsePower + 15); 51 | 52 | } 53 | void Car::fill(){ 54 | gas = 100; 55 | } 56 | 57 | void Car::drive(const int &km){ 58 | gas -= km * horsePower * 0.15; 59 | } 60 | 61 | int main(){ 62 | 63 | Car myCar; 64 | 65 | myCar.fill(); 66 | myCar.setHorsePower(90); 67 | myCar.setDistanceTraveled(0); 68 | 69 | myCar.drive(15); 70 | 71 | std::cout << myCar.getGas() << '\n'; 72 | 73 | myCar.upgrade(); 74 | myCar.fill(); 75 | 76 | myCar.drive(15); 77 | 78 | std::cout << myCar.getGas() << '\n'; 79 | 80 | return 0; 81 | 82 | } -------------------------------------------------------------------------------- /Seminar/Week 04/Task1_structure.hpp: -------------------------------------------------------------------------------- 1 | // Да се реализират функциите... 2 | 3 | class Complex{ 4 | 5 | public: 6 | int getReal() const; 7 | int getImag() const; 8 | 9 | void setReal(const int &); 10 | void setImag(const int &); 11 | 12 | void print() const; 13 | 14 | private: 15 | int real, imag; 16 | 17 | }; 18 | 19 | Complex add(const Complex &, const Complex &); 20 | Complex subtract(const Complex &, const Complex &); 21 | Complex multiply(const Complex &, const Complex &); -------------------------------------------------------------------------------- /Seminar/Week 04/Task2_structure.hpp: -------------------------------------------------------------------------------- 1 | // Да се реализират методите на класът... 2 | 3 | class Car{ 4 | 5 | public: 6 | int getGas() const; 7 | int getHorsePower() const; 8 | int getDistanceTraveled() const; 9 | 10 | void setGas(const int &); 11 | void setHorsePower(const int &); 12 | void setDistanceTraveled(const int &); 13 | 14 | void upgrade(); 15 | void fill(); 16 | void drive(const int &); 17 | 18 | private: 19 | int gas, horsePower, distanceTraveled; 20 | 21 | }; -------------------------------------------------------------------------------- /Seminar/Week 05/Athlete/Athlete.hpp: -------------------------------------------------------------------------------- 1 | #ifndef __ATHLETE_H 2 | #define __ATHLETE 3 | 4 | class Athlete{ 5 | 6 | public: 7 | // enum е най-добре да бъде scoped(class), за да може да използваме само самите стойности(да не можем да използваме числа). 8 | // Дефиниран е вътре в класа, тъй като в нашия случай ще се отнася само за атлетите. 9 | // Ако им употреба някъде другаде трябва да бъде извън него. 10 | enum class Sport : char{ 11 | 12 | Football, 13 | Basketball, 14 | Volleyball, 15 | Tennis 16 | 17 | }; 18 | 19 | // Жизнен цикъл 20 | Athlete(); 21 | Athlete(char const *name, int stamina, int speed, int power, bool trauma, char const *team, Sport sport); 22 | ~Athlete(); 23 | 24 | // Get-ери 25 | char const *GetName() const; 26 | int GetStamina() const; 27 | int GetSpeed() const; 28 | int GetPower() const; 29 | bool GetTrauma() const; 30 | char const *GetTeam() const; 31 | Sport GetSport() const; 32 | 33 | // Мутатори(променят полетата на класа) 34 | void ChangeTeam(char const *); 35 | void Train(); 36 | 37 | // Функция за принтиране 38 | void Print() const; 39 | 40 | private: 41 | // Динамични низове за имената на атлета и отбора. 42 | char *name, *team; 43 | // Тези полета са оставени като char, с цел спестяване на памет. Вместо 3х4b, имаме 3х1b. 44 | char stamina, speed, power; 45 | Sport sport; 46 | bool trauma; 47 | 48 | }; 49 | 50 | #endif -------------------------------------------------------------------------------- /Seminar/Week 05/Athlete/main.cpp: -------------------------------------------------------------------------------- 1 | #include "Athlete.hpp" 2 | 3 | int main(){ 4 | 5 | Athlete first; 6 | Athlete second("Gosho", 2, 3, 1, false, "Bistriskite Tigri", Athlete::Sport::Volleyball); 7 | 8 | first.Print(); 9 | second.Print(); 10 | 11 | second.Train(); 12 | second.Print(); 13 | 14 | second.ChangeTeam("Maznite banici"); 15 | second.Print(); 16 | 17 | first.Train(); 18 | first.Print(); 19 | 20 | return 0; 21 | 22 | } -------------------------------------------------------------------------------- /Seminar/Week 06/Examples/MemoryBlock/main.cpp: -------------------------------------------------------------------------------- 1 | #include "MemoryBlock.h" 2 | #include 3 | 4 | int main() 5 | { 6 | // Create a vector object and add a few elements to it. 7 | std::vector v; 8 | v.push_back(MemoryBlock(25)); 9 | v.push_back(MemoryBlock(75)); 10 | 11 | // Insert a new element into the second position of the vector. 12 | v.insert(v.begin() + 1, MemoryBlock(50)); 13 | } -------------------------------------------------------------------------------- /Seminar/Week 06/Examples/MyClass.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | class MyClass{ 4 | 5 | public: 6 | MyClass(): i(0), s({}), ptr(new int(42)){} 7 | 8 | //...Copy assignment operator 9 | // (takes an lvalue) 10 | MyClass &operator =(MyClass const &rhs){ 11 | 12 | if (this == &rhs) return *this; 13 | 14 | i = rhs.i; 15 | ptr = new int; 16 | *ptr = *rhs.ptr; 17 | s = rhs.s; 18 | 19 | return *this; 20 | } 21 | 22 | // Move contructor 23 | // tasks: 24 | // 1. tranfer the contents of mc into this 25 | // 2. leave mc in valid but undefinied state 26 | MyClass(MyClass &&mc) noexcept: i(std::move(mc.i)), s(std::move(mc.s)), ptr(std::move(mc.ptr)){ 27 | mc.ptr = nullptr; 28 | } 29 | 30 | //...Move assignment operator 31 | // (takes a rvalue) 32 | // tasks: 33 | // 1. clear resources 34 | // 2. tranfer the contents of mc into this 35 | // 3. leave mc in valid but undefinied state 36 | MyClass &operator =(MyClass &&mc) noexcept{ 37 | 38 | delete ptr; 39 | 40 | i = std::move(mc.i); 41 | s = std::move(mc.s); 42 | ptr = std::move(mc.ptr); 43 | mc.ptr = nullptr; 44 | 45 | return *this; 46 | 47 | } 48 | 49 | static MyClass createMyClass(){ 50 | return MyClass(); 51 | } 52 | 53 | private: 54 | std::string s = ""; 55 | int *ptr = nullptr, i = 0; 56 | 57 | }; -------------------------------------------------------------------------------- /Seminar/Week 06/Examples/Person/Person.cpp: -------------------------------------------------------------------------------- 1 | #include "Person.hpp" 2 | 3 | #include 4 | #include 5 | 6 | Person::Person(): name(new(std::nothrow) char[1]), surname(new(std::nothrow) char[1]), age(0){ 7 | 8 | if(name) *name = '\0'; 9 | if(surname) *surname = '\0'; 10 | 11 | } 12 | 13 | Person::Person(const char * const &name, const char * const &surname, int const &age): name(new(std::nothrow) char[strlen(name) + 1]), 14 | surname(new(std::nothrow) char[strlen(surname) + 1]), age(age){ 15 | 16 | if(this -> name) strcpy(this -> name, name); 17 | if(this -> surname) strcpy(this -> surname, surname); 18 | 19 | } 20 | 21 | Person::Person(Person const &other){ 22 | copy(other); 23 | } 24 | 25 | Person &Person::operator =(Person const &other){ 26 | 27 | if(this != &other){ 28 | 29 | free(); 30 | copy(other); 31 | 32 | } 33 | 34 | return *this; 35 | 36 | } 37 | 38 | Person::~Person(){ 39 | free(); 40 | } 41 | 42 | int const &Person::getAge() const{ 43 | return age; 44 | } 45 | 46 | char const *Person::getName() const{ 47 | return name; 48 | } 49 | 50 | char const *Person::getSurname() const{ 51 | return surname; 52 | } 53 | 54 | void Person::free(){ 55 | 56 | delete[] name; 57 | delete[] surname; 58 | 59 | } 60 | 61 | void Person::copy(Person const &other){ 62 | 63 | name = new(std::nothrow) char[strlen(other.name) + 1]; 64 | surname = new(std::nothrow) char[strlen(other.surname) + 1]; 65 | 66 | if(name) strcpy(name, other.name); 67 | if(surname) strcpy(surname, other.surname); 68 | 69 | age = other.age; 70 | 71 | } -------------------------------------------------------------------------------- /Seminar/Week 06/Examples/Person/Person.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | class Person{ 4 | 5 | public: 6 | Person(); 7 | Person(const char * const &, const char * const &, int const &); 8 | Person(Person const &); 9 | ~Person(); 10 | 11 | Person &operator =(Person const &); 12 | 13 | int const &getAge() const; 14 | char const *getName() const; 15 | char const *getSurname() const; 16 | 17 | private: 18 | void free(); 19 | void copy(Person const &); 20 | 21 | char *name, *surname; 22 | int age; 23 | 24 | }; -------------------------------------------------------------------------------- /Seminar/Week 06/Examples/Person/test.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "Person.hpp" 3 | 4 | int main(){ 5 | 6 | Person p("Hristo", "Kanev", 20), p1; 7 | 8 | p1 = p; 9 | 10 | std::cout << p1.getName() << ' ' << p1.getSurname() << ' ' << p1.getAge() << '\n'; 11 | 12 | return 0; 13 | 14 | } -------------------------------------------------------------------------------- /Seminar/Week 06/Examples/String/String.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | class String{ 6 | 7 | public: 8 | String(); 9 | String(char const *str); 10 | String(String const &other); 11 | String(String &&other); 12 | ~String(); 13 | 14 | String &operator =(String const &other); 15 | String &operator =(String &&other); 16 | 17 | char const *c_str() const; 18 | size_t Length() const; 19 | void Append(char const *str); 20 | void Append(String const &other); 21 | String Combine(String const &other) const; 22 | void Clear(); 23 | bool Empty() const; 24 | char At(size_t const index) const; 25 | 26 | private: 27 | void free(); 28 | void copy(String const &other); 29 | void move(String &&other); 30 | void resize(size_t const newCapacity); 31 | 32 | size_t const DEFAULT_CAPACITY = 16; 33 | size_t capacity = DEFAULT_CAPACITY, size = 0; 34 | char *str = nullptr; 35 | 36 | }; -------------------------------------------------------------------------------- /Seminar/Week 06/Examples/String/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "String.hpp" 3 | 4 | int main(){ 5 | 6 | String s("Hello World"); 7 | 8 | String s1(s), s2; 9 | 10 | std::cout << s2.Length() << '\n'; 11 | 12 | s2 = s; 13 | 14 | std::cout << s.c_str() << '\n'; 15 | std::cout << s1.c_str() << '\n'; 16 | std::cout << s2.c_str() << '\n'; 17 | 18 | s.Append(" I am Mario"); 19 | std::cout << s.Length() << '\n'; 20 | 21 | for(size_t i = 0; i < s.Length(); ++i) 22 | if(s.At(i) == '!') 23 | std::cout << "Exclamation\n"; 24 | 25 | String s3 = s.Combine(String(" Pesho")); 26 | std::cout << s3.c_str() << '\n'; 27 | 28 | std::cout << s3.Empty() << '\n'; 29 | s3.Clear(); 30 | std::cout << s3.Empty() << '\n'; 31 | 32 | return 0; 33 | 34 | } -------------------------------------------------------------------------------- /Seminar/Week 06/Examples/lvalues_and_rvalues2.cpp: -------------------------------------------------------------------------------- 1 | int main() 2 | { 3 | int i, j, *p; 4 | 5 | // Correct usage: the variable i is an lvalue and the literal 7 is a prvalue. 6 | i = 7; 7 | 8 | // Incorrect usage: The left operand must be an lvalue (C2106).`j * 4` is a prvalue. 9 | 7 = i; // C2106 10 | j * 4 = 7; // C2106 11 | 12 | // Correct usage: the dereferenced pointer is an lvalue. 13 | *p = i; 14 | 15 | // Correct usage: the conditional operator returns an lvalue. 16 | ((i < 3) ? i : j) = 7; 17 | 18 | // Incorrect usage: the constant ci is a non-modifiable lvalue (C3892). 19 | const int ci = 7; 20 | ci = 9; // C3892 21 | } -------------------------------------------------------------------------------- /Seminar/Week 06/Examples/named-reference.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // A class that contains a memory resource. 4 | class MemoryBlock 5 | { 6 | // TODO: Add resources for the class here. 7 | }; 8 | 9 | void g(const MemoryBlock &) 10 | { 11 | std::cout << "In g(const MemoryBlock&)." << std::endl; 12 | } 13 | 14 | void g(MemoryBlock &&) 15 | { 16 | std::cout << "In g(MemoryBlock&&)." << std::endl; 17 | } 18 | 19 | MemoryBlock &&f(MemoryBlock &&block) 20 | { 21 | g(block); 22 | return std::move(block); 23 | } 24 | 25 | int main() 26 | { 27 | g(f(MemoryBlock())); 28 | } -------------------------------------------------------------------------------- /Seminar/Week 06/Examples/reference-overload.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // A class that contains a memory resource. 4 | class MemoryBlock 5 | { 6 | // TODO: Add resources for the class here. 7 | }; 8 | 9 | void f(const MemoryBlock &) 10 | { 11 | std::cout << "In f(const MemoryBlock&). This version can't modify the parameter." << std::endl; 12 | } 13 | 14 | void f(MemoryBlock &&) 15 | { 16 | std::cout << "In f(MemoryBlock&&). This version can modify the parameter." << std::endl; 17 | } 18 | 19 | int main() 20 | { 21 | MemoryBlock block; 22 | f(block); 23 | f(MemoryBlock()); 24 | } -------------------------------------------------------------------------------- /Seminar/Week 06/Examples/reference_declarator.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct Person 4 | { 5 | char *Name; 6 | short Age; 7 | }; 8 | 9 | int main() 10 | { 11 | // Declare a Person object. 12 | Person myFriend; 13 | 14 | // Declare a reference to the Person object. 15 | Person &rFriend = myFriend; 16 | 17 | // Set the fields of the Person object. 18 | // Updating either variable changes the same object. 19 | myFriend.Name = "Bill"; 20 | rFriend.Age = 40; 21 | 22 | // Print the fields of the Person object to the console. 23 | std::cout << rFriend.Name << " is " << myFriend.Age << std::endl; 24 | } -------------------------------------------------------------------------------- /Seminar/Week 06/Examples/rule_of_three_five_zero/rule_of_five.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | class rule_of_five 7 | { 8 | char *cstring; // raw pointer used as a handle to a dynamically-allocated memory block 9 | 10 | void copy(const char *s) 11 | { 12 | const size_t n = strlen(s) + 1; 13 | cstring = new(std::nothrow) char[n]; // allocate 14 | if (!cstring) return; 15 | strcpy(cstring, s); // populate 16 | } 17 | 18 | void free() 19 | { 20 | delete[] cstring; 21 | } 22 | public: 23 | rule_of_five(const char *s = "") : cstring(nullptr) 24 | { 25 | if (!s) return; 26 | copy(s); 27 | } 28 | 29 | ~rule_of_five() 30 | { 31 | free(); // deallocate 32 | } 33 | 34 | rule_of_five(const rule_of_five &other) // copy constructor 35 | { 36 | copy(other.cstring); 37 | } 38 | 39 | rule_of_five(rule_of_five &&other) noexcept // move constructor 40 | { 41 | cstring = std::move(other.cstring); 42 | other.cstring = nullptr; 43 | } 44 | 45 | rule_of_five &operator =(const rule_of_five &other) // copy assignment 46 | { 47 | if (this == &other) return *this; 48 | free(); 49 | copy(other.cstring); 50 | return *this; 51 | } 52 | 53 | rule_of_five &operator =(rule_of_five &&other) noexcept // move assignment 54 | { 55 | cstring = std::move(other.cstring); 56 | other.cstring = nullptr; 57 | return *this; 58 | } 59 | }; -------------------------------------------------------------------------------- /Seminar/Week 06/Examples/rule_of_three_five_zero/rule_of_three.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | // If a class requires a user-defined destructor, a user-defined copy constructor, 7 | // or a user-defined copy assignment operator, it almost certainly requires all three. 8 | 9 | class rule_of_three 10 | { 11 | char *cstring; // raw pointer used as a handle to a dynamically-allocated memory block 12 | 13 | void copy(const char *s, size_t n) 14 | { 15 | if (!s) return; 16 | cstring = new(std::nothrow) char[n]; // allocate 17 | if (!cstring) return; 18 | strcpy(cstring, s); // populate 19 | } 20 | 21 | rule_of_three(const char *s, size_t n) // to avoid counting twice 22 | { 23 | copy(s, n); 24 | } 25 | 26 | public: 27 | rule_of_three(const char *s = "") 28 | : rule_of_three(s, std::strlen(s) + 1) {} 29 | 30 | ~rule_of_three() // I. destructor 31 | { 32 | delete[] cstring; // deallocate 33 | } 34 | 35 | rule_of_three(const rule_of_three &other) // II. copy constructor 36 | : rule_of_three(other.cstring) 37 | { 38 | } 39 | 40 | rule_of_three &operator=(const rule_of_three &other) // III. copy assignment 41 | { 42 | if (this == &other) return *this; 43 | 44 | delete[] cstring; 45 | copy(other.cstring, strlen(other.cstring)); 46 | 47 | return *this; 48 | } 49 | }; -------------------------------------------------------------------------------- /Seminar/Week 06/Examples/rule_of_three_five_zero/rule_of_zero.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // If you can avoid defining default operations, do 4 | 5 | class rule_of_zero 6 | { 7 | std::string cppstring; 8 | 9 | public: 10 | rule_of_zero(const std::string &arg) : cppstring(arg) {} 11 | }; 12 | 13 | class base_of_five_defaults 14 | { 15 | public: 16 | base_of_five_defaults(const base_of_five_defaults &) = default; 17 | base_of_five_defaults(base_of_five_defaults &&) = default; 18 | base_of_five_defaults &operator=(const base_of_five_defaults &) = default; 19 | base_of_five_defaults &operator=(base_of_five_defaults &&) = default; 20 | virtual ~base_of_five_defaults() = default; 21 | }; -------------------------------------------------------------------------------- /Seminar/Week 06/generateRandomNumber.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(){ 5 | 6 | srand(time(0)); // Слагаме seed-а на random да е времето. (стандартна практика) 7 | 8 | for(size_t i = 0; i < 10; ++i) 9 | std::cout << rand() % 100 << '\n'; // % 100 -> число в интервалът [0, 100). 10 | 11 | } -------------------------------------------------------------------------------- /Seminar/Week 07/Examples/Friends/examples.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | // friend classes 6 | class A 7 | { 8 | private: 9 | int a; 10 | 11 | public: 12 | A() { a = 0; } 13 | friend class B; // Friend Class 14 | }; 15 | 16 | // forward declaration 17 | class C; 18 | 19 | class B 20 | { 21 | private: 22 | int b; 23 | 24 | public: 25 | B() { b = 1; } 26 | void showA(A &x) 27 | { 28 | // Since B is friend of A, it can access 29 | // private members of A 30 | std::cout << "A::a = " << x.a << std::endl; 31 | } 32 | void showC(C &x); // Friend function 33 | }; 34 | 35 | // forward declaration 36 | class C 37 | { 38 | private: 39 | int c; 40 | 41 | public: 42 | C() { c = 2; } 43 | friend void B::showC(C &x); // Friend function 44 | C Add(const C &other) 45 | { 46 | C c; 47 | c.c = this->c + other.c; 48 | return c; 49 | } 50 | C Add(int num) 51 | { 52 | C c; 53 | c.c = this->c + num; 54 | return c; 55 | } 56 | friend C Add(int num, const C &c); 57 | void setC(int c) 58 | { 59 | this->c = c; 60 | } 61 | }; 62 | 63 | C Add(int num, const C &rhs) 64 | { 65 | C c; 66 | c.c = rhs.c + num; 67 | return c; 68 | } 69 | 70 | void B::showC(C &x) 71 | { 72 | // Since showC() is friend of C, it can 73 | // access private members of C 74 | std::cout << "C::c = " << x.c << std::endl; 75 | } 76 | 77 | int main() 78 | { 79 | // friend classes 80 | A a; 81 | B b; 82 | C c1; 83 | C c2; 84 | c2.setC(10); 85 | C c3 = c1.Add(c2); 86 | C c4 = c1.Add(5); 87 | C c5 = Add(6, c1); 88 | b.showA(a); 89 | b.showC(c3); 90 | b.showC(c4); 91 | b.showC(c5); 92 | 93 | return 0; 94 | } -------------------------------------------------------------------------------- /Seminar/Week 08/Examples/ArraySubscriptOperator.md: -------------------------------------------------------------------------------- 1 | If the value type is known to be a built - in type, the const variant should return by value. 2 | Where direct access to the elements of the container is not wanted or 3 | not possible or distinguishing between lvalue c[i] = v; 4 | and rvalue v = c[i]; 5 | usage, operator[] may return a proxy. 6 | 7 | ```c++ 8 | struct T 9 | { 10 | value_t &operator[](std::size_t idx) { return mVector[idx]; } 11 | const value_t &operator[](std::size_t idx) const { return mVector[idx]; } 12 | }; 13 | ``` -------------------------------------------------------------------------------- /Seminar/Week 08/Examples/AssignmentOperators.md: -------------------------------------------------------------------------------- 1 | ```c++ 2 | // copy assignment 3 | T &operator=(const T &other) 4 | { 5 | // Guard self assignment 6 | if (this == &other) { 7 | return *this; 8 | } 9 | 10 | // assume *this manages a reusable resource, such as a heap-allocated buffer mArray 11 | if (size != other.size) 12 | { // resource in *this cannot be reused 13 | delete[] mArray; // release resource in *this 14 | mArray = nullptr; 15 | size = 0; // preserve invariants in case next line throws 16 | mArray = new int[other.size]; // allocate resource in *this 17 | size = other.size; 18 | } 19 | 20 | std::copy(other.mArray, other.mArray + other.size, mArray); 21 | return *this; 22 | } 23 | 24 | // move assignment 25 | T &operator=(T &&other) noexcept 26 | { 27 | // Guard self assignment 28 | if (this == &other) 29 | return *this; // delete[]/size=0 would also be ok 30 | 31 | delete[] mArray; // release resource in *this 32 | mArray = std::exchange(other.mArray, nullptr); // leave other in valid state 33 | size = std::exchange(other.size, 0); 34 | return *this; 35 | } 36 | ``` -------------------------------------------------------------------------------- /Seminar/Week 08/Examples/Comaprison.md: -------------------------------------------------------------------------------- 1 | Typically, once operator< is provided, the other relational operators are implemented in terms of operator<. 2 | 3 | ```c++ 4 | bool operator< (const X& lhs, const X& rhs){ /* do actual comparison */ } 5 | bool operator> (const X& lhs, const X& rhs){ return rhs < lhs; } 6 | bool operator<=(const X& lhs, const X& rhs){ return !(lhs > rhs); } 7 | bool operator>=(const X& lhs, const X& rhs){ return !(lhs < rhs); } 8 | ``` 9 | 10 | Likewise, the inequality operator is typically implemented in terms of operator==: 11 | 12 | ```c++ 13 | bool operator==(const X& lhs, const X& rhs){ /* do actual comparison */ } 14 | bool operator!=(const X& lhs, const X& rhs){ return !(lhs == rhs); } 15 | ``` -------------------------------------------------------------------------------- /Seminar/Week 08/Examples/Comparison.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Record 5 | { 6 | std::string name; 7 | unsigned int floor; 8 | double weight; 9 | friend bool operator<(const Record &l, const Record &r) 10 | { 11 | // tie provides lexicographical comparison 12 | return std::tie(l.name, l.floor, l.weight) < std::tie(r.name, r.floor, r.weight); // keep the same order 13 | } 14 | }; -------------------------------------------------------------------------------- /Seminar/Week 08/Examples/CriteriaExample.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | typedef bool(*FunctionPointer)(int); 4 | 5 | class Function{ 6 | 7 | public: 8 | Function(FunctionPointer func){ 9 | this -> func = func; 10 | } 11 | 12 | bool operator()(int a){ 13 | return func(a); 14 | } 15 | 16 | private: 17 | FunctionPointer func; 18 | 19 | }; 20 | 21 | class Set{ 22 | 23 | public: 24 | Set(Function criteria): criteria(criteria){} 25 | 26 | void Add(int a){ 27 | if(criteria(a) && size < MAX_SIZE) arr[size++] = a; 28 | } 29 | 30 | void Print() const{ 31 | for(size_t i = 0; i < size; ++i) 32 | std::cout << arr[i] << ' '; 33 | std::cout << '\n'; 34 | } 35 | 36 | private: 37 | static size_t const MAX_SIZE = 100; 38 | Function criteria; 39 | size_t size = 0; 40 | int arr[MAX_SIZE]; 41 | 42 | }; 43 | 44 | bool IsOdd(int a){ 45 | return a % 2; 46 | } 47 | 48 | bool IsEven(int a){ 49 | return !IsOdd(a); 50 | } 51 | 52 | int main(){ 53 | 54 | Set oddSet(IsOdd); 55 | Set evenSet(IsEven); 56 | 57 | oddSet.Add(1); 58 | oddSet.Add(2); 59 | oddSet.Add(3); 60 | oddSet.Add(4); 61 | 62 | evenSet.Add(1); 63 | evenSet.Add(2); 64 | evenSet.Add(3); 65 | evenSet.Add(4); 66 | 67 | std::cout << "Odd:\n"; 68 | oddSet.Print(); 69 | std::cout << "Even:\n"; 70 | evenSet.Print(); 71 | 72 | return 0; 73 | 74 | } -------------------------------------------------------------------------------- /Seminar/Week 08/Examples/FunctionCallOperator.cpp: -------------------------------------------------------------------------------- 1 | // An object of this type represents a linear function of one variable a*x + b. 2 | struct Linear 3 | { 4 | double a, b; 5 | 6 | double operator()(double x) const 7 | { 8 | return a * x + b; 9 | } 10 | }; 11 | 12 | int main() 13 | { 14 | Linear f{2, 1}; // Represents function 2x + 1. 15 | Linear g{-1, 0}; // Represents function -x. 16 | // f and g are objects that can be used like a function. 17 | 18 | double f0 = f(0); 19 | double f1 = f(1); 20 | 21 | double g0 = g(0); 22 | } -------------------------------------------------------------------------------- /Seminar/Week 08/Examples/IncrementAndDecrement.md: -------------------------------------------------------------------------------- 1 | ```c++ 2 | struct X 3 | { 4 | // prefix increment 5 | X &operator++() 6 | { 7 | // actual increment takes place here 8 | return *this; // return new value by reference 9 | } 10 | 11 | // postfix increment 12 | X operator++(int) 13 | { 14 | X old = *this; // copy old value 15 | operator++(); // prefix increment 16 | return old; // return old value 17 | } 18 | 19 | // prefix decrement 20 | X &operator--() 21 | { 22 | // actual decrement takes place here 23 | return *this; // return new value by reference 24 | } 25 | 26 | // postfix decrement 27 | X operator--(int) 28 | { 29 | X old = *this; // copy old value 30 | operator--(); // prefix decrement 31 | return old; // return old value 32 | } 33 | }; 34 | ``` -------------------------------------------------------------------------------- /Seminar/Week 08/Examples/StreamExtractionAndInsertion.md: -------------------------------------------------------------------------------- 1 | ```c++ 2 | std::ostream &operator<<(std::ostream &os, const T &obj) 3 | { 4 | // write obj to stream 5 | return os; 6 | } 7 | 8 | std::istream &operator>>(std::istream &is, T &obj) 9 | { 10 | // read obj from stream 11 | if (/* T could not be constructed */) 12 | is.setstate(std::ios::failbit); 13 | return is; 14 | } -------------------------------------------------------------------------------- /Seminar/Week 08/Smart Pointers/shared_ptr.hpp: -------------------------------------------------------------------------------- 1 | #ifndef SHARED_PTR_HPP 2 | #define SHARED_PTR_HPP 3 | 4 | typedef decltype(nullptr) nullptr_t; 5 | typedef unsigned long long size_t; 6 | 7 | class SharedPtr{ 8 | 9 | public: 10 | SharedPtr() = default; 11 | SharedPtr(nullptr_t) noexcept; 12 | explicit SharedPtr(int *ptr); 13 | SharedPtr(SharedPtr const &other) noexcept; 14 | ~SharedPtr() noexcept; 15 | 16 | SharedPtr &operator =(SharedPtr const &other) noexcept; 17 | 18 | int &operator *() const noexcept; 19 | int *operator ->() const noexcept; 20 | int *Get() const noexcept; 21 | explicit operator bool() const noexcept; 22 | 23 | size_t UseCount() const noexcept; 24 | bool Unique() const noexcept; 25 | 26 | void Reset(); 27 | void Reset(int *ptr); 28 | void Swap(SharedPtr &other) noexcept; 29 | 30 | private: 31 | int *m_Ptr = nullptr; 32 | size_t *m_RC = nullptr; 33 | 34 | }; 35 | 36 | inline bool operator ==(SharedPtr const &lhs, SharedPtr const &rhs) noexcept; 37 | inline bool operator ==(SharedPtr const &lhs, nullptr_t) noexcept; 38 | inline bool operator ==(nullptr_t, SharedPtr const &rhs) noexcept; 39 | 40 | inline bool operator !=(SharedPtr const &lhs, SharedPtr const &rhs) noexcept; 41 | inline bool operator !=(SharedPtr const &lhs, nullptr_t) noexcept; 42 | inline bool operator !=(nullptr_t, SharedPtr const &rhs) noexcept; 43 | 44 | #endif -------------------------------------------------------------------------------- /Seminar/Week 08/Smart Pointers/unique_ptr.cpp: -------------------------------------------------------------------------------- 1 | #include "unique_ptr.hpp" 2 | 3 | UniquePtr::UniquePtr(nullptr_t) noexcept{} 4 | 5 | explicit UniquePtr::UniquePtr(int *ptr) noexcept: m_Ptr(ptr){} 6 | 7 | UniquePtr::~UniquePtr(){ if(m_Ptr) delete m_Ptr; } 8 | 9 | int &UniquePtr::operator *() const noexcept{ return *m_Ptr; } 10 | int *UniquePtr::operator ->() const noexcept{ return m_Ptr; } 11 | int *UniquePtr::Get() const noexcept{ return m_Ptr; } 12 | explicit UniquePtr::operator bool() const noexcept{ return m_Ptr ? true : false; } 13 | 14 | int *UniquePtr::Release() noexcept{ 15 | 16 | int *old = m_Ptr; 17 | m_Ptr = nullptr; 18 | return old; 19 | 20 | } 21 | 22 | void UniquePtr::Reset(int *ptr){ 23 | 24 | UniquePtr temp(ptr); 25 | temp.Swap(*this); 26 | 27 | } 28 | 29 | void swap(int *&lhs, int *&rhs){ 30 | 31 | int *temp = lhs; 32 | lhs = rhs; 33 | rhs = temp; 34 | 35 | } 36 | 37 | void UniquePtr::Swap(UniquePtr &other) noexcept{ 38 | swap(m_Ptr, other.m_Ptr); 39 | } 40 | 41 | inline bool operator ==(UniquePtr const &lhs, UniquePtr const &rhs) noexcept{ 42 | return lhs.Get() == rhs.Get(); 43 | } 44 | 45 | inline bool operator ==(UniquePtr const &lhs, nullptr_t) noexcept{ 46 | return !lhs; 47 | } 48 | 49 | inline bool operator ==(nullptr_t, UniquePtr const &rhs) noexcept{ 50 | return !rhs; 51 | } 52 | 53 | inline bool operator !=(UniquePtr const &lhs, UniquePtr const &rhs) noexcept{ 54 | return !(lhs == rhs); 55 | } 56 | 57 | inline bool operator !=(UniquePtr const &lhs, nullptr_t) noexcept{ 58 | return bool(lhs); 59 | } 60 | 61 | inline bool operator !=(nullptr_t, UniquePtr const &rhs) noexcept{ 62 | return bool(rhs); 63 | } -------------------------------------------------------------------------------- /Seminar/Week 08/Smart Pointers/unique_ptr.hpp: -------------------------------------------------------------------------------- 1 | #ifndef UNIQUE_PTR_HPP 2 | #define UNIQUE_PTR_HPP 3 | 4 | typedef decltype(nullptr) nullptr_t; 5 | 6 | class UniquePtr{ 7 | 8 | public: 9 | UniquePtr() noexcept = default; 10 | UniquePtr(nullptr_t) noexcept; 11 | explicit UniquePtr(int *ptr) noexcept; 12 | ~UniquePtr() noexcept; 13 | 14 | int &operator *() const noexcept; 15 | int *operator ->() const noexcept; 16 | int *Get() const noexcept; 17 | explicit operator bool() const noexcept; 18 | 19 | int *Release() noexcept; 20 | void Reset(int *ptr = nullptr); 21 | void Swap(UniquePtr &other) noexcept; 22 | 23 | UniquePtr(UniquePtr const &) = delete; 24 | UniquePtr &operator =(UniquePtr const &) = delete; 25 | 26 | private: 27 | int *m_Ptr; 28 | 29 | }; 30 | 31 | inline bool operator ==(UniquePtr const &lhs, UniquePtr const &rhs) noexcept; 32 | inline bool operator ==(UniquePtr const &lhs, nullptr_t) noexcept; 33 | inline bool operator ==(nullptr_t, UniquePtr const &rhs) noexcept; 34 | 35 | inline bool operator !=(UniquePtr const &lhs, UniquePtr const &rhs) noexcept; 36 | inline bool operator !=(UniquePtr const &lhs, nullptr_t) noexcept; 37 | inline bool operator !=(nullptr_t, UniquePtr const &rhs) noexcept; 38 | 39 | #endif -------------------------------------------------------------------------------- /Seminar/Week 08/String/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "String.hpp" 3 | 4 | int main(){ 5 | 6 | String s("Hello World"); 7 | 8 | String s1(s), s2; 9 | 10 | std::cout << s2.Length() << '\n'; 11 | 12 | std::cin >> s2; 13 | 14 | std::cout << s2 << '\n'; 15 | std::cout << s2.Length() << '\n'; 16 | 17 | s2 = s; 18 | 19 | std::cout << s << '\n'; 20 | std::cout << s1 << '\n'; 21 | std::cout << s2 << '\n'; 22 | 23 | s += " I am Mario"; 24 | s += '!'; 25 | std::cout << s.Length() << '\n'; 26 | 27 | for(size_t i = 0; i < s.Length(); ++i) 28 | if(s[i] == '!') 29 | std::cout << "Exclamation\n"; 30 | 31 | String s3 = s + String(" Pesho"); 32 | std::cout << s3 << '\n'; 33 | 34 | std::cout << s3.Empty() << '\n'; 35 | s3.Clear(); 36 | std::cout << s3.Empty() << '\n'; 37 | 38 | return 0; 39 | 40 | } -------------------------------------------------------------------------------- /Seminar/Week 09/Examples/Person, Student, Teacher/Person/Person.cpp: -------------------------------------------------------------------------------- 1 | #include "Person.hpp" 2 | #include 3 | #include 4 | #include 5 | 6 | Person::Person(char const *m_Name, int m_Age){ 7 | 8 | SetName(m_Name); 9 | SetAge(m_Age); 10 | 11 | } 12 | 13 | Person::Person(Person const &other){ 14 | Copy(other); 15 | } 16 | 17 | Person::Person(Person &&other){ 18 | Move(std::move(other)); 19 | } 20 | 21 | Person& Person::operator=(const Person& other){ 22 | 23 | if (this == &other) return *this; 24 | 25 | *this = Person(other); 26 | 27 | return *this; 28 | 29 | } 30 | 31 | Person& Person::operator=(Person &&other){ 32 | 33 | if (this == &other) return *this; 34 | 35 | Free(); 36 | Move(std::move(other)); 37 | 38 | return *this; 39 | 40 | } 41 | 42 | char const *Person::GetName() const{ 43 | return m_Name; 44 | } 45 | 46 | int Person::GetAge() const{ 47 | return m_Age; 48 | } 49 | 50 | void Person::SetName(char const *name){ 51 | 52 | if(!m_Name || this -> m_Name == name) return; 53 | 54 | size_t const NAME_LENGTH = strlen(name); 55 | char *temp = new char[NAME_LENGTH + 1]; 56 | strcpy(temp, name); 57 | 58 | delete[] this -> m_Name; 59 | this -> m_Name = temp; 60 | 61 | } 62 | 63 | void Person::SetAge(unsigned m_Age){ 64 | this->m_Age = m_Age; 65 | } 66 | 67 | 68 | Person::~Person(){ 69 | Free(); 70 | } 71 | 72 | void Person::Print() const{ 73 | std::cout << m_Name << " " << m_Age << '\n'; 74 | } 75 | 76 | 77 | void Person::Copy(Person const &other){ 78 | 79 | m_Name = new char[strlen(other.m_Name) + 1]; 80 | strcpy(m_Name, other.m_Name); 81 | m_Age = other.m_Age; 82 | 83 | } 84 | 85 | void Person::Move(Person &&other){ 86 | 87 | m_Name = std::exchange(other.m_Name, nullptr); 88 | m_Age = other.m_Age; 89 | 90 | } 91 | 92 | void Person::Free(){ 93 | delete[] m_Name; 94 | } -------------------------------------------------------------------------------- /Seminar/Week 09/Examples/Person, Student, Teacher/Person/Person.hpp: -------------------------------------------------------------------------------- 1 | #ifndef __PERSON_HPP 2 | #define __PERSON_HPP 3 | 4 | class Person{ 5 | 6 | public: 7 | Person() = default; 8 | Person(char const *name, int age); 9 | Person(Person const &other); 10 | Person(Person &&other); 11 | ~Person(); 12 | 13 | Person& operator=(Person const &other); 14 | Person& operator=(Person &&other); 15 | 16 | const char* GetName() const; 17 | int GetAge() const; 18 | 19 | void Print() const; 20 | 21 | protected: 22 | void SetName(const char* name); 23 | void SetAge(unsigned age); 24 | 25 | private: 26 | char *m_Name = nullptr; 27 | unsigned m_Age = 0; 28 | 29 | void Copy(Person const &other); 30 | void Move(Person &&other); 31 | void Free(); 32 | 33 | }; 34 | 35 | #endif -------------------------------------------------------------------------------- /Seminar/Week 09/Examples/Person, Student, Teacher/Source.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "Person/Person.hpp" 3 | #include "Student/Student.hpp" 4 | #include "Teacher/Teacher.hpp" 5 | 6 | int main(){ 7 | 8 | char subjects[3][20] = { "English", "Mathematics", "Physics" }; 9 | 10 | char **subjectsPointers = new char *[3]; 11 | 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 | -------------------------------------------------------------------------------- /Seminar/Week 09/Examples/Person, Student, Teacher/Student/Student.cpp: -------------------------------------------------------------------------------- 1 | #include "Student.hpp" 2 | 3 | Student::Student(char const *name, unsigned age, size_t fn): Person(name, age){ 4 | SetFn(fn); 5 | } 6 | 7 | size_t Student::GetFn() const{ 8 | return fn; 9 | } 10 | 11 | void Student::SetFn(size_t fn){ 12 | 13 | if(fn < 100) fn = 100; 14 | this -> fn = fn; 15 | 16 | } 17 | 18 | // The compiler will make: 19 | 20 | //Student(const Student& other) : Person(other), fn(other.fn), grade(other.grade) OK!!! 21 | //{} 22 | 23 | //Student& operator=(const Student& other) OK!!!! 24 | //{ 25 | // if (this != &other) 26 | // { 27 | // Person::operator=(other); //handles the deletion and copying of the base class 28 | // fn = other.fn; 29 | // } 30 | // return *this; 31 | //} -------------------------------------------------------------------------------- /Seminar/Week 09/Examples/Person, Student, Teacher/Student/Student.hpp: -------------------------------------------------------------------------------- 1 | #ifndef __STUDENT_HPP 2 | #define __STUDENT_HPP 3 | 4 | #include "../Person/Person.h" 5 | #include 6 | 7 | class Student : public Person{ 8 | 9 | public: 10 | Student() = default; 11 | Student(char const *name, unsigned age, size_t fn); 12 | 13 | size_t GetFn() const; 14 | void SetFn(size_t fn); 15 | 16 | // No need for big 4, since there is NO dyn. memory in Student 17 | // The compiler will generate valid: 18 | 19 | //Student(const Student& other); 20 | //Student& operator=(const Student& other); //no need 21 | // ~Student() 22 | 23 | //See on the .cpp file how the compiler creates them 24 | 25 | private: 26 | size_t fn = 0; 27 | 28 | }; 29 | 30 | #endif -------------------------------------------------------------------------------- /Seminar/Week 09/Examples/Person, Student, Teacher/Teacher/Teacher.cpp: -------------------------------------------------------------------------------- 1 | #include "Teacher.hpp" 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | Teacher::Teacher(char const *name, unsigned age, char const * const *subjects, size_t subjectsCount): Person(name, age){ 8 | 9 | this -> m_Subjects = new char *[subjectsCount]; 10 | 11 | for (size_t i = 0; i < subjectsCount; i++){ 12 | 13 | this -> m_Subjects[i] = new(std::nothrow) char[strlen(subjects[i]) + 1]; 14 | 15 | if(!this -> m_Subjects[i]){ 16 | 17 | Free(i); 18 | throw std::bad_alloc(); 19 | 20 | } 21 | 22 | strcpy(this -> m_Subjects[i], subjects[i]); 23 | 24 | } 25 | 26 | this -> m_SubjectsCount = subjectsCount; 27 | 28 | } 29 | 30 | Teacher::Teacher(Teacher const &other): Person(other){ 31 | Copy(other); //only the teacher stuff is copied 32 | } 33 | 34 | Teacher::Teacher(Teacher &&other): Person(other){ 35 | Move(std::move(other)); //only the teacher stuff is copied 36 | } 37 | 38 | Teacher& Teacher::operator=(const Teacher& other){ 39 | 40 | if (this == &other) return *this; 41 | 42 | *this = Teacher(other); 43 | 44 | return *this; 45 | 46 | } 47 | 48 | Teacher& Teacher::operator=(Teacher &&other){ 49 | 50 | if (this == &other) return *this; 51 | 52 | Person::operator=(other); //delete data of person + copy the data from person 53 | Free(m_SubjectsCount); 54 | Move(std::move(other)); 55 | 56 | return *this; 57 | 58 | } 59 | 60 | Teacher::~Teacher(){ 61 | Free(m_SubjectsCount); 62 | } // destr person 63 | 64 | void Teacher::Copy(Teacher const &other){ 65 | 66 | m_Subjects = new char* [other.m_SubjectsCount]; 67 | 68 | for (size_t i = 0; i < other.m_SubjectsCount; i++) 69 | { 70 | m_Subjects[i] = new char[strlen(other.m_Subjects[i]) + 1]; 71 | strcpy(m_Subjects[i], other.m_Subjects[i]); 72 | } 73 | 74 | m_SubjectsCount = other.m_SubjectsCount; 75 | } 76 | 77 | void Teacher::Move(Teacher &&other){ 78 | 79 | m_Subjects = std::exchange(other.m_Subjects, nullptr); 80 | m_SubjectsCount = other.m_SubjectsCount; 81 | 82 | } 83 | 84 | void Teacher::Free(size_t subjectsCount){ 85 | 86 | for(size_t i = 0; i < subjectsCount; i++) 87 | delete[] m_Subjects[i]; 88 | delete[] m_Subjects; 89 | 90 | } -------------------------------------------------------------------------------- /Seminar/Week 09/Examples/Person, Student, Teacher/Teacher/Teacher.hpp: -------------------------------------------------------------------------------- 1 | #ifndef __TEACHER_HPP 2 | #define __TEACHER_HPP 3 | 4 | #include "../Person/Person.h" 5 | #include 6 | 7 | class Teacher : public Person{ 8 | 9 | public: 10 | Teacher(char const *name, unsigned age, char const * const *subjects, size_t subjectsCount); 11 | Teacher(Teacher const &other); 12 | Teacher(Teacher &&other); 13 | ~Teacher(); 14 | 15 | Teacher &operator =(Teacher const &other); 16 | Teacher &operator =(Teacher &&other); 17 | 18 | private: 19 | void Copy(Teacher const &other); // само нещата, които са от Teacher 20 | void Move(Teacher &&other); // само нещата, които са от Teacher 21 | void Free(size_t subjectsCount); 22 | 23 | char **m_Subjects; 24 | size_t m_SubjectsCount; 25 | 26 | }; 27 | 28 | #endif -------------------------------------------------------------------------------- /Seminar/Week 09/Examples/forwardDeclaration/A.hpp: -------------------------------------------------------------------------------- 1 | #ifndef A_H 2 | #define A_H 3 | 4 | #include "B.h" 5 | 6 | class A : public B 7 | { 8 | }; 9 | 10 | #endif -------------------------------------------------------------------------------- /Seminar/Week 09/Examples/forwardDeclaration/B.hpp: -------------------------------------------------------------------------------- 1 | #ifndef B_H 2 | #define B_H 3 | 4 | class A; 5 | 6 | class B 7 | { 8 | private: 9 | A *instance; 10 | }; 11 | 12 | #endif -------------------------------------------------------------------------------- /Seminar/Week 10/Examples/polymorphism.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | class Vehicle 5 | { 6 | private: 7 | char *make; 8 | char *model; 9 | int horsepower; 10 | 11 | public: 12 | Vehicle() {} 13 | Vehicle(const Vehicle &objectToCopyFrom) {} 14 | Vehicle &operator=(const Vehicle &objectToCopyFrom) {} 15 | const char *getMake() const {} 16 | const char *getModel() const {} 17 | const int getHorsepower() const {} 18 | virtual void honk() 19 | { 20 | std::cout << "A vehicle honking\n"; 21 | } 22 | virtual ~Vehicle() {} 23 | }; 24 | 25 | class Car : public Vehicle 26 | { 27 | private: 28 | int seats; 29 | 30 | public: 31 | Car() : seats{1} {} 32 | void honk() 33 | { 34 | std::cout << "A car honking\n"; 35 | } 36 | const int getSeats() const {} 37 | }; 38 | 39 | class Motorcycle : public Vehicle 40 | { 41 | private: 42 | int capacityLuggage; 43 | 44 | public: 45 | Motorcycle() : capacityLuggage{0} {} 46 | const int getCapacity() const {} 47 | void honk() 48 | { 49 | std::cout << "A motorcycle has no horn\n"; 50 | } 51 | }; 52 | 53 | int main() 54 | { 55 | Vehicle v; 56 | Car c; 57 | Motorcycle m; 58 | v.honk(); 59 | c.honk(); 60 | m.honk(); 61 | Vehicle *v1 = new Motorcycle(), *v2 = new Car(); 62 | v1->honk(); 63 | v2->honk(); 64 | // std::vector vehicles{v1, v2, &v}; 65 | // for (size_t i = 0; i < vehicles.size(); i++) 66 | // { 67 | // vehicles[i]->honk(); 68 | // } 69 | } 70 | -------------------------------------------------------------------------------- /Seminar/Week 10/Examples/shape_polymorphism/Circle.cpp: -------------------------------------------------------------------------------- 1 | #include "Circle.h" 2 | 3 | const double PI = 3.1415; 4 | 5 | Circle::Circle(int x, int y, double radius): Shape(1), radius(radius){ 6 | SetPoint(0, x, y); 7 | } 8 | 9 | double Circle::GetArea() const{ 10 | return PI * radius * radius; 11 | } 12 | 13 | double Circle::GetPer() const{ 14 | return 2 * PI * radius; 15 | } 16 | 17 | bool Circle::IsPointIn(int x, int y) const{ 18 | return GetPointAtIndex(0).GetDistance(Shape::Point(x, y)) <= radius; 19 | } 20 | -------------------------------------------------------------------------------- /Seminar/Week 10/Examples/shape_polymorphism/Circle.h: -------------------------------------------------------------------------------- 1 | #ifndef __CIRCLE_H_ 2 | #define __CIRCLE_H_ 3 | 4 | #include "Shape.h" 5 | 6 | class Circle : public Shape{ 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 | private: 16 | double radius; 17 | 18 | }; 19 | 20 | #endif -------------------------------------------------------------------------------- /Seminar/Week 10/Examples/shape_polymorphism/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 | 12 | double Rectangle::GetArea() const{ 13 | 14 | Shape::Point p0 = GetPointAtIndex(0); 15 | Shape::Point p1 = GetPointAtIndex(1); 16 | Shape::Point p3 = GetPointAtIndex(3); 17 | 18 | return p0.GetDistance(p1) * p0.GetDistance(p3); 19 | 20 | } 21 | 22 | double Rectangle::GetPer() const{ 23 | 24 | Shape::Point p0 = GetPointAtIndex(0); 25 | Shape::Point p1 = GetPointAtIndex(1); 26 | Shape::Point p3 = GetPointAtIndex(3); 27 | 28 | return 2 * (p0.GetDistance(p1) + p0.GetDistance(p3)); 29 | 30 | } 31 | 32 | bool Rectangle::IsPointIn(int x, int y) const{ 33 | 34 | Shape::Point p(x, y); 35 | return p.x >= GetPointAtIndex(0).x && p.y >= GetPointAtIndex(1).x && 36 | p.y <= GetPointAtIndex(0).y && p.y >= GetPointAtIndex(2).y; 37 | 38 | } 39 | -------------------------------------------------------------------------------- /Seminar/Week 10/Examples/shape_polymorphism/Rectangle.h: -------------------------------------------------------------------------------- 1 | #ifndef __RECTANGLE_H_ 2 | #define __RECTANGLE_H_ 3 | 4 | #include "Shape.h" 5 | 6 | class Rectangle : public Shape{ 7 | 8 | public: 9 | Rectangle(int x1, int y1, int x3, int y3); 10 | double GetArea() const override; 11 | double GetPer() const override; 12 | bool IsPointIn(int x, int y) const override; 13 | 14 | }; 15 | 16 | #endif -------------------------------------------------------------------------------- /Seminar/Week 10/Examples/shape_polymorphism/Shape.cpp: -------------------------------------------------------------------------------- 1 | #include "Shape.h" 2 | #include 3 | #include 4 | #include 5 | 6 | Shape::Shape(size_t const numberOfPoints): m_NumberOfPoints(numberOfPoints){ 7 | m_Points = new Point[numberOfPoints]; // [0,0], [0,0].... 8 | } 9 | 10 | Shape::Shape(Shape const &other){ 11 | Copy(other); 12 | } 13 | 14 | Shape::Shape(Shape &&other){ 15 | Move(std::move(other)); 16 | } 17 | 18 | Shape &Shape::operator =(Shape const &other){ 19 | 20 | if(this == &other) return *this; 21 | 22 | Free(); 23 | Copy(other); 24 | 25 | return *this; 26 | 27 | } 28 | 29 | Shape &Shape::operator =(Shape &&other){ 30 | 31 | if(this == &other) return *this; 32 | 33 | Free(); 34 | Move(std::move(other)); 35 | 36 | return *this; 37 | 38 | } 39 | 40 | Shape::~Shape(){ 41 | Free(); 42 | } 43 | 44 | void Shape::SetPoint(size_t pointIndex, int x, int y){ 45 | 46 | if(pointIndex >= m_NumberOfPoints) throw std::out_of_range("Invalid Point index!"); 47 | m_Points[pointIndex] = Point(x, y); 48 | 49 | } 50 | 51 | double Shape::Point::GetDistance(Point const other) const{ 52 | 53 | int dx = x - other.x; 54 | int dy = y - other.y; 55 | 56 | return sqrt(dx * dx + dy * dy); 57 | 58 | } 59 | 60 | Shape::Point const Shape::GetPointAtIndex(size_t index) const{ 61 | 62 | if(index >= m_NumberOfPoints) throw std::out_of_range("Invalid Point index!"); 63 | return m_Points[index]; 64 | 65 | } 66 | 67 | void Shape::Copy(Shape const &other){ 68 | 69 | m_Points = new Point[other.m_NumberOfPoints]; 70 | 71 | for(size_t i = 0; i < other.m_NumberOfPoints; ++i) 72 | m_Points[i] = other.m_Points[i]; 73 | 74 | m_NumberOfPoints = other.m_NumberOfPoints; 75 | 76 | } 77 | 78 | void Shape::Move(Shape &&other){ 79 | 80 | m_Points = std::exchange(other.m_Points, nullptr); 81 | m_NumberOfPoints = other.m_NumberOfPoints; 82 | 83 | } 84 | 85 | void Shape::Free(){ 86 | delete[] m_Points; 87 | } -------------------------------------------------------------------------------- /Seminar/Week 10/Examples/shape_polymorphism/Shape.h: -------------------------------------------------------------------------------- 1 | #ifndef __SHAPE_H_ 2 | #define __SHAPE_H_ 3 | 4 | #include 5 | 6 | class Shape{ // Abstract class - no instances of Shape are allowed! 7 | 8 | public: 9 | Shape(size_t const pointsCount); 10 | 11 | Shape(Shape const &other); 12 | Shape(Shape &&other); 13 | 14 | virtual ~Shape(); //!!!!!! 15 | 16 | Shape &operator =(Shape const &other); 17 | Shape &operator =(Shape &&other); 18 | 19 | public: 20 | void SetPoint(size_t pointIndex, int x, int y); 21 | 22 | virtual double GetArea() const = 0; //pure virtual 23 | virtual double GetPer() const = 0; // pure virtual 24 | virtual bool IsPointIn(int x, int y) const = 0; 25 | 26 | protected: 27 | struct Point{ 28 | 29 | Point() = default; 30 | Point(int x, int y): x(x), y(y){} 31 | 32 | double GetDistance(Point const other) const; 33 | 34 | int x = 0, y = 0; 35 | 36 | }; 37 | 38 | Point const GetPointAtIndex(size_t index) const; 39 | 40 | private: 41 | void Copy(Shape const &other); 42 | void Move(Shape &&other); 43 | void Free(); 44 | 45 | private: 46 | Point* m_Points; 47 | size_t m_NumberOfPoints; 48 | 49 | }; 50 | 51 | #endif -------------------------------------------------------------------------------- /Seminar/Week 10/Examples/shape_polymorphism/Triangle.cpp: -------------------------------------------------------------------------------- 1 | #include "Triangle.h" 2 | #include 3 | 4 | double const EPSILON = 0.00001; 5 | 6 | Triangle::Triangle(int x1, int y1, int x2, int y2, int x3, int y3): Shape(3){ 7 | 8 | SetPoint(0, x1, y1); 9 | SetPoint(1, x2, y2); 10 | SetPoint(2, x3, y3); 11 | 12 | } 13 | 14 | double Triangle::GetArea() const{ 15 | 16 | Shape::Point p1 = GetPointAtIndex(0); 17 | Shape::Point p2 = GetPointAtIndex(1); 18 | Shape::Point p3 = GetPointAtIndex(2); 19 | 20 | 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; 21 | 22 | } 23 | 24 | double Triangle::GetPer() const{ 25 | 26 | Shape::Point p1 = GetPointAtIndex(0); 27 | Shape::Point p2 = GetPointAtIndex(1); 28 | Shape::Point p3 = GetPointAtIndex(2); 29 | 30 | return p1.GetDistance(p2) + p2.GetDistance(p3) + p3.GetDistance(p1); 31 | 32 | } 33 | 34 | bool Triangle::IsPointIn(int x, int y) const{ 35 | 36 | Shape::Point p(x, y); 37 | Triangle t1(GetPointAtIndex(0).x, GetPointAtIndex(0).y, GetPointAtIndex(1).x, GetPointAtIndex(1).y, p.x, p.y); 38 | Triangle t2(GetPointAtIndex(2).x, GetPointAtIndex(2).y, GetPointAtIndex(1).x, GetPointAtIndex(1).y, p.x, p.y); 39 | Triangle t3(GetPointAtIndex(2).x, GetPointAtIndex(2).y, GetPointAtIndex(0).x, GetPointAtIndex(0).y, p.x, p.y); 40 | 41 | return abs(t1.GetArea() + t2.GetArea() + t3.GetArea() - GetArea()) <= EPSILON; 42 | 43 | } -------------------------------------------------------------------------------- /Seminar/Week 10/Examples/shape_polymorphism/Triangle.h: -------------------------------------------------------------------------------- 1 | #ifndef __TRIANGLE_H_ 2 | #define __TRIANGLE_H_ 3 | 4 | #include "Shape.h" 5 | 6 | class Triangle : public Shape{ 7 | 8 | public: 9 | Triangle(int x1, int y1, int x2, int y2, int x3, int y3); 10 | double GetArea() const override; 11 | double GetPer() const override; 12 | bool IsPointIn(int x, int y) const override; 13 | 14 | }; 15 | 16 | #endif -------------------------------------------------------------------------------- /Seminar/Week 10/Examples/shape_polymorphism/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "Rectangle.h" 4 | #include "Circle.h" 5 | #include "Triangle.h" 6 | 7 | void PrintAreas(Shape **shapes, size_t shapesCount){ 8 | 9 | for(size_t i = 0; i < shapesCount; ++i) 10 | std::cout << shapes[i]->GetArea() << '\n'; 11 | } 12 | void PrintPers(Shape **shapes, size_t shapesCount){ 13 | 14 | for(size_t i = 0; i < shapesCount; ++i) 15 | std::cout << shapes[i]->GetPer() << '\n'; 16 | 17 | } 18 | 19 | void CheckPointIn(Shape **shapes, size_t shapesCount, int x, int y){ 20 | 21 | for(size_t i = 0; i < shapesCount; ++i) 22 | std::cout << shapes[i]->IsPointIn(x,y) << '\n'; 23 | 24 | } 25 | 26 | void FreeCollection(Shape **shapes, size_t shapesCount){ 27 | 28 | for(size_t i = 0; i < shapesCount; ++i) 29 | delete shapes[i]; 30 | delete[] shapes; 31 | 32 | } 33 | 34 | int main(){ 35 | 36 | Shape **arr = new Shape *[4]; 37 | 38 | arr[0] = new Rectangle(3, 4, 6, 8); 39 | arr[1] = new Circle(3, 3, 4); 40 | arr[2] = new Circle(1, 4, 5); 41 | arr[3] = new Triangle(1, 1, 2, 2, 3, 3); 42 | 43 | PrintAreas(arr, 4); 44 | std::cout << '\n'; 45 | 46 | PrintPers(arr, 4); 47 | std::cout << '\n'; 48 | 49 | CheckPointIn(arr, 4, 3, 3); 50 | 51 | FreeCollection(arr, 4); 52 | 53 | return 0; 54 | 55 | } 56 | -------------------------------------------------------------------------------- /Seminar/Week 10/Examples/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 | -------------------------------------------------------------------------------- /Seminar/Week 10/Examples/virtual_inheritance_layout.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | class I { 4 | public: 5 | int i; 6 | public: 7 | virtual void foo() { 8 | std::cout << "I::foo" << std::endl; 9 | } 10 | virtual void bar() { 11 | std::cout << "I::bar" << std::endl; 12 | } 13 | }; 14 | 15 | class C : virtual public I { 16 | public: 17 | int c1; 18 | int c2; 19 | 20 | public: 21 | virtual void foo() { 22 | std::cout << "C::foo" << std::endl; 23 | } 24 | }; 25 | 26 | class B : virtual public I { 27 | public: 28 | int b1; 29 | int b2; 30 | 31 | public: 32 | virtual void baz() { 33 | std::cout << "B::baz" << std::endl; 34 | } 35 | }; 36 | 37 | class A : public B, public C { 38 | public: 39 | int a1; 40 | int a2; 41 | 42 | public: 43 | virtual void seta1(int a) { 44 | a1 = a; 45 | } 46 | virtual void seta2(int a) { 47 | a2 = a; 48 | } 49 | }; 50 | 51 | int main() { 52 | 53 | A *a = new A(); 54 | B *b = a; 55 | C *c = a; 56 | I *i = a; 57 | 58 | int A::*ptm = &A::a1; 59 | int A::*ptm1 = &A::a2; 60 | int B::*ptm2 = &B::b1; 61 | int B::*ptm3 = &B::b2; 62 | int C::*ptm4 = &C::c1; 63 | int C::*ptm5 = &C::c2; 64 | int I::*ptm6 = &I::i; 65 | 66 | std::cout << "a: " << a << '\n'; 67 | std::cout << "Offsets:\n"; 68 | std::cout << "--------\n"; 69 | std::cout << "A - *v-table: " << (char *)a - (char *)a << '\n'; 70 | std::cout << "A - Fields:\na1: " << (char *)&(a->*ptm) - (char *)a << "\na2: " << (char *)&(a->*ptm1) - (char *)a << '\n'; 71 | std::cout << "--------\n"; 72 | std::cout << "B - *v-table: " << (char *)b - (char *)a << '\n'; 73 | std::cout << "B - Fields:\nb1: " << (char *)&(a->*ptm2) - (char *)a << "\nb2: " << (char *)&(a->*ptm3) - (char *)a << '\n'; 74 | std::cout << "--------\n"; 75 | std::cout << "C - *v-table: " << (char *)c - (char *)a << '\n'; 76 | std::cout << "C - Fields:\nc1: " << (char *)&(a->*ptm4) - (char *)a << "\nc2: " << (char *)&(a->*ptm5) - (char *)a << '\n'; 77 | std::cout << "--------\n"; 78 | std::cout << "I - *v-table: " << (char *)i - (char *)a << '\n'; 79 | std::cout << "I - Fields:\nc1: " << (char *)&(a->*ptm6) - (char *)a << '\n'; 80 | 81 | return 0; 82 | } -------------------------------------------------------------------------------- /Seminar/Week 11/Examples/Farm/Animals/Animal.hpp: -------------------------------------------------------------------------------- 1 | #ifndef __ANIMAL_HPP_ 2 | #define __ANIMAL_HPP_ 3 | 4 | class Animal{ 5 | 6 | public: 7 | virtual ~Animal() noexcept {} //!!! 8 | 9 | virtual void Talk() const = 0; 10 | virtual Animal *Clone() const = 0; //!!! 11 | 12 | }; 13 | 14 | #endif -------------------------------------------------------------------------------- /Seminar/Week 11/Examples/Farm/Animals/Cat.cpp: -------------------------------------------------------------------------------- 1 | #include "Cat.hpp" 2 | #include 3 | 4 | void Cat::Talk() const{ 5 | std::cout << "Hello, I am a Cat!\n"; 6 | } 7 | 8 | Animal *Cat::Clone() const{ 9 | return new Cat(*this); 10 | } -------------------------------------------------------------------------------- /Seminar/Week 11/Examples/Farm/Animals/Cat.hpp: -------------------------------------------------------------------------------- 1 | #ifndef __CAT_HPP_ 2 | #define __CAT_HPP_ 3 | 4 | #include "Animal.hpp" 5 | 6 | class Cat : public Animal{ 7 | 8 | public: 9 | void Talk() const override; 10 | Animal *Clone() const override; 11 | 12 | }; 13 | 14 | #endif -------------------------------------------------------------------------------- /Seminar/Week 11/Examples/Farm/Animals/Dog.cpp: -------------------------------------------------------------------------------- 1 | #include "Dog.hpp" 2 | #include 3 | 4 | void Dog::Talk() const{ 5 | std::cout << "Hello, I am a Dog!\n"; 6 | } 7 | 8 | Animal *Dog::Clone() const{ 9 | return new Dog(*this);; 10 | } -------------------------------------------------------------------------------- /Seminar/Week 11/Examples/Farm/Animals/Dog.hpp: -------------------------------------------------------------------------------- 1 | #ifndef __DOG_HPP_ 2 | #define __DOG_HPP_ 3 | 4 | #include "Animal.hpp" 5 | 6 | class Dog : public Animal{ 7 | 8 | public: 9 | void Talk() const override; 10 | Animal *Clone() const override; 11 | 12 | }; 13 | 14 | #endif -------------------------------------------------------------------------------- /Seminar/Week 11/Examples/Farm/Animals/Mouse.cpp: -------------------------------------------------------------------------------- 1 | #include "Mouse.hpp" 2 | #include 3 | 4 | void Mouse::Talk() const{ 5 | std::cout << "Hello, I am a Mouse!\n"; 6 | } 7 | 8 | Animal *Mouse::Clone() const{ 9 | return new Mouse(*this); 10 | } -------------------------------------------------------------------------------- /Seminar/Week 11/Examples/Farm/Animals/Mouse.hpp: -------------------------------------------------------------------------------- 1 | #ifndef __MOUSE_HPP_ 2 | #define __MOUSE_HPP_ 3 | 4 | #include "Animal.hpp" 5 | 6 | class Mouse : public Animal{ 7 | 8 | public: 9 | void Talk() const override; 10 | Animal *Clone() const override; 11 | 12 | }; 13 | 14 | #endif -------------------------------------------------------------------------------- /Seminar/Week 11/Examples/Farm/Collection/Farm.cpp: -------------------------------------------------------------------------------- 1 | #include "Farm.hpp" 2 | #include 3 | 4 | Farm::Farm(): m_Capacity(4), m_Size(0), m_Animals(new Animal *[m_Capacity]){} 5 | 6 | Farm::Farm(Farm const &other){ 7 | Copy(other); 8 | } 9 | 10 | Farm::Farm(Farm &&other) noexcept{ 11 | Move(std::move(other)); 12 | } 13 | 14 | Farm &Farm::operator =(Farm const &other){ 15 | 16 | if(this == &other) return *this; 17 | 18 | *this = Farm(other); 19 | 20 | return *this; 21 | 22 | } 23 | 24 | Farm &Farm::operator =(Farm &&other) noexcept{ 25 | 26 | if(this == &other) return *this; 27 | 28 | Free(); 29 | Move(std::move(other)); 30 | 31 | return *this; 32 | 33 | } 34 | 35 | Farm::~Farm(){ 36 | Free(); 37 | } 38 | 39 | void Farm::AddAnimal(Animal const *new_animal){ 40 | 41 | if(m_Size == m_Capacity) Resize(); 42 | m_Animals[m_Size++] = new_animal -> Clone(); 43 | 44 | } 45 | 46 | void Farm::AllTalk() const{ 47 | 48 | for(size_t i = 0; i < m_Size; i++) 49 | m_Animals[i] -> Talk(); 50 | 51 | } 52 | 53 | void Farm::Resize(){ 54 | 55 | Animal **newCollection = new Animal *[m_Capacity *= 2]; 56 | for(size_t i = 0; i < m_Size; i++) 57 | newCollection[i] = m_Animals[i]; 58 | 59 | delete[] m_Animals; 60 | m_Animals = newCollection; 61 | 62 | } 63 | 64 | void Farm::Copy(Farm const &other){ 65 | 66 | m_Animals = new Animal *[other.m_Capacity]; 67 | m_Capacity = other.m_Capacity; 68 | m_Size = other.m_Size; 69 | 70 | for(size_t i = 0; i < m_Size; i++) 71 | m_Animals[i] = other.m_Animals[i] -> Clone(); 72 | 73 | } 74 | 75 | void Farm::Move(Farm &&other) noexcept{ 76 | 77 | m_Animals = std::exchange(other.m_Animals, nullptr); 78 | m_Capacity = other.m_Capacity; 79 | m_Size = other.m_Size; 80 | 81 | } 82 | 83 | void Farm::Free() noexcept{ 84 | 85 | for(size_t i = 0; i < m_Size; i++) 86 | delete m_Animals[i]; 87 | delete[] m_Animals; 88 | m_Animals = nullptr; 89 | 90 | } -------------------------------------------------------------------------------- /Seminar/Week 11/Examples/Farm/Collection/Farm.hpp: -------------------------------------------------------------------------------- 1 | #ifndef __FARM_HPP_ 2 | #define __FARM_HPP_ 3 | 4 | #include "../Animals/Animal.hpp" 5 | #include 6 | 7 | class Farm{ 8 | 9 | public: 10 | Farm(); 11 | Farm(Farm const &other); 12 | Farm(Farm &&other) noexcept; 13 | Farm &operator=(Farm const &other); 14 | Farm &operator=(Farm &&other) noexcept; 15 | ~Farm() noexcept; 16 | 17 | void AddAnimal(Animal const *animal); 18 | 19 | void AllTalk() const; 20 | 21 | private: 22 | void Resize(); 23 | void Copy(Farm const &other); 24 | void Move(Farm &&other) noexcept; 25 | void Free() noexcept; 26 | 27 | private: 28 | size_t m_Size, m_Capacity; 29 | Animal **m_Animals; 30 | 31 | }; 32 | 33 | #endif -------------------------------------------------------------------------------- /Seminar/Week 11/Examples/Farm/Factory/Factory.cpp: -------------------------------------------------------------------------------- 1 | #include "Factory.hpp" 2 | #include "../Animals/Cat.hpp" 3 | #include "../Animals/Dog.hpp" 4 | #include "../Animals/Mouse.hpp" 5 | 6 | Animal *Factory(AnimalType type){ 7 | 8 | switch (type){ 9 | 10 | case AnimalType::Cat: return new Cat; 11 | case AnimalType::Dog: return new Dog; 12 | case AnimalType::Mouse: return new Mouse; 13 | 14 | default: return nullptr; 15 | 16 | } 17 | 18 | } -------------------------------------------------------------------------------- /Seminar/Week 11/Examples/Farm/Factory/Factory.hpp: -------------------------------------------------------------------------------- 1 | #ifndef __FACTORY_HPP_ 2 | #define __FACTORY_HPP_ 3 | 4 | #include "../Animals/Animal.hpp" 5 | 6 | enum class AnimalType{ 7 | Cat, 8 | Dog, 9 | Mouse 10 | }; 11 | 12 | Animal *Factory(AnimalType type); 13 | 14 | #endif -------------------------------------------------------------------------------- /Seminar/Week 11/Examples/Farm/source.cpp: -------------------------------------------------------------------------------- 1 | #include "Collection/Farm.hpp" 2 | #include "Factory/Factory.hpp" 3 | #include 4 | #include 5 | 6 | int main(){ 7 | 8 | try{ 9 | 10 | Farm f; 11 | f.AddAnimal(Factory(AnimalType::Cat)); 12 | f.AddAnimal(Factory(AnimalType::Dog)); 13 | 14 | f.AllTalk(); 15 | 16 | } 17 | catch(std::bad_alloc){ 18 | std::cerr << "Bad alloc\n"; 19 | } 20 | 21 | return 0; 22 | 23 | } -------------------------------------------------------------------------------- /Seminar/Week 11/Examples/ShapeCollection/ShapeCollection/ShapeCollection.hpp: -------------------------------------------------------------------------------- 1 | #ifndef __SHAPE_COLLECTION_ 2 | #define __SHAPE_COLLECTION_ 3 | 4 | #include "../Shapes/Shape.hpp" 5 | 6 | class ShapeCollection{ 7 | 8 | public: 9 | ShapeCollection(); 10 | ShapeCollection(ShapeCollection const &); 11 | ShapeCollection(ShapeCollection &&) noexcept; 12 | ShapeCollection &operator =(ShapeCollection const &); 13 | ShapeCollection &operator =(ShapeCollection &&) noexcept; 14 | ~ShapeCollection() noexcept; 15 | 16 | void AddShape(Shape * const shape); 17 | 18 | Shape *&operator [](size_t index); 19 | Shape * const operator [](size_t index) const; 20 | 21 | size_t Size() const; 22 | size_t Capacity() const; 23 | bool Empty() const; 24 | 25 | private: 26 | void Resize(); 27 | void Copy(ShapeCollection const &other); 28 | void Move(ShapeCollection &&other) noexcept; 29 | void Free() noexcept; 30 | 31 | private: 32 | size_t m_Size = 0, m_Capacity = 0; 33 | Shape **m_Shapes = nullptr; 34 | 35 | }; 36 | 37 | #endif -------------------------------------------------------------------------------- /Seminar/Week 11/Examples/ShapeCollection/Shapes/Circle.cpp: -------------------------------------------------------------------------------- 1 | #include "Circle.hpp" 2 | 3 | Circle::Circle(int x, int y, double radius): Shape(1), m_Radius(radius){ 4 | SetPoint(0, x, y); 5 | } 6 | 7 | double Circle::GetArea() const{ 8 | return PI * m_Radius * m_Radius; 9 | } 10 | 11 | double Circle::GetPer() const{ 12 | return 2 * PI * m_Radius; 13 | } 14 | 15 | bool Circle::IsPointIn(int x, int y) const{ 16 | return GetPointAtIndex(0).GetDistance(Shape::Point(x, y)) <= m_Radius; 17 | } 18 | 19 | Shape *Circle::Clone() const{ 20 | return new Circle(*this); 21 | } -------------------------------------------------------------------------------- /Seminar/Week 11/Examples/ShapeCollection/Shapes/Circle.hpp: -------------------------------------------------------------------------------- 1 | #ifndef __CIRCLE_H_ 2 | #define __CIRCLE_H_ 3 | 4 | #include "Shape.hpp" 5 | 6 | class Circle : public Shape{ 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 | 16 | private: 17 | static constexpr double PI = 3.1415; 18 | double m_Radius; 19 | 20 | }; 21 | 22 | #endif -------------------------------------------------------------------------------- /Seminar/Week 11/Examples/ShapeCollection/Shapes/Rectangle.cpp: -------------------------------------------------------------------------------- 1 | #include "Rectangle.hpp" 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 | 12 | double Rectangle::GetArea() const{ 13 | 14 | Shape::Point p0 = GetPointAtIndex(0); 15 | Shape::Point p1 = GetPointAtIndex(1); 16 | Shape::Point p3 = GetPointAtIndex(3); 17 | 18 | return p0.GetDistance(p1) * p0.GetDistance(p3); 19 | 20 | } 21 | 22 | double Rectangle::GetPer() const{ 23 | 24 | Shape::Point p0 = GetPointAtIndex(0); 25 | Shape::Point p1 = GetPointAtIndex(1); 26 | Shape::Point p3 = GetPointAtIndex(3); 27 | 28 | return 2 * (p0.GetDistance(p1) + p0.GetDistance(p3)); 29 | 30 | } 31 | 32 | bool Rectangle::IsPointIn(int x, int y) const{ 33 | 34 | Shape::Point p(x, y); 35 | return GetPointAtIndex(0).x <= p.x && p.x <= GetPointAtIndex(2).x 36 | && GetPointAtIndex(0).y <= p.y && p.y <= GetPointAtIndex(2).y; 37 | 38 | } 39 | 40 | Shape *Rectangle::Clone() const{ 41 | return new Rectangle(*this); 42 | } -------------------------------------------------------------------------------- /Seminar/Week 11/Examples/ShapeCollection/Shapes/Rectangle.hpp: -------------------------------------------------------------------------------- 1 | #ifndef __RECTANGLE_H_ 2 | #define __RECTANGLE_H_ 3 | 4 | #include "Shape.hpp" 5 | 6 | class Rectangle : public Shape{ 7 | 8 | public: 9 | Rectangle(int x1, int y1, int x3, int y3); 10 | double GetArea() const override; 11 | double GetPer() const override; 12 | bool IsPointIn(int x, int y) const override; 13 | Shape *Clone() const override; 14 | 15 | }; 16 | 17 | #endif -------------------------------------------------------------------------------- /Seminar/Week 11/Examples/ShapeCollection/Shapes/Shape.cpp: -------------------------------------------------------------------------------- 1 | #include "Shape.hpp" 2 | #include 3 | #include 4 | #include 5 | 6 | Shape::Shape(size_t const numberOfPoints): m_NumberOfPoints(numberOfPoints){ 7 | m_Points = new Point[numberOfPoints]; // [0,0], [0,0].... 8 | } 9 | 10 | Shape::Shape(Shape const &other){ 11 | Copy(other); 12 | } 13 | 14 | Shape::Shape(Shape &&other) noexcept{ 15 | Move(std::move(other)); 16 | } 17 | 18 | Shape &Shape::operator =(Shape const &other){ 19 | 20 | if(this == &other) return *this; 21 | 22 | Free(); 23 | Copy(other); 24 | 25 | return *this; 26 | 27 | } 28 | 29 | Shape &Shape::operator =(Shape &&other) noexcept{ 30 | 31 | if(this == &other) return *this; 32 | 33 | Free(); 34 | Move(std::move(other)); 35 | 36 | return *this; 37 | 38 | } 39 | 40 | Shape::~Shape() noexcept{ 41 | Free(); 42 | } 43 | 44 | void Shape::SetPoint(size_t pointIndex, int x, int y){ 45 | 46 | if(pointIndex >= m_NumberOfPoints) throw std::out_of_range("Invalid Point index!"); 47 | m_Points[pointIndex] = Point(x, y); 48 | 49 | } 50 | 51 | double Shape::Point::GetDistance(Point const other) const{ 52 | 53 | int dx = x - other.x; 54 | int dy = y - other.y; 55 | 56 | return sqrt(dx * dx + dy * dy); 57 | 58 | } 59 | 60 | Shape::Point const Shape::GetPointAtIndex(size_t index) const{ 61 | 62 | if(index >= m_NumberOfPoints) throw std::out_of_range("Invalid Point index!"); 63 | return m_Points[index]; 64 | 65 | } 66 | 67 | void Shape::Copy(Shape const &other){ 68 | 69 | m_Points = new Point[other.m_NumberOfPoints]; 70 | 71 | for(size_t i = 0; i < other.m_NumberOfPoints; ++i) 72 | m_Points[i] = other.m_Points[i]; 73 | 74 | m_NumberOfPoints = other.m_NumberOfPoints; 75 | 76 | } 77 | 78 | void Shape::Move(Shape &&other) noexcept{ 79 | 80 | m_Points = std::exchange(other.m_Points, nullptr); 81 | m_NumberOfPoints = other.m_NumberOfPoints; 82 | 83 | } 84 | 85 | void Shape::Free() noexcept{ 86 | delete[] m_Points; 87 | } -------------------------------------------------------------------------------- /Seminar/Week 11/Examples/ShapeCollection/Shapes/Shape.hpp: -------------------------------------------------------------------------------- 1 | #ifndef __SHAPE_H_ 2 | #define __SHAPE_H_ 3 | 4 | #include 5 | 6 | class Shape{ // Abstract class - no instances of Shape are allowed! 7 | 8 | public: 9 | Shape(size_t const pointsCount); 10 | 11 | Shape(Shape const &other); 12 | Shape(Shape &&other) noexcept; 13 | 14 | Shape &operator =(Shape const &other); 15 | Shape &operator =(Shape &&other) noexcept; 16 | 17 | virtual ~Shape() noexcept; //!!!!!! 18 | 19 | public: 20 | void SetPoint(size_t pointIndex, int x, int y); 21 | 22 | virtual double GetArea() const = 0; //pure virtual 23 | virtual double GetPer() const = 0; // pure virtual 24 | virtual bool IsPointIn(int x, int y) const = 0; 25 | virtual Shape *Clone() const = 0; 26 | 27 | protected: 28 | struct Point{ 29 | 30 | Point() = default; 31 | Point(int x, int y): x(x), y(y){} 32 | 33 | double GetDistance(Point const other) const; 34 | 35 | int x = 0, y = 0; 36 | 37 | }; 38 | 39 | Point const GetPointAtIndex(size_t index) const; 40 | 41 | private: 42 | void Copy(Shape const &other); 43 | void Move(Shape &&other) noexcept; 44 | void Free() noexcept; 45 | 46 | private: 47 | Point *m_Points = nullptr; 48 | size_t m_NumberOfPoints = 0; 49 | 50 | }; 51 | 52 | #endif -------------------------------------------------------------------------------- /Seminar/Week 11/Examples/ShapeCollection/Shapes/Triangle.cpp: -------------------------------------------------------------------------------- 1 | #include "Triangle.hpp" 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 | 12 | double Triangle::GetArea() const{ 13 | 14 | Shape::Point p1 = GetPointAtIndex(0); 15 | Shape::Point p2 = GetPointAtIndex(1); 16 | Shape::Point p3 = GetPointAtIndex(2); 17 | 18 | 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; 19 | 20 | } 21 | 22 | double Triangle::GetPer() const{ 23 | 24 | Shape::Point p1 = GetPointAtIndex(0); 25 | Shape::Point p2 = GetPointAtIndex(1); 26 | Shape::Point p3 = GetPointAtIndex(2); 27 | 28 | return p1.GetDistance(p2) + p2.GetDistance(p3) + p3.GetDistance(p1); 29 | 30 | } 31 | 32 | bool Triangle::IsPointIn(int x, int y) const{ 33 | 34 | Shape::Point p(x, y); 35 | Triangle t1(GetPointAtIndex(0).x, GetPointAtIndex(0).y, GetPointAtIndex(1).x, GetPointAtIndex(1).y, p.x, p.y); 36 | Triangle t2(GetPointAtIndex(2).x, GetPointAtIndex(2).y, GetPointAtIndex(1).x, GetPointAtIndex(1).y, p.x, p.y); 37 | Triangle t3(GetPointAtIndex(2).x, GetPointAtIndex(2).y, GetPointAtIndex(0).x, GetPointAtIndex(0).y, p.x, p.y); 38 | 39 | return abs(t1.GetArea() + t2.GetArea() + t3.GetArea() - GetArea()) <= EPSILON; 40 | 41 | } 42 | 43 | Shape *Triangle::Clone() const{ 44 | return new Triangle(*this); 45 | } -------------------------------------------------------------------------------- /Seminar/Week 11/Examples/ShapeCollection/Shapes/Triangle.hpp: -------------------------------------------------------------------------------- 1 | #ifndef __TRIANGLE_H_ 2 | #define __TRIANGLE_H_ 3 | 4 | #include "Shape.hpp" 5 | 6 | class Triangle : public Shape{ 7 | 8 | public: 9 | Triangle(int x1, int y1, int x2, int y2, int x3, int y3); 10 | double GetArea() const override; 11 | double GetPer() const override; 12 | bool IsPointIn(int x, int y) const override; 13 | Shape *Clone() const override; 14 | 15 | private: 16 | static constexpr double EPSILON = 0.00001; 17 | 18 | }; 19 | 20 | #endif -------------------------------------------------------------------------------- /Seminar/Week 11/Examples/ShapeCollection/main.cpp: -------------------------------------------------------------------------------- 1 | #include "ShapeCollection/ShapeCollection.hpp" 2 | #include "Factory/Factory.hpp" 3 | #include 4 | 5 | int main(){ 6 | 7 | ShapeCollection s; 8 | 9 | s.AddShape(Factory(ShapeType::Rectangle, 1, 1, 9, 9)); 10 | s.AddShape(Factory(ShapeType::Triangle, 1, 2, 9, 4, 0, 0)); 11 | s.AddShape(Factory(ShapeType::Circle, 3, 4, 1)); 12 | 13 | std::cout << std::boolalpha << s[0] -> IsPointIn(3, 4.5) << '\n'; 14 | std::cout << s[2] -> GetArea() << '\n'; 15 | 16 | } 17 | -------------------------------------------------------------------------------- /Seminar/Week 11/Examples/Students/Factory/Factory.cpp: -------------------------------------------------------------------------------- 1 | #include "Factory.hpp" 2 | #include "../Student Types/LazyStudent.hpp" 3 | #include "../Student Types/MotivatedStudent.hpp" 4 | 5 | Student *Factory(StudentType type, char const *name, size_t fn){ 6 | 7 | switch (type){ 8 | case StudentType::LazyStudent: return new LazyStudent(name, fn); 9 | case StudentType::MotivatedStudent: return new MotivatedStudent(name, fn); 10 | 11 | default: return nullptr; 12 | } 13 | 14 | } -------------------------------------------------------------------------------- /Seminar/Week 11/Examples/Students/Factory/Factory.hpp: -------------------------------------------------------------------------------- 1 | #ifndef __FACTORY_HPP_ 2 | #define __FACTORY_HPP_ 3 | 4 | #include "../Student Types/Student.hpp" 5 | 6 | enum class StudentType{ 7 | LazyStudent, 8 | MotivatedStudent 9 | }; 10 | 11 | Student *Factory(StudentType type, char const *name, size_t fn); 12 | 13 | #endif -------------------------------------------------------------------------------- /Seminar/Week 11/Examples/Students/Major/Major.hpp: -------------------------------------------------------------------------------- 1 | #ifndef __MAJOR_HPP_ 2 | #define __MAJOR_HPP_ 3 | 4 | #include "../Student Types/Student.hpp" 5 | 6 | class Major{ 7 | 8 | public: 9 | Major(); 10 | Major(Major const &other); 11 | Major(Major &&other); 12 | ~Major(); 13 | 14 | Major &operator =(Major const &other); 15 | Major &operator =(Major &&other); 16 | 17 | private: 18 | void Resize(size_t newCapacity); 19 | void Copy(Major const &other); 20 | void Move(Major &&other); 21 | void Free(); 22 | 23 | public: 24 | Student *&operator [](size_t index); 25 | Student const *operator [](size_t index) const; 26 | 27 | public: 28 | void AddStudent(Student *student); 29 | void YeetFromUni(size_t index); 30 | void SwapMajor(size_t index, Major &other); 31 | 32 | public: 33 | size_t Size() const; 34 | size_t TakeExam() const; 35 | bool IsAdequateMajor() const; 36 | 37 | private: 38 | size_t m_Size = 0, m_Capacity = 8; 39 | Student **m_Students = nullptr; 40 | 41 | }; 42 | 43 | #endif -------------------------------------------------------------------------------- /Seminar/Week 11/Examples/Students/Student Types/LazyStudent.cpp: -------------------------------------------------------------------------------- 1 | #include "LazyStudent.hpp" 2 | 3 | LazyStudent::LazyStudent(char const *name, size_t fn): Student(name, fn){} 4 | 5 | double LazyStudent::PercentageToPassTheExam() const{ 6 | return 0.2; 7 | } 8 | 9 | unsigned LazyStudent::HoursSpentPerDayStudying() const{ 10 | return 1; 11 | } 12 | 13 | Student *LazyStudent::Clone() const{ 14 | return new LazyStudent(*this); 15 | } -------------------------------------------------------------------------------- /Seminar/Week 11/Examples/Students/Student Types/LazyStudent.hpp: -------------------------------------------------------------------------------- 1 | #ifndef __LAZY_STUDENT_HPP_ 2 | #define __LAZY_STUDENT_HPP_ 3 | 4 | #include "Student.hpp" 5 | 6 | class LazyStudent : public Student{ 7 | 8 | public: 9 | LazyStudent(char const *name, size_t fn); 10 | 11 | public: 12 | double PercentageToPassTheExam() const override; 13 | unsigned HoursSpentPerDayStudying() const override; 14 | Student *Clone() const override; 15 | 16 | }; 17 | 18 | #endif -------------------------------------------------------------------------------- /Seminar/Week 11/Examples/Students/Student Types/MotivatedStudent.cpp: -------------------------------------------------------------------------------- 1 | #include "MotivatedStudent.hpp" 2 | 3 | MotivatedStudent::MotivatedStudent(char const *name, size_t fn): Student(name, fn){} 4 | 5 | double MotivatedStudent::PercentageToPassTheExam() const{ 6 | return 0.75; 7 | } 8 | 9 | unsigned MotivatedStudent::HoursSpentPerDayStudying() const{ 10 | return 16; 11 | } 12 | 13 | Student *MotivatedStudent::Clone() const{ 14 | return new MotivatedStudent(*this); 15 | } -------------------------------------------------------------------------------- /Seminar/Week 11/Examples/Students/Student Types/MotivatedStudent.hpp: -------------------------------------------------------------------------------- 1 | #ifndef __MOTIVATED_STUDENT_HPP_ 2 | #define __MOTIVATED_STUDENT_HPP_ 3 | 4 | #include "Student.hpp" 5 | 6 | class MotivatedStudent : public Student{ 7 | 8 | public: 9 | MotivatedStudent(char const *name, size_t fn); 10 | 11 | public: 12 | double PercentageToPassTheExam() const override; 13 | unsigned HoursSpentPerDayStudying() const override; 14 | Student *Clone() const override; 15 | 16 | }; 17 | 18 | #endif -------------------------------------------------------------------------------- /Seminar/Week 11/Examples/Students/Student Types/Student.cpp: -------------------------------------------------------------------------------- 1 | #include "Student.hpp" 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | size_t Student::numberOfStudentsCreated = 0; 8 | 9 | Student::Student(char const *name, size_t fn){ 10 | 11 | if(!name) throw std::invalid_argument("Name must not be a nullptr"); 12 | if(9'999 >= fn || fn >= 100'000) throw std::invalid_argument("Fn is not in the correct format"); 13 | 14 | m_Name = new char[strlen(name) + 1]; 15 | strcpy(m_Name, name); 16 | m_Fn = fn; 17 | ++numberOfStudentsCreated; 18 | 19 | } 20 | 21 | Student::Student(Student const &other){ 22 | Copy(other); 23 | } 24 | 25 | Student::Student(Student &&other) noexcept{ 26 | Move(std::move(other)); 27 | } 28 | 29 | Student::~Student() noexcept{ 30 | // Unalive student 31 | --numberOfStudentsCreated; 32 | Free(); 33 | } 34 | 35 | Student &Student::operator =(Student const &other){ 36 | 37 | if(this == &other) return *this; 38 | 39 | char *newName = new char[strlen(m_Name) + 1]; 40 | strcpy(newName, other.m_Name); 41 | Free(); 42 | m_Name = newName; 43 | strcpy(m_Name, newName); 44 | m_Fn = other.m_Fn; 45 | 46 | return *this; 47 | 48 | } 49 | 50 | Student &Student::operator =(Student &&other) noexcept{ 51 | 52 | if(this == &other) return *this; 53 | 54 | Free(); 55 | Move(std::move(other)); 56 | 57 | return *this; 58 | 59 | } 60 | 61 | char const *Student::GetName() const{ 62 | return m_Name; 63 | } 64 | 65 | size_t Student::GetFN() const{ 66 | return m_Fn; 67 | } 68 | 69 | size_t Student::AliveStudents(){ 70 | return numberOfStudentsCreated; 71 | } 72 | 73 | void Student::Copy(Student const &other){ 74 | 75 | m_Name = new char[strlen(other.m_Name) + 1]; 76 | strcpy(m_Name, other.m_Name); 77 | m_Fn = other.m_Fn; 78 | 79 | } 80 | 81 | void Student::Move(Student &&other) noexcept{ 82 | 83 | m_Name = std::exchange(other.m_Name, nullptr); 84 | m_Fn = other.m_Fn; 85 | 86 | } 87 | 88 | void Student::Free() noexcept{ 89 | delete m_Name; 90 | } -------------------------------------------------------------------------------- /Seminar/Week 11/Examples/Students/Student Types/Student.hpp: -------------------------------------------------------------------------------- 1 | #ifndef __STUDENT_HPP_ 2 | #define __STUDENT_HPP_ 3 | 4 | #include 5 | 6 | class Student{ 7 | 8 | public: 9 | Student(char const *name, size_t fn); 10 | Student(Student const &other); 11 | Student(Student &&other) noexcept; 12 | virtual ~Student() noexcept; 13 | 14 | Student &operator =(Student const &other); 15 | Student &operator =(Student &&other) noexcept; 16 | 17 | private: 18 | void Copy(Student const &other); 19 | void Move(Student &&other) noexcept; 20 | void Free() noexcept; 21 | 22 | public: 23 | char const *GetName() const; 24 | size_t GetFN() const; 25 | 26 | public: 27 | virtual double PercentageToPassTheExam() const = 0; 28 | virtual unsigned HoursSpentPerDayStudying() const = 0; 29 | virtual Student *Clone() const = 0; 30 | 31 | public: 32 | static size_t AliveStudents(); 33 | 34 | private: 35 | static size_t numberOfStudentsCreated; 36 | char *m_Name = nullptr; 37 | size_t m_Fn = 0; 38 | 39 | }; 40 | 41 | #endif -------------------------------------------------------------------------------- /Seminar/Week 11/Examples/Students/main.cpp: -------------------------------------------------------------------------------- 1 | #include "Major/Major.hpp" 2 | #include "Factory/Factory.hpp" 3 | #include 4 | 5 | int main(){ 6 | 7 | try{ 8 | 9 | Major major; 10 | Student *ptr = Factory(StudentType::LazyStudent, "Hristo", 21312); 11 | major.AddStudent(ptr); 12 | delete ptr; 13 | ptr = Factory(StudentType::MotivatedStudent, "Nikoleta", 44444); 14 | major.AddStudent(ptr); 15 | delete ptr; 16 | ptr = Factory(StudentType::LazyStudent, "Andrey", 11111); 17 | major.AddStudent(ptr); 18 | delete ptr; 19 | ptr = Factory(StudentType::MotivatedStudent, "Bogdan", 33333); 20 | major.AddStudent(ptr); 21 | delete ptr; 22 | 23 | std::cout << major.TakeExam() << '\n'; 24 | std::cout << std::boolalpha << major.IsAdequateMajor() << '\n'; 25 | 26 | for(size_t i = 0; i < major.Size(); ++i) 27 | std::cout << major[i] -> GetName() << ' ' << major[i] -> HoursSpentPerDayStudying() << '\n'; 28 | 29 | } 30 | catch(std::bad_alloc&){ 31 | std::cerr << "Bad alloc\n"; 32 | } 33 | catch(std::invalid_argument const &ex){ 34 | std::cerr << ex.what() << '\n'; 35 | } 36 | catch(std::out_of_range const &ex){ 37 | std::cerr << ex.what() << '\n'; 38 | } 39 | 40 | return 0; 41 | 42 | } --------------------------------------------------------------------------------