├── .gitignore ├── Bonus ├── Task.md └── consultation │ ├── lines_struct.cpp │ ├── old_exam.cpp │ └── recursion.cpp ├── Exams ├── Exam02 │ ├── README.md │ ├── Task01.cpp │ ├── Task02.cpp │ └── Task02_universal.cpp ├── Exam03 │ ├── task01.cpp │ ├── task02.cpp │ ├── task03.cpp │ └── tasks.pdf └── Exam04 │ ├── K04_var1.pdf │ ├── K04_var2.pdf │ ├── var01.cpp │ └── var02.cpp ├── Instructions ├── Compilation.md └── GitHub Workflow │ ├── README.md │ └── images │ ├── fetch-origin.png │ ├── repository-fork-settings.png │ ├── repository-settings-menu.png │ └── star-the-repo.png ├── LICENSE ├── README.md ├── Sem. 01 ├── Pract. 01 │ ├── AdditionalTasks.md │ ├── README.md │ └── Theory.md ├── README.md └── Solutions │ ├── Task01.cpp │ ├── Task02.cpp │ ├── Task03.cpp │ ├── Task04.cpp │ ├── Task05.cpp │ ├── Task06.cpp │ ├── Task07.cpp │ ├── Task08.cpp │ └── Task09.cpp ├── Sem. 02 ├── Pract.02 │ ├── README.md │ ├── Task03.cpp │ ├── Task10.cpp │ ├── Task12.cpp │ ├── Task13.cpp │ ├── Task14.cpp │ ├── Task15.cpp │ ├── Task16.cpp │ ├── Task17.cpp │ └── Theory.md ├── README.md └── Solutions │ ├── Task01.cpp │ ├── Task02.cpp │ ├── Task03.cpp │ ├── Task04.cpp │ ├── Task05.cpp │ ├── Task06.cpp │ └── Task07.cpp ├── Sem. 03 ├── Pract.03 │ ├── README.md │ ├── Task01.cpp │ ├── Task02.cpp │ ├── Task04.cpp │ ├── Task05.cpp │ ├── Task06.1.cpp │ ├── Task06.cpp │ ├── Task07.cpp │ ├── Task08.cpp │ ├── Task09.cpp │ ├── Task10.cpp │ ├── Task11.cpp │ ├── Task12.cpp │ ├── Task14.cpp │ ├── Task15.cpp │ ├── Task16.cpp │ ├── Task17.cpp │ ├── Theory.md │ └── task16.1.cpp ├── README.md └── Solutions │ ├── Task01.cpp │ ├── Task02.cpp │ ├── Task03.cpp │ ├── Task04.cpp │ ├── Task05.cpp │ ├── Task06.cpp │ └── Task07.cpp ├── Sem. 04 ├── Pract.04 │ ├── README.md │ ├── Task14.cpp │ ├── Task15.cpp │ ├── Task17.cpp │ └── Theory.md ├── README.md └── Solutions │ ├── IsPalindrome.cpp │ ├── IsPrime.cpp │ ├── LogK.cpp │ ├── Points.cpp │ ├── Pow.cpp │ ├── Prefix-Infix-Suffix.cpp │ └── ReverseNumber.cpp ├── Sem. 05 ├── Pract.05 │ ├── README.md │ ├── Task04.cpp │ ├── Task05.cpp │ ├── Task06.cpp │ ├── Task08.cpp │ ├── Task09.cpp │ ├── Task10.cpp │ ├── Task11.cpp │ ├── Theory.md │ └── bullsAndCows.cpp └── README.md ├── Sem. 06 ├── Pract.06 │ ├── README.md │ ├── Task10.cpp │ ├── Task10_bonus.cpp │ ├── Task11.cpp │ ├── Task12.cpp │ ├── Task13.cpp │ ├── Task14.cpp │ ├── Task15.cpp │ └── Theory.md ├── README.md └── Solutions │ ├── BinarySearch.cpp │ ├── ExerciseTemplate.cpp │ ├── LinearSearch.cpp │ ├── PrintArray.cpp │ ├── ReadArray.cpp │ ├── ReverseArray.cpp │ ├── SelectionSort.cpp │ └── ЕratosthenesSieve.cpp ├── Sem. 07 ├── Pract.07.2 │ ├── README.md │ └── Task 14.cpp ├── Pract.07 │ ├── README.md │ ├── Task05.cpp │ ├── Task08.cpp │ ├── Task09.cpp │ ├── Task10.cpp │ ├── Task11.cpp │ ├── Task12.cpp │ └── Task13.cpp ├── README.md └── Solutions │ ├── Simple-Tic-Tac-Toe.cpp │ └── Task09.cpp ├── Sem. 08 ├── Pract.09 │ ├── NumberSystems.cpp │ ├── README.md │ ├── Subsets.cpp │ ├── Task07.cpp │ ├── Task08.cpp │ └── Task10.cpp ├── README.md └── Solutions │ ├── 2To10AndReversed.cpp │ ├── AnyBaseToAnyBaseConverter.cpp │ ├── BitManipulation.cpp │ ├── BitwisePow.cpp │ ├── FirstNotDuplicated.cpp │ ├── IsEven.cpp │ └── IsPowerOfTwo.cpp ├── Sem. 09 ├── Pract.10 │ ├── README.md │ ├── Task01.cpp │ ├── Task02.cpp │ ├── Task12.cpp │ ├── Task13.cpp │ ├── Task14.cpp │ ├── Task15.cpp │ ├── Task16.cpp │ └── Task17.cpp ├── README.md ├── Solutions │ └── StringFunctionsImplementations.cpp └── images │ ├── example1.png │ ├── example2.png │ ├── right-to-left.jfif │ └── spiral-rule.jfif ├── Sem. 10 ├── Pract.11 │ ├── README.md │ ├── Task12.cpp │ ├── Task13.cpp │ └── Task14.cpp ├── README.md └── images │ ├── Memory.png │ └── exampleMemoryLeak.png ├── Sem. 11 ├── Pract.12 │ ├── README.md │ ├── Task07.cpp │ ├── Task08.cpp │ ├── Task09.cpp │ ├── Task10.cpp │ ├── Task11.cpp │ └── Task12.cpp ├── README.md ├── Solutions │ ├── Censor.cpp │ ├── DynamicCube.cpp │ ├── DynamicMatrix.cpp │ ├── DynamicMemoryExamples.cpp │ ├── LowerUpper.cpp │ ├── SortLower.cpp │ ├── Task07.cpp │ └── Task08.cpp ├── Task04.cpp ├── Task05.cpp └── Task06.cpp ├── Sem. 12 ├── Bonus_Theory.md ├── Pract.13 │ ├── README.md │ ├── Task08.cpp │ ├── Task09.cpp │ └── Task12.cpp ├── README.md ├── RecursionQuestions.cpp ├── Solutions │ ├── BinarySearch.cpp │ ├── Factoriel.cpp │ ├── FastPow.cpp │ ├── Fibonacci.cpp │ ├── Fibonacci_Cache.cpp │ ├── LinearSearch.cpp │ ├── Pow.cpp │ └── SumArray.cpp └── images │ ├── Head-recursion.jpg │ ├── Indirect-direct-recursion.png │ ├── Nested-recursion.jpg │ ├── Recursion-simpsons.gif │ ├── SumRange.gif │ ├── Tail-recursion.jpg │ ├── Tree-recursion.jpg │ ├── factorial-formula.png │ ├── factorial.gif │ ├── fib.gif │ ├── fib.png │ └── gcd-definition.png └── Sem. 13 ├── Algorithms ├── Complexity │ ├── CompareFunctions.cpp │ └── ComplexityExamples.cpp ├── Searching │ ├── BinarySearch.cpp │ ├── LinearSearch.cpp │ └── LinearchVsBinarySearch.cpp └── Sorting │ ├── BubbleSort.cpp │ ├── CountingSort.cpp │ ├── DemoMain.cpp │ ├── InsertionSort.cpp │ ├── SelectionSort.cpp │ └── StableCountingSort.cpp ├── Pract.14 └── README.md ├── README.md └── images ├── bubble.png ├── counting.png ├── insertion.png └── selection.png /.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 | -------------------------------------------------------------------------------- /Bonus/Task.md: -------------------------------------------------------------------------------- 1 |

8D битова баница с късмет

2 | 3 | ## Условие 4 | 5 | За празниците сме подготвили октерактна баница с късмет. Тя е нарязана така, че всяко измерение има 2 реда. Общо 256 парчета, като в едно от тях има паричка. 6 | 7 | Вашата задача е да напишете функция `int lucky()`, която да връща адреса на парчето с паричка. Очакваме адресът да е цяло число `int` в интервала [ 0 - 256 ), което представено в двоичен код представлява адрес в осем-измерната баница, на който е паричката. 8 | 9 | За да определите къде е късмета, можете да извикате една функция `int clue(int left_shift, int right_shift, int bwAnd, int bwOr)`, която да ви помогне. 10 | 11 | Имате право да извикате функцията `clue` само 4 пъти. Всяко извикване може да се направи с един от 4 именувани аргумента, **като всеки аргумент може да се използва само веднъж**. Нямате право да викате функцията повече от веднъж с даден аргумент. 12 | 13 | Вариантите са следните: 14 | 15 | - `left_shift` - Функцията `leftShift` очаква цяло число със стойност не по-малка от 5. Функцията трябва да връща цяло число, което се получава след изместване вляво дадения брой позиции 16 | 17 | **Пример:** 18 | 19 | ```c++ 20 | // Адресът с късмет е 42 (00101010) 21 | 22 | clue(6, -1, -1, -1) // => 128 23 | 24 | // 00101010 изместено вляво с 6 бита - 00001010 10000000 25 | // взимат се само най-десните 8 бита - 10000000 26 | // 10000000 e двоичен запис за 128 27 | ``` 28 | 29 | - `right_shift` - Функцията `rightShift` е еквивалентна на `leftShift`, но с изместване вдясно 30 | 31 | **Пример:** 32 | 33 | ```c++ 34 | // Адресът с късмет е 42 (00101010) 35 | 36 | clue(-1, 5, -1, -1) // => 1 37 | 38 | // 00101010 изместено вдясно с 5 бита - 00000001 39 | // 00000001 e двоичен запис за 1 40 | ``` 41 | 42 | - `bwAnd` - Функцията `bwAnd` очаква цяло число, чието двоично представяне съдържа не повече от една единица 43 | 44 | **Пример:** 45 | 46 | ```c++ 47 | // Адресът с късмет е 42 (00101010) 48 | 49 | clue(-1, -1, 8, -1) // => 8 50 | 51 | // 8 се представя като 00001000 52 | // прилагане на побитово AND между 53 | // 00001000 & 54 | // 00101010 55 | // => 00001000, което е 8 в десетична система 56 | ``` 57 | 58 | - `bwOr` - Функцията `bwOr` очаква цяло число, чието двоично представяне съдържа не повече от една нула 59 | 60 | **Пример:** 61 | 62 | ```c++ 63 | // Адресът с късмет е 42 (00101010) 64 | 65 | clue(-1, -1, -1, 223) // => 255 66 | 67 | // 223 се представя като 11011111 68 | // прилагане на побитово OR между 69 | // 11011111 | 70 | // 00101010 71 | // => 11111111, което е 255 в десетична система 72 | ``` 73 | 74 | Ако не е изпълнено едно от следните условия, функцията трябва да продължи своето изпълнение: 75 | 76 | - Поне 5 позиции за шифтване при shift_left и shift_right; 77 | - Не повече от 1 нула / единица при AND и OR; 78 | - Извикване с невалидна стойност; 79 | 80 | Във всички примери адресът на късмета е 42, така че се очаква вашата функция да върне 42: 81 | 82 | ```c++ 83 | lucky() // => 42 84 | ``` 85 | 86 | Весело търсене на късмета! 🎅🎄 -------------------------------------------------------------------------------- /Bonus/consultation/lines_struct.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | struct line { 7 | double startX; 8 | double startY; 9 | double endX; 10 | double endY; 11 | }; 12 | 13 | double lengthOfLine(line l) { 14 | double squaredDistance = (l.startX - l.endX) * (l.startX - l.endX) + (l.startY - l.endY) * (l.startY - l.endY); 15 | 16 | 17 | return sqrt(squaredDistance); 18 | } 19 | 20 | bool isParallel(const line &l1) { 21 | return l1.endX == l1.startX || l1.endY == l1.startY; 22 | } 23 | 24 | bool areOnOneLine(const line &l1, const line &l2) { 25 | return (l1.startX == l2.startX && l1.endX == l2.endX) || (l1.startY == l2.startY && l1.endY == l2.endY); 26 | } 27 | 28 | double min(double a, double b) { 29 | return a < b ? a : b; 30 | } 31 | 32 | double max(double a, double b) { 33 | return a > b ? a : b; 34 | } 35 | 36 | double getCommonDistance(const line &l1, const line &l2) { 37 | if (!isParallel(l1) || !isParallel(l2)) { 38 | return -1; 39 | } 40 | 41 | if (!areOnOneLine(l1, l2)) { 42 | return 0; 43 | } 44 | 45 | if (l1.startX == l2.startX) { 46 | return min(l1.endY, l2.endY) - max(l1.startY, l2.startY); 47 | } 48 | 49 | return min(l1.endX, l2.endX) - max(l1.startX, l2.startX); 50 | } 51 | 52 | int main() { 53 | line l1{10, 10, 10, 35}; 54 | 55 | line l2; 56 | l2.startX = 10; 57 | l2.startY = 10; 58 | l2.endX = 0; 59 | l2.endY = 10; 60 | 61 | cout << getCommonDistance(l1, l2) << endl; 62 | } 63 | -------------------------------------------------------------------------------- /Bonus/consultation/old_exam.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | bool isDigit(char c) { 5 | return c >= '0' && c <= '9'; 6 | } 7 | 8 | unsigned atoi(char c) { 9 | return c - '0'; 10 | } 11 | 12 | int analyzeArray(const char* str) { 13 | bool arr[10]; 14 | for (int i = 0; i < 10; ++i) { 15 | arr[i] = false; 16 | } 17 | 18 | while (*str == '\0') { 19 | if (isDigit(*str)) { 20 | arr[atoi(*str)] = true; 21 | } 22 | str++; 23 | } 24 | 25 | for (int i = 9; i >= 0; --i) { 26 | if (!arr[i]) { 27 | return i; 28 | } 29 | } 30 | 31 | return -1; 32 | } 33 | 34 | long getAbsDifference(long a, long b) { 35 | return (a > b) ? (a - b) : (b - a); 36 | } 37 | 38 | void swap(long* a, long* b) { 39 | long temp = *a; 40 | *a = *b; 41 | *b = temp; 42 | } 43 | 44 | unsigned getNumberLength(long n) { 45 | if (n == 0) { 46 | return 1; 47 | } 48 | 49 | unsigned length = 0; 50 | while (n != 0) { 51 | ++length; 52 | n /= 10; 53 | } 54 | return length; 55 | } 56 | 57 | char itoa(unsigned n) { 58 | return n + '0'; 59 | } 60 | 61 | void numberToStr(long n, unsigned numLength, char* str) { // 1234 => '1234' 62 | for (int i = numLength - 1; i >= 0; --i) { 63 | str[i] = itoa(n % 10); 64 | n /= 10; 65 | } 66 | } 67 | 68 | char* findDiff(const long arr[], size_t N) { 69 | long left, right; 70 | long minDistance = LONG_MAX; 71 | 72 | for (int i = 0; i < N - 1; ++i) { 73 | long currentDistance = getAbsDifference(arr[i], arr[i + 1]); 74 | if (currentDistance < minDistance) { 75 | minDistance = currentDistance; 76 | left = arr[i]; 77 | right = arr[i + 1]; 78 | } 79 | } 80 | 81 | if (left < right) { 82 | swap(&left, &right); 83 | } 84 | 85 | unsigned leftLength = getNumberLength(left); 86 | unsigned rightLength = getNumberLength(right); //x o y o y o o x 87 | 88 | char *result = new char[leftLength + 1 + rightLength + 1]; //leftLength + 1 + rightLength +1 89 | 90 | numberToStr(left, leftLength, result); // 123,78 91 | result[leftLength] = ','; 92 | numberToStr(right, rightLength, result + leftLength + 1); //123, 93 | 94 | result[leftLength + 1 + rightLength] = '\0'; 95 | 96 | return result; 97 | } 98 | 99 | void swap(int &a, int &b) { 100 | int temp = a; 101 | a = b; 102 | b = temp; 103 | } 104 | 105 | void selectionSort(int *arr, size_t L) { // 8 5 9 15 0 106 | for (int i = 0; i < L; ++i) { 107 | int maxIndex = i; 108 | for (int j = i + 1; j < L; ++j) { 109 | if (arr[j] > arr[maxIndex]) { 110 | maxIndex = j; 111 | } 112 | } 113 | 114 | if (maxIndex != i) { 115 | swap(arr[maxIndex], arr[i]); 116 | } 117 | } 118 | } 119 | 120 | int findIndex(const int arr[], size_t L) { 121 | int *sortedArr = new int[L]; 122 | for (int i = 0; i < L; ++i) { 123 | sortedArr[i] = arr[i]; 124 | } 125 | 126 | selectionSort(sortedArr, L); 127 | 128 | int currentSize = 0; 129 | int *ptrToDelete = sortedArr; 130 | 131 | while (currentSize < L && *sortedArr > currentSize) { 132 | ++currentSize; 133 | sortedArr++; 134 | } 135 | 136 | delete [] ptrToDelete; 137 | return currentSize; 138 | } 139 | 140 | int main() { 141 | using namespace std; 142 | 143 | int arr[10] = {100, 1000, 400, 900, 1100, 400, 800, 1000, 400, 800}; 144 | 145 | cout << findIndex(arr, 10) << endl; 146 | 147 | } -------------------------------------------------------------------------------- /Bonus/consultation/recursion.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | bool findPath(int currentI, int currentJ, const bool *const* labyrinth, int n, int m, bool **visited) { 6 | if (currentI >= n || currentJ >= m) { 7 | return false; 8 | } 9 | 10 | if (!labyrinth[currentI][currentJ] || visited[currentI][currentJ]) { 11 | return false; 12 | } 13 | 14 | if (currentI == n - 1 && currentJ == m - 1) { 15 | return true; 16 | } 17 | 18 | 19 | visited[currentI][currentJ] = true; 20 | return findPath(currentI + 1, currentJ, labyrinth, n, m, visited) 21 | || findPath(currentI, currentJ + 1, labyrinth, n, m, visited); 22 | } 23 | 24 | int main() { 25 | 26 | 27 | } -------------------------------------------------------------------------------- /Exams/Exam02/README.md: -------------------------------------------------------------------------------- 1 | # Контролно **№** 2 2 | 3 | ## Вариант **№** 1 4 | 5 | Конкатенация на две естествени числа **A** и **B** наричаме число **A ∘ B**, което се получава като към цифрите на **A** се долепят цифрите на **B**. 6 | 7 | **Пример:** 8 | 9 | ```c++ 10 | 123 ∘ 431 = 123431 11 | 123 ∘ 0 = 1230 12 | ``` 13 | 14 | Да се напише програма, която въвежда две естествени числа **N** и **K** и извежда дали съществуват естествени числа **А** и **B**, такива че **N = A ∘ K ∘ B**. 15 | 16 | Програмата да валидира, че двете числа са положителни и да изписва на екрана подходящо съобщение за грешка, ако не са. 17 | 18 | **В решението на задачата не се допуска използването на масиви!** 19 | 20 | | Вход | Изход | Насоки | 21 | | ----------------- | ------ | ------------- | 22 | | N = 1234; K = 23 | True | N = 1 ∘ K ∘ 4 | 23 | | N = 1234; K = 4 | False | | 24 | | N = 1234; K = 2 | True | N = 1 ∘ K ∘ 34 | 25 | 26 | ## Вариант **№** 2 27 | 28 | **Пясъчен часовник** наричаме 7 елемента от матрицата, които са подредени по следния начин в нея: 29 | 30 | ```c++ 31 | 1 1 1 32 | 1 33 | 1 1 1 34 | ``` 35 | 36 | Напишете програма, която приема от стандартния вход елементите (цели числа) на матрица с размерност **6 х 6**. 37 | 38 | Програмата да изведе на стандартния изход адреса (индексите) на центъра на този пясъчен часовник, който има максимален сбор на елементите си. Изведете също и съответния сбор. 39 | 40 | **Пояснение:** Считаме, че елементът в горния ляв ъгъл е с адрес **(0, 0)** 41 | 42 | **Пояснение 2:** Ако има два пясъчни часовника с еднаква сума, няма значение кой от двата ще бъде изведен като резултат. 43 | 44 | **Пример 1:** 45 | 46 | ```c++ 47 | 0 0 0 0 0 0 48 | 0 0 0 -5 -6 -7 49 | 1 2 3 -8 -4 -3 50 | 4 5 6 0 0 0 51 | 7 8 9 0 0 0 52 | 0 0 0 0 0 0 53 | ``` 54 | 55 | ```c++ 56 | Row: 3 57 | Column: 1 58 | Sum: 35 59 | ``` 60 | 61 | **Обяснение:** 62 | 63 |
64 | 0   0   0   0   0   0 
65 | 0   0   0  -5  -6  -7
66 | 1   2   3  -8  -4  -3
67 | 4   5   6   0   0   0
68 | 7   8   9   0   0   0
69 | 0   0   0   0   0   0
70 | 
71 | 72 | **Пример 2:** 73 | 74 | ```c++ 75 | -9 -9 -9 1 1 1 76 | 0 -9 0 4 3 2 77 | -9 -9 -9 1 2 3 78 | 0 0 8 6 6 0 79 | 0 0 0 -2 0 0 80 | 0 0 1 2 4 0 81 | ``` 82 | 83 | ```c++ 84 | Row: 2 85 | Column: 3 86 | Sum: 28 87 | ``` 88 | 89 | **Обяснение:** 90 | 91 |
92 | -9  -9  -9   1   1   1
93 |  0  -9   0   4   3   2
94 | -9  -9  -9   1   2   3
95 |  0   0   8   6   6   0
96 |  0   0   0  -2   0   0
97 |  0   0   1   2   4   0
98 | 
99 | -------------------------------------------------------------------------------- /Exams/Exam02/Task01.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int myPow(int a, int k) { 5 | int result = 1; 6 | for (int i = 0; i < k; i++) { 7 | result *= a; 8 | } 9 | return result; 10 | } 11 | 12 | int count_digits(int num) { 13 | int count = 0; 14 | while (num > 0) { 15 | num /= 10; 16 | count++; 17 | } 18 | return count; 19 | } 20 | 21 | 22 | bool check_concatenation(int N, int K) { 23 | int digits = count_digits(K); 24 | int power = myPow(10, digits); 25 | 26 | N /= 10; //guarantee that B is not empty 27 | 28 | while (N >= K) { 29 | if (N % power == K) { 30 | int A = N / power; 31 | 32 | if (A >= 0) { 33 | return true; 34 | } 35 | } 36 | N /= 10; 37 | } 38 | 39 | return false; 40 | } 41 | 42 | int main() { 43 | int N, K; 44 | 45 | cin >> N; 46 | cin >> K; 47 | 48 | if (N <= 0 || K <= 0) { 49 | return 0; 50 | } 51 | 52 | 53 | cout << check_concatenation(N, K); 54 | 55 | return 0; 56 | } -------------------------------------------------------------------------------- /Exams/Exam02/Task02.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | constexpr size_t SIZE = 6; 5 | constexpr size_t CLOCK_SIZE = 3; 6 | 7 | void readMatrix(int matrix[][SIZE]) { 8 | for (size_t i = 0; i < SIZE; i++) { 9 | for (size_t j = 0; j < SIZE; j++) { 10 | std::cin >> matrix[i][j]; 11 | } 12 | } 13 | } 14 | 15 | void findSandClocks(const int matrix[][SIZE], size_t ¢erX, size_t ¢erY, int &maxSum) { 16 | for (int i = 1; i < SIZE - 1; ++i) { 17 | for (int j = 1; j < SIZE - 1; ++j) { 18 | int directions[] = {-1, 0, 1}; 19 | 20 | int sum = matrix[i][j]; 21 | for (int d : directions) { 22 | sum += matrix[i - 1][j + d]; 23 | sum += matrix[i + 1][j + d]; 24 | } 25 | 26 | if (sum >= maxSum) { 27 | centerX = j; 28 | centerY = i; 29 | 30 | maxSum = sum; 31 | } 32 | } 33 | } 34 | } 35 | 36 | void sandClocks() { 37 | int matrix[SIZE][SIZE]; 38 | readMatrix(matrix); 39 | 40 | size_t centerX = 0, centerY = 0; 41 | int maxSum = INT_MIN; 42 | 43 | findSandClocks(matrix, centerX, centerY, maxSum); 44 | 45 | std::cout << "Row: " << centerY << std::endl; 46 | std::cout << "Column: " << centerX << std::endl; 47 | std::cout << "Sum: " << maxSum << std::endl; 48 | } 49 | 50 | int main() { 51 | sandClocks(); 52 | 53 | return 0; 54 | } 55 | -------------------------------------------------------------------------------- /Exams/Exam02/Task02_universal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | constexpr size_t MAX_SIZE = 100; 4 | constexpr size_t CLOCK_SIZE = 3; 5 | 6 | bool areValidDimensions(size_t rows, size_t cols) 7 | { 8 | return rows > 2 && rows < MAX_SIZE && cols > 2 && cols && MAX_SIZE && rows == cols; 9 | } 10 | 11 | void readMatrix(int mtx[][MAX_SIZE], size_t rows, size_t cols) 12 | { 13 | for (size_t i = 0; i < rows; i++) 14 | { 15 | for (size_t j = 0; j < cols; j++) 16 | { 17 | std::cin >> mtx[i][j]; 18 | } 19 | } 20 | } 21 | 22 | int getRowSummation(const int mtx[][MAX_SIZE], size_t row, size_t startX, size_t endX) 23 | { 24 | int rowSum = 0; 25 | 26 | for (size_t i = startX; i <= endX; i++) 27 | { 28 | rowSum += mtx[row][i]; 29 | } 30 | 31 | return rowSum; 32 | } 33 | 34 | int calculateSandClockSummation(const int mtx[][MAX_SIZE], size_t startX, size_t endX, size_t startY, size_t endY) 35 | { 36 | int sum = 0; 37 | 38 | size_t i, j; 39 | 40 | for (i = startY, j = endY; i != j; i++, j--) 41 | { 42 | sum += getRowSummation(mtx, i, startX, endX) + getRowSummation(mtx, j, startX, endX); 43 | startX++; 44 | endX--; 45 | } 46 | 47 | return sum + mtx[i][startX]; 48 | } 49 | 50 | void findSandClocks(const int mtx[][MAX_SIZE], size_t rows, size_t cols, 51 | size_t& centerX, size_t& centerY, int& maximumSummation) 52 | { 53 | size_t outset = CLOCK_SIZE / 2; 54 | 55 | size_t startX = outset, endX = rows - outset; 56 | size_t startY = outset, endY = cols - outset; 57 | 58 | while (startX < endX && startY < endY) 59 | { 60 | int sum = calculateSandClockSummation(mtx, startX - outset, startX + outset, startY - outset, startY + outset); 61 | 62 | if (sum > maximumSummation) 63 | { 64 | maximumSummation = sum; 65 | centerX = startX; 66 | centerY = startY; 67 | } 68 | 69 | startX++; 70 | 71 | if (startX == endX) 72 | { 73 | startX = 0; 74 | startY++; 75 | } 76 | } 77 | } 78 | 79 | void sandClocks() 80 | { 81 | size_t ROWS = 0, COLUMNS = 0; 82 | std::cin >> ROWS >> COLUMNS; 83 | 84 | if (!areValidDimensions(ROWS, COLUMNS)) 85 | { 86 | std::cout << "Invalid matrix dimensions!" << std::endl; 87 | return; 88 | } 89 | 90 | int mtx[MAX_SIZE][MAX_SIZE]{ 0 }; 91 | 92 | readMatrix(mtx, ROWS, COLUMNS); 93 | 94 | size_t centerX = 0, centerY = 0; 95 | int maximumSummation = INT_MIN; 96 | 97 | findSandClocks(mtx, ROWS, COLUMNS, centerX, centerY, maximumSummation); 98 | 99 | std::cout << "Row: " << centerY << std::endl; 100 | std::cout << "Column: " << centerX << std::endl; 101 | std::cout << "Sum: " << maximumSummation << std::endl; 102 | } 103 | 104 | int main() 105 | { 106 | sandClocks(); 107 | 108 | return 0; 109 | } 110 | -------------------------------------------------------------------------------- /Exams/Exam03/task01.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | const char TERMINATE_SYMBOL = '\0'; 4 | 5 | unsigned myStrLen(const char* str) { 6 | if (!str) { 7 | return 0; 8 | } 9 | 10 | unsigned index = 0; 11 | while (str[index] != TERMINATE_SYMBOL) { 12 | index++; 13 | } 14 | 15 | return index; 16 | } 17 | 18 | bool isDigit(char ch) { 19 | return '0' <= ch && ch <= '9'; 20 | } 21 | 22 | char digitToChar(unsigned digit) { 23 | return digit + '0'; 24 | } 25 | 26 | unsigned charToDigit (char a) { 27 | return a - '0'; 28 | } 29 | 30 | bool isLower(char ch) { 31 | return 'a' <= ch && ch <= 'z'; 32 | } 33 | 34 | void toLower(char &ch) { 35 | ch += ('a' - 'A'); 36 | } 37 | 38 | bool isUpper(char ch) { 39 | return 'A' <= ch && ch <= 'Z'; 40 | } 41 | 42 | void toUpper(char &ch) { 43 | ch += ('A' - 'a'); 44 | } 45 | 46 | void swap(char& a, char& b) { 47 | char temp = a; 48 | a = b; 49 | b = temp; 50 | } 51 | 52 | void reverseString(char* arr, unsigned length) { 53 | for (int i = 0; i < length / 2; i++) { 54 | swap(arr[i], arr[length - i - 1]); 55 | } 56 | } 57 | 58 | void convertString(char *str, char ch) { 59 | unsigned length = myStrLen(str); 60 | 61 | reverseString(str, length); 62 | 63 | for (int i = 0; i < length; i++) { 64 | if (isUpper(str[i])) { 65 | toLower(str[i]); 66 | } else if (isLower(str[i])) { 67 | toUpper(str[i]); 68 | } else if (isDigit(str[i])) { 69 | int remainder = charToDigit(str[i]) % 2; 70 | str[i] = digitToChar(remainder); //COMMON MISTAKE! - forget to reverse the int back to char 71 | } else { 72 | str[i] = ch; 73 | } 74 | } 75 | } 76 | 77 | int main() { 78 | char str[] = "up FMI 2024-2025"; 79 | 80 | convertString(str, '!'); 81 | std::cout << str; 82 | } 83 | -------------------------------------------------------------------------------- /Exams/Exam03/task02.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | const int MAX_SIZE = 1024; 3 | 4 | using namespace std; 5 | 6 | int smallestInSubsequence(const int *arr, int start, int end) { 7 | int smallest = arr[start]; 8 | for (int i = start + 1; i <= end; i++) { 9 | if (arr[i] < smallest) { 10 | smallest = arr[i]; 11 | } 12 | } 13 | 14 | return smallest; 15 | } 16 | 17 | int sumOfSmallestElements(const int *arr, int length, int K) { 18 | int sum = 0; 19 | if (K > length) { 20 | return sum; 21 | } 22 | 23 | int left = 0, right = K - 1; 24 | while (right < length) { 25 | sum += smallestInSubsequence(arr, left, right); 26 | left++; 27 | right++; 28 | } 29 | 30 | return sum; 31 | } 32 | 33 | int main() { 34 | int N, K; 35 | cin >> N >> K; 36 | 37 | if (N > MAX_SIZE || K > MAX_SIZE || K > N) { 38 | cout << "Invalid input" << endl; 39 | return 0; 40 | } 41 | 42 | int arr[MAX_SIZE]; 43 | for (int i = 0; i < N; ++i) { 44 | cin >> arr[i]; 45 | } 46 | 47 | cout << sumOfSmallestElements(arr, N, K) << endl; 48 | } -------------------------------------------------------------------------------- /Exams/Exam03/task03.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | long nums[] = { 15, 60, 90 }; 3 | 4 | int fun1(long* const a, char b[]) { 5 | char* p = new char[10]; //УТЕЧКА 6 | 7 | for (size_t i = 0; i < 10; i++) 8 | p[i] = b[i]; 9 | 10 | for (size_t i = 0; i < 10; i++) 11 | std::cout << b[i] << ' '; //h e l l o 0 //още 4 символа, които не може да определим предварително 12 | 13 | std::cout << a[9] << std::endl; //недефинирано поведение (или се извежда 0 - и двата варианта са ок) 14 | a[9] = 200; 15 | std::cout << a[9] << std::endl;//200 16 | 17 | std::cout << *nums << std::endl; //15 (заради ред 2) 18 | 19 | return 0; 20 | } 21 | 22 | int main() 23 | { 24 | long nums[10] = { 0, 10, 20, 30 }; 25 | char str[10] = "hello"; 26 | 27 | fun1(nums, str); 28 | std::cout << *nums << std::endl//0 29 | << ::nums; //адресът на глобалния масив 30 | 31 | } 32 | 33 | -------------------------------------------------------------------------------- /Exams/Exam03/tasks.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nikola354/Introduction-to-programming-FMI/1b26ba380133c1919893c672bf3fca6c95f7e34c/Exams/Exam03/tasks.pdf -------------------------------------------------------------------------------- /Exams/Exam04/K04_var1.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nikola354/Introduction-to-programming-FMI/1b26ba380133c1919893c672bf3fca6c95f7e34c/Exams/Exam04/K04_var1.pdf -------------------------------------------------------------------------------- /Exams/Exam04/K04_var2.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nikola354/Introduction-to-programming-FMI/1b26ba380133c1919893c672bf3fca6c95f7e34c/Exams/Exam04/K04_var2.pdf -------------------------------------------------------------------------------- /Exams/Exam04/var01.cpp: -------------------------------------------------------------------------------- 1 | main.cpp#include 2 | 3 | unsigned countResultSize(unsigned A, unsigned B) { 4 | unsigned resultLength = 0; 5 | 6 | while (A != 0 || B != 0) { 7 | if ((A & 1) != (B & 1)) { 8 | resultLength++; 9 | } 10 | 11 | A >>= 1; 12 | B >>= 1; 13 | } 14 | 15 | return resultLength; 16 | } 17 | 18 | unsigned *findIndexes(unsigned A, unsigned B, unsigned &resultLength) { 19 | resultLength = countResultSize(A, B); 20 | if (resultLength == 0) { 21 | return nullptr; 22 | } 23 | 24 | unsigned *result = new unsigned[resultLength]; 25 | 26 | unsigned index = 0; 27 | unsigned resultIndex = 0; 28 | while (resultIndex < resultLength && (A != 0 || B != 0)) { 29 | if ((A & 1) != (B & 1)) { 30 | result[resultIndex++] = index; 31 | } 32 | 33 | index++; 34 | A >>= 1; 35 | B >>= 1; 36 | } 37 | 38 | return result; 39 | } 40 | 41 | void printArr(const unsigned *arr, unsigned length) { 42 | for (unsigned i = 0; i < length; i++) { 43 | std::cout << arr[i] << " "; 44 | } 45 | } 46 | 47 | int main() 48 | { 49 | unsigned length = 0; 50 | unsigned *indexes = findIndexes(10, 20, length); 51 | 52 | if (indexes == nullptr) { 53 | std::cout << "Equal numbers" << std::endl; 54 | return 0; 55 | } 56 | 57 | printArr(indexes, length); 58 | std::cout << std::endl; 59 | 60 | delete [] indexes; 61 | } -------------------------------------------------------------------------------- /Exams/Exam04/var02.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int binaryToDecimal(const bool* arr, unsigned length) { 6 | int decimal = 0; 7 | 8 | for (int i = 0; i < length; i++) { 9 | if (arr[i]) { 10 | decimal += 1 << (length - 1 - i); //power of 2 11 | } 12 | } 13 | 14 | return decimal; 15 | } 16 | 17 | int* binaryToDecimalMatrix(const bool*const* binary, unsigned rows, unsigned cols) { 18 | int* result = new int[rows]; 19 | 20 | for (int i = 0; i < rows; i++) { 21 | result[i] = binaryToDecimal(binary[i], cols); 22 | } 23 | 24 | return result; 25 | } 26 | 27 | bool** readBoolMatrix(unsigned rows, unsigned cols) { 28 | bool** matrix = new bool*[rows]; 29 | 30 | for (int i = 0; i < rows; ++i) { 31 | matrix[i] = new bool[cols]; 32 | for (int j = 0; j < cols; ++j) { 33 | cin >> matrix[i][j]; 34 | } 35 | } 36 | 37 | return matrix; 38 | } 39 | 40 | void printArray(const int* arr, unsigned length) { 41 | for (int i = 0; i < length; ++i) { 42 | cout << arr[i] << " "; 43 | } 44 | cout << endl; 45 | } 46 | 47 | int main() { 48 | int rows, cols; 49 | cin >> rows >> cols; 50 | 51 | bool **binary = readBoolMatrix(rows, cols); 52 | 53 | int* decimals = binaryToDecimalMatrix(binary, rows, cols); 54 | printArray(decimals, rows); 55 | 56 | //free memory: 57 | 58 | for (int i = 0; i < rows; ++i) { 59 | delete[] binary[i]; 60 | } 61 | delete[] binary; 62 | delete[] decimals; 63 | 64 | return 0; 65 | } 66 | -------------------------------------------------------------------------------- /Instructions/Compilation.md: -------------------------------------------------------------------------------- 1 | # Компилация на C++ при различните операционни системи 2 | 3 | ## Windows 4 | 5 | * Има голям набор от IDE-та (Integrated Development Environment) и Text Editor-и, но в рамките на курса се препоръчват ```Visual Studio 2022 Community```, ```CLion``` и в краен случай ```Code::Blocks``` 6 | * При програмиране на VSCode се следват същите стъпки за компилация, както при ```macOS```, но трябва допълнителна конфигурация на GCC през тези линкове: 7 | * [Using GCC with MinGW](https://code.visualstudio.com/docs/cpp/config-mingw) 8 | * [GCC and MinGW-w64 for Windows](https://winlibs.com/) 9 | * Накрая във ```VSCode``` се изтегля допълнителен ```Extension: C/C++``` 10 | 11 | ## macOS 12 | 13 | * За IDE можете да използвате ```VSCode``` или ```CLion``` 14 | * За компилация на код ви трябва GCC, който може да си го свалите по следния начин ```xcode-select --install``` и след това да проверите, че всичко е наред, като изпълните командата ```g++ --version``` 15 | * За да компилирате даден .cpp файл, трябва да се намирате в папката, където се намира файлът и да run-нете ```g++ .cpp -o .out``` 16 | * За изпълнение на executable файла, ако няма компилационни грешки, се използва ```./.out``` 17 | 18 | ## Linux 19 | 20 | * За IDE се използват ```VSCode``` и ```CLion```, като допълнително трябва да се свали g++ в зависимост от дистрото на Linux: 21 | * Debian / Ubuntu: ```sudo apt install g++``` 22 | * Red Hat / Fedora: ```sudo dnf install gcc-c++``` 23 | * Компилацията на .cpp е със същите команди като при macOS 24 | 25 | ### !!! При допълнителни въпроси относно конфигурация питайте [Slavi Rezashki](https://github.com/Slavi15) 26 | -------------------------------------------------------------------------------- /Instructions/GitHub Workflow/README.md: -------------------------------------------------------------------------------- 1 | ## GitHub workflow 2 | 3 | 0. Star the repository 4 | ![image](images/star-the-repo.png) 5 | 6 | 1. Fork the repository 7 | - [How to fork a repository.](https://docs.github.com/en/get-started/quickstart/fork-a-repo) 8 | 9 | 2. Clone the repository on your local machine 10 | - [How to clone a repository.](https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository) 11 | 12 | - In GitHub desktop - Repository -> Repository settings... -> Fork behavior -> select To contribute to the parent repository 13 | ![repo menu](images/repository-settings-menu.png) 14 | ![repo-settings](images/repository-fork-settings.png) 15 | 16 | 17 | 3. Fetch origin 18 | - ![fetch origin](images/fetch-origin.png) 19 | 20 | 4. Create a branch **(optional)** 21 | - You should create branch for each **3 tasks**. 22 | - The branch should be created from the main branch of the original repository. In this way you will always have the latest changes . 23 | - [About branches.](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-branches) 24 | - [How to create branch.](https://docs.github.com/en/desktop/contributing-and-collaborating-using-github-desktop/making-changes-in-a-branch/managing-branches#creating-a-branch) 25 | 26 | 4. Add a solution for a task 27 | - Create a cpp file for each task. 28 | - **The name of the file should be TaskXX.cpp where XX is the number of the task**
e.g. Task01.cpp, Task12.cpp etc. 29 | - Copy your solution into the file. 30 | 31 | 5. Commit solution to a task 32 | - Commit the file for the task. 33 | - **Each task should be in seperate commit.** 34 | - Repeat step 5. and 6. until you have 3 tasks in the new branch.
35 | Then create a new branch and start from step 4. 36 | - [About commits.](https://docs.github.com/en/desktop/contributing-and-collaborating-using-github-desktop/making-changes-in-a-branch/committing-and-reviewing-changes-to-your-project#about-commits) 37 | 38 | 7. Open PR to the original repository to the main branch 39 | - [How to create pull request.](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request) 40 | - The pull request should request to merge the changes of your branch in the fork to the main branch of the original repositor. 41 | - **The title of the Pull Request should be:** 42 | ``` 43 | Pract.\: Add \ - \ | \ 44 | 45 | Example: 46 | Pract.03: Add 01-03 | John Doe 47 | ``` 48 | - **The description of the pull Request should be** 49 | ``` 50 | \ \ 51 | \ \ \ 52 | 53 | Example: 54 | John Doe 55 | SI 2 2MI0600192 56 | ``` 57 | 58 | 59 | | :boom: **DANGER**| 60 | |:-----------------| 61 | | ***If a pull request has more than 3 tasks or the title or description are not in the format described above, the PR will be rejected and will not be reviewed.***| 62 | -------------------------------------------------------------------------------- /Instructions/GitHub Workflow/images/fetch-origin.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nikola354/Introduction-to-programming-FMI/1b26ba380133c1919893c672bf3fca6c95f7e34c/Instructions/GitHub Workflow/images/fetch-origin.png -------------------------------------------------------------------------------- /Instructions/GitHub Workflow/images/repository-fork-settings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nikola354/Introduction-to-programming-FMI/1b26ba380133c1919893c672bf3fca6c95f7e34c/Instructions/GitHub Workflow/images/repository-fork-settings.png -------------------------------------------------------------------------------- /Instructions/GitHub Workflow/images/repository-settings-menu.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nikola354/Introduction-to-programming-FMI/1b26ba380133c1919893c672bf3fca6c95f7e34c/Instructions/GitHub Workflow/images/repository-settings-menu.png -------------------------------------------------------------------------------- /Instructions/GitHub Workflow/images/star-the-repo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nikola354/Introduction-to-programming-FMI/1b26ba380133c1919893c672bf3fca6c95f7e34c/Instructions/GitHub Workflow/images/star-the-repo.png -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Nikola Manolov 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Материали от семинарите и практикумите по "Увод в програмирането" 2 | #### Зимен семестър 2024/2025, спец. Софтуерно инженерство 3 | 4 | - [Тема 1](./Sem.%2001): Увод. Примитивни типове данни. Преобразуване между типове. Основни аритметични операции. Оператори. Вход и изход. 5 | - [Тема 2](./Sem.%2002): Условни конструкции. 6 | - [Тема 3](./Sem.%2003): Цикли. Оператори break и continue. 7 | - [Тема 4](./Sem.%2004): Функции. Оператор return. 8 | - [Тема 5](./Sem.%2005): Функции - допълнение. Референции. l-value & r-value. Стек и Стекова рамка. Пример с малък проект. 9 | - [Тема 6](./Sem.%2006): Масиви (с фиксирана дължина). + Още типове данни 10 | - [Тема 7](./Sem.%2007): Многомерни масиви. Работа с масиви от масиви. Пример с малък проект: Tic-Tac-Toe 11 | - [Тема 8](./Sem.%2008): Бройни системи. Преобразуване между бройни системи. Побитови операции. 12 | - [Тема 9](./Sem.%2009): Указатели. Символни низове(стрингове). Основни операции с низове. 13 | - [Тема 10](./Sem.%2010): Динамична памет - теория. Заделяне на динамична памет. Оператори new и delete. 14 | - [Тема 11](./Sem.%2011): Динамична памет - задачи. Работа с динамични масиви от динамични масиви. 15 | - [Тема 12](./Sem.%2012): Рекурсия 16 | - [Тема 13](./Sem.%2013): Сложност и алгоритми. Алгоритми за търсене и сортиране. -------------------------------------------------------------------------------- /Sem. 01/Pract. 01/AdditionalTasks.md: -------------------------------------------------------------------------------- 1 | ## Допълнителни задачи 2 | 3 | **Задача 1:** Да се напише програма, която чете от конзолата реално число - см и го превръща в инчове. (1см = 0.393701 инча). 4 | 5 | Вход: 6 | ```c++ 7 | 25 8 | ``` 9 | 10 | Изход: 11 | ```c++ 12 | 9.84 13 | ``` 14 | 15 | **Задача 2:** От конзолата се прочитат две цели числа и се отпечатва частното и остатъка им (пълноценното им деление) 16 | 17 | Вход: 18 | ```c++ 19 | 17 4 20 | ``` 21 | 22 | Изход: 23 | ```c++ 24 | 4 1 25 | ``` 26 | 27 | **Задача 3:** От конзолата се въвеждат 5 цели числа. Да се изведе сумата на нечетните числа. 28 | 29 | Вход: 30 | ```c++ 31 | 2 7 18 9 5 32 | ``` 33 | 34 | Изход: 35 | ```c++ 36 | 21 37 | ``` 38 | 39 | **Задача 4:** От конзолата се четат 3 реални числа. Да се изведе дали могат да бъдат страни на триъгълник. 40 | 41 | Вход: 42 | ```c++ 43 | 3 4 5 44 | ``` 45 | 46 | Изход: 47 | ```c++ 48 | 1 49 | ``` 50 | 51 | **Задача 5:** Потребителят въвежда число n. Да се изведе сборът на числата, които се делят на 3 и са по-малки или равни на n. 52 | 53 | Вход: 54 | ```c++ 55 | 15 56 | ``` 57 | 58 | Изход: 59 | ```c++ 60 | 45 61 | ``` 62 | 63 | **Задача 6:** Да се напише програма, която чете 4 реални числа от конзолата и отпечатва 1, ако редицата е растяща. В противен случай програмата да отпечата 0. 64 | 65 | Вход: 66 | ```c++ 67 | 2.56 3.78 5.12 9.45 68 | ``` 69 | 70 | Изход: 71 | ```c++ 72 | 1 73 | ``` 74 | 75 | **Задача 7:** Да се определи за дадено 6-цифрено число дали 3-цифреното число, образувано от първите 3 цифри на даденото, е по-малко от това, образурано от вторите 3. 76 | 77 | Вход: 78 | ```c++ 79 | 548735 80 | ``` 81 | 82 | Изход: 83 | ```c++ 84 | 1 85 | ``` 86 | 87 | **Задача 8:** Напишете програма, която приема цяло положително число и: 88 | * Ако то е едноциферно - да се изпечати. 89 | * Ако то е двуцифрено - да се изпечати последната му цифра събрана с 1. 90 | * Във всеки друг случай - да се изпечати цялото без последната цифра. 91 | 92 | Вход: 93 | ```c++ 94 | 2358 95 | ``` 96 | 97 | Изход: 98 | ```c++ 99 | 235 100 | ``` 101 | 102 | Вход: 103 | ```c++ 104 | 92 105 | ``` 106 | 107 | Изход: 108 | ```c++ 109 | 3 110 | ``` 111 | 112 | Вход: 113 | ```c++ 114 | 7 115 | ``` 116 | 117 | Изход: 118 | ```c++ 119 | 7 120 | ``` -------------------------------------------------------------------------------- /Sem. 01/Pract. 01/Theory.md: -------------------------------------------------------------------------------- 1 | ## Теоретични въпроси 2 | 3 | # Теоретични задачи 4 | 5 | **Задача 1:** Какво ще се отпечата на конзолата? 6 | ```c++ 7 | #include 8 | 9 | int main() { 10 | double first = 3.75; 11 | double second = 5.36; 12 | int result = first + second; 13 | std::cout << result << std::endl; 14 | return 0; 15 | } 16 | ``` 17 | 18 | **Задача 2:** Какво ще се отпечата на конзолата? 19 | ```c++ 20 | #include 21 | 22 | int main() { 23 | double a = 1.2; 24 | double b = 0; 25 | int c = 4; 26 | std::cout << a / !c << std::endl; 27 | std::cout << b / !!false << std::endl; 28 | std::cout << c / b << std::endl; 29 | } 30 | ``` 31 | 32 | **Задача 3:** Какво ще се отпечата на конзолата? 33 | ```c++ 34 | #include 35 | 36 | int main() { 37 | int a = 10; 38 | std::cout << ++++a; 39 | std::cout << ++++a++; 40 | } 41 | ``` 42 | 43 | **Задача 4:** Какво ще отпечата следният код? 44 | 45 | ```c++ 46 | #include 47 | 48 | int main() 49 | { 50 | int a = 0, b = 10; 51 | std::cout << (((a || b) && (a || !b)) || !a); 52 | } 53 | ``` 54 | 55 | **Задача 5:** Какво ще отпечата следният код? Имаме ли загуба на памет? 56 | 57 | ```c++ 58 | #include 59 | using namespace std; 60 | 61 | int main() 62 | { 63 | int a = 5; 64 | int b = 10; 65 | double c = 2.2; 66 | double d = 2.3; 67 | int s = c + d; 68 | c = a / b; 69 | d = 1.0 * a / b; 70 | int e = d; 71 | cout << s << endl << c << endl << d << endl << e; 72 | } 73 | 74 | ``` 75 | 76 | **Задача 6:** Какво ще отпечата следният код? 77 | 78 | ```c++ 79 | #include 80 | using namespace std; 81 | 82 | int x = 10; 83 | 84 | int main() 85 | { 86 | cout << x << endl; 87 | int x = 5; 88 | cout << x++ << endl; 89 | { 90 | int x = 15; 91 | cout << ++x << endl; 92 | } 93 | { 94 | int x = 0; 95 | x = x++; 96 | cout << x << endl; 97 | } 98 | cout << x << endl; 99 | return 0; 100 | } 101 | ``` 102 | 103 | **Задача 7:** Какво ще отпечата следният код? 104 | 105 | ```c++ 106 | #include 107 | 108 | int main() 109 | { 110 | int a = 0; 111 | int b = a++; 112 | std::cout << (a == !b) << std::endl; 113 | { 114 | int c = ++a; 115 | c *= 2; 116 | std::cout << c << std::endl; 117 | } 118 | int sum = a + b + c; 119 | std::cout << sum << std::endl; 120 | return 0; 121 | } 122 | ``` 123 | -------------------------------------------------------------------------------- /Sem. 01/Solutions/Task01.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | int number; 5 | std::cin >> number; 6 | 7 | bool isEven = (number % 2) == 0; 8 | std::cout << isEven; 9 | } -------------------------------------------------------------------------------- /Sem. 01/Solutions/Task02.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | int number; 5 | std::cin >> number; 6 | 7 | // 326 8 | int firstDigit = number / 100; 9 | int secondDigit = (number / 10) % 10; 10 | int thirdDigit = number % 10; 11 | // 3 2 6 12 | // 623 + 1 13 | int result = thirdDigit * 100 + secondDigit * 10 + firstDigit + 1; 14 | 15 | std::cout << result; 16 | } -------------------------------------------------------------------------------- /Sem. 01/Solutions/Task03.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | char ch; 5 | std::cin >> ch; 6 | 7 | bool isVowel = ch == 'a' || ch == 'e' || ch == 'o' || ch == 'u' || ch == 'i' 8 | || ch == 'A' || ch == 'E' || ch == 'O' || ch == 'U' || ch == 'I'; 9 | 10 | std::cout << isVowel << std::endl; 11 | } -------------------------------------------------------------------------------- /Sem. 01/Solutions/Task04.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | int grade; 5 | std::cin >> grade; 6 | 7 | bool isValidGrade = grade >= 2 && grade <= 6; 8 | 9 | std::cout << isValidGrade << std::endl; 10 | } -------------------------------------------------------------------------------- /Sem. 01/Solutions/Task05.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | int number; 5 | std::cin >> number; 6 | std::cout << (number / 10); 7 | } -------------------------------------------------------------------------------- /Sem. 01/Solutions/Task06.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | int a, b; 5 | std::cin >> a >> b; 6 | 7 | int expr1 = a + b; 8 | int expr2 = a - b; 9 | 10 | int result = expr1 * expr1 * expr1 * expr1 - expr2 * expr2; 11 | 12 | std::cout << result; 13 | } -------------------------------------------------------------------------------- /Sem. 01/Solutions/Task07.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | int n; 5 | std::cin >> n; 6 | 7 | int b100 = n / 100; 8 | n %= 100; 9 | 10 | int b50 = n / 50; 11 | n %= 50; 12 | 13 | int b20 = n / 20; 14 | n %= 20; 15 | 16 | int b10 = n / 10; 17 | n %= 10; 18 | 19 | int b5 = n / 5; 20 | n %= 5; 21 | 22 | int b2 = n / 2; 23 | n %= 2; 24 | 25 | int b1 = n; 26 | std::cout << b100 << "x100lv " 27 | << b50 << "x50lv " 28 | << b20 << "x20lv " 29 | << b10 << "x10lv " 30 | << b5 << "x5lv " 31 | << b2 << "x2lv " 32 | << b1 << "x1lv" << std::endl; 33 | } -------------------------------------------------------------------------------- /Sem. 01/Solutions/Task08.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int mainV1() { 4 | int a, b; 5 | std::cin >> a >> b; 6 | 7 | bool shouldSwap = (a < b) && (a = b); 8 | 9 | std::cout << a; 10 | } 11 | 12 | int mainV2() { 13 | int a, b; 14 | std::cin >> a >> b; 15 | 16 | bool isFirstBigger = a > b; 17 | 18 | std::cout << isFirstBigger * a + !isFirstBigger * b; 19 | } -------------------------------------------------------------------------------- /Sem. 01/Solutions/Task09.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | int a = 5; 5 | int b = 10; 6 | 7 | // std::cin >> a >> b; 8 | 9 | a += b; // 15 10 10 | b = a - b; // 15 5 11 | a -= b; // 10 5 12 | 13 | std::cout << a; 14 | std::cout << b; 15 | } -------------------------------------------------------------------------------- /Sem. 02/Pract.02/Task03.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | char ch; 8 | 9 | cin >> ch; 10 | 11 | switch (ch) 12 | { 13 | case 'I': 14 | cout << (int)ch << endl; 15 | break; 16 | case 'V': 17 | cout << (int)ch << endl; 18 | break; 19 | case 'X': 20 | cout << (int)ch << endl; 21 | break; 22 | case 'L': 23 | cout << (int)ch << endl; 24 | break; 25 | case 'C': 26 | cout << (int)ch << endl; 27 | break; 28 | case 'D': 29 | cout << (int)ch << endl; 30 | break; 31 | case 'M': 32 | cout << (int)ch << endl; 33 | break; 34 | default: 35 | cout << "-1" << endl; 36 | break; 37 | } 38 | 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /Sem. 02/Pract.02/Task10.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int a, b, c; 8 | 9 | cin >> a >> b >> c; 10 | 11 | if (a > b) 12 | { 13 | int temp = a; 14 | a = b; 15 | b = temp; 16 | } 17 | 18 | if (b > c) 19 | { 20 | int temp = b; 21 | b = c; 22 | c = temp; 23 | } 24 | 25 | if (a > c) 26 | { 27 | int temp = a; 28 | a = c; 29 | c = temp; 30 | } 31 | 32 | cout << a << " " << b << " " << c << endl; 33 | 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /Sem. 02/Pract.02/Task12.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | int main(){ 3 | double fisrtSide,secondSide,thirdSide; 4 | std::cin>>fisrtSide>>secondSide>>thirdSide; 5 | bool marker_1 = fisrtSide + secondSide > thirdSide; 6 | bool marker_2 = thirdSide + secondSide > fisrtSide; 7 | bool marker_3 = fisrtSide + thirdSide > secondSide; 8 | if(marker_1 && marker_2 && marker_3) std::cout<<"This thriangle exists."; 9 | else std::cout<<"This triangle doesn't exist."; 10 | return 0; 11 | } -------------------------------------------------------------------------------- /Sem. 02/Pract.02/Task13.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int main(){ 4 | int radius,pointX,pointY; 5 | std::cin>>radius>>pointX>>pointY; 6 | double distanceToPoint = sqrt(pointX*pointX + pointY*pointY); 7 | if(distanceToPoint < radius){ 8 | std::cout<<"In the circle"; 9 | }else if (distanceToPoint == radius) { 10 | std::cout<<"On the cirlce"; 11 | }else 12 | std::cout<<"Out of the circle"; 13 | } -------------------------------------------------------------------------------- /Sem. 02/Pract.02/Task14.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | int main(){ 3 | double firstNum, secondNum; 4 | char ch; 5 | std::cin>>firstNum >> ch >> secondNum; 6 | switch (ch) { 7 | case('+'): std::cout<< firstNum + secondNum; break; 8 | case('-'): std::cout<< firstNum - secondNum; break; 9 | case('*'): std::cout<< firstNum * secondNum; break; 10 | case('/'): std::cout<< firstNum / secondNum; break; 11 | default: std::cout<< "Invalid input"; 12 | } 13 | return 0; 14 | } -------------------------------------------------------------------------------- /Sem. 02/Pract.02/Task15.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int n; 8 | cin >> n; 9 | 10 | int firstDigit = n / 1000; 11 | n %= 1000; 12 | 13 | int secondDigit = n / 100; 14 | n %= 100; 15 | 16 | int thirdDigit = n / 10; 17 | n %= 10; 18 | 19 | int fourthDigit = n; 20 | 21 | int firstNum = firstDigit * 10 + fourthDigit; 22 | int secondNum = secondDigit * 10 + thirdDigit; 23 | 24 | if (firstNum < secondNum) 25 | { 26 | cout << "Less: (" << firstNum << " < " << secondNum << ")"; 27 | } 28 | else if (firstNum == secondNum) 29 | { 30 | cout << "Equal: (" << firstNum << " = " << secondNum << ")"; 31 | } 32 | else 33 | { 34 | cout << "Bigger: (" << firstNum << " > " << secondNum << ")"; 35 | } 36 | 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /Sem. 02/Pract.02/Task16.cpp: -------------------------------------------------------------------------------- 1 | // От конзолата се чете число в интервала [0, ..., 12]. Ако числото е четно, програмата 2 | // принтира всички четни числа по-големи или равни на числото, намиращи се в интервала. 3 | // Ако е нечетно, принтираме всички по-големи или равни нечетни числа. (Опитайте се да 4 | // направите кода максимално четим) 5 | #include 6 | int main() { 7 | int n; 8 | std::cin >> n; 9 | switch (n) 10 | { 11 | case 1: 12 | std::cout << 1 << std::endl; 13 | case 3: 14 | std::cout << 3 << std::endl; 15 | case 5: 16 | std::cout << 5 << std::endl; 17 | case 7: 18 | std::cout << 7 << std::endl; 19 | case 9: 20 | std::cout << 9 << std::endl; 21 | case 11: 22 | std::cout << 11 << std::endl; 23 | break; 24 | case 0: 25 | std::cout << 0 << std::endl; 26 | case 2: 27 | std::cout << 2 << std::endl; 28 | case 4: 29 | std::cout << 4 << std::endl; 30 | case 6: 31 | std::cout << 6 << std::endl; 32 | case 8: 33 | std::cout << 8 << std::endl; 34 | case 10: 35 | std::cout << 10 << std::endl; 36 | case 12: 37 | std::cout << 12 << std::endl; 38 | break; 39 | default: 40 | std::cout << "Incorrect input" << std::endl; 41 | } 42 | } -------------------------------------------------------------------------------- /Sem. 02/Pract.02/Task17.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | const char CAPITAL_TO_LOWER = 'a' - 'A'; 8 | 9 | char capitalStart, capitalEnd, lowerStart, lowerEnd, symbol; 10 | cin >> capitalStart >> capitalEnd >> lowerStart >> lowerEnd >> symbol; 11 | 12 | if (symbol >= 'A' && symbol <= 'Z') 13 | { 14 | symbol += CAPITAL_TO_LOWER; 15 | } 16 | 17 | capitalStart += CAPITAL_TO_LOWER; 18 | capitalEnd += CAPITAL_TO_LOWER; 19 | 20 | bool isInFirst = symbol >= capitalStart && symbol <= capitalEnd; 21 | bool isInSecond = symbol >= lowerStart && symbol <= lowerEnd; 22 | 23 | bool isUnion = isInFirst || isInSecond; 24 | bool isIntersection = isInFirst && isInSecond; 25 | bool isDifference = isInFirst && !isInSecond; 26 | bool isInOnlySet = isUnion && !isIntersection; 27 | 28 | cout << (isUnion ? "true" : "false") << endl; 29 | cout << (isIntersection ? "true" : "false") << endl; 30 | cout << (isDifference ? "true" : "false") << endl; 31 | cout << (isInOnlySet ? "true" : "false") << endl; 32 | } 33 | -------------------------------------------------------------------------------- /Sem. 02/Pract.02/Theory.md: -------------------------------------------------------------------------------- 1 | ## Теоретични въпроси: 2 | 3 | 1) Еквивалентни ли са двете парчета код? 4 | 5 | 6 | ```c++ 7 | if (a > 0) if (b > 0) std::cout << 1; else std::cout << 3; 8 | ``` 9 | 10 | ```c++ 11 | if (a > 0) { 12 | if (b > 0) { 13 | std::cout << 1; 14 | } 15 | } 16 | else std::cout << 3; 17 | ``` 18 | 19 | 2) Какво ще се отпечата на конзолата? 20 | 21 | ```c++ 22 | int num = 25; 23 | int a = 7; 24 | if (++num, num += 2, num > 27) { 25 | num % 2 == 0 ? num /= 2 : a -= 4; 26 | } 27 | if (num==12, num - 2 * a) { 28 | std::cout << num+1; 29 | } 30 | else { 31 | std::cout << num+2; 32 | } 33 | ``` 34 | 35 | 3) Какво ще се отпечата на конзолата? 36 | 37 | ```c++ 38 | int x = 5; 39 | char ch = 'A'; 40 | switch (x % 3) { 41 | case 0: 42 | std::cout << "Zero\n"; 43 | break; 44 | case 1: 45 | std::cout << "One\n"; 46 | case 2: 47 | std::cout << "Two\n"; 48 | ch = 'C'; 49 | case 3: 50 | std::cout << "Three\n"; 51 | break; 52 | default: 53 | std::cout << "Default\n"; 54 | } 55 | switch (ch) { 56 | case 'A': 57 | std::cout << "Character A\n"; 58 | break; 59 | case 'B': 60 | std::cout << "Character B\n"; 61 | break; 62 | case 'C': 63 | std::cout << "Character C\n"; 64 | default: 65 | std::cout << "Character Default\n"; 66 | } 67 | return 0; 68 | ``` 69 | 70 | 4) Преобразувайте кода, като използвате switch, вместо if и if else 71 | 72 | ```c++ 73 | 74 | unsigned a; 75 | std::cin>>a; 76 | if (a == 2) { 77 | std::cout << "Two" << std::endl; 78 | } 79 | if (a <= 1) { 80 | std::cout << "Less" << std::endl; 81 | } 82 | else if (a == 3) { 83 | std::cout << "Three" << std::endl; 84 | } 85 | else { 86 | std::cout << "Dont know" << std::endl; 87 | } 88 | ``` 89 | -------------------------------------------------------------------------------- /Sem. 02/Solutions/Task01.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | int num; 5 | std::cin >> num; 6 | 7 | switch (num) { 8 | case 1:std::cout << "Monday" << std::endl; break; 9 | case 2:std::cout << "Tuesday" << std::endl; break; 10 | case 3:std::cout << "Wednesday" << std::endl; break; 11 | case 4:std::cout << "Thursday" << std::endl; break; 12 | case 5:std::cout << "Friday" << std::endl; break; 13 | case 6:std::cout << "Saturday" << std::endl; break; 14 | case 7:std::cout << "Sunday" << std::endl; break; 15 | default: std::cout << "The number is not a valid day of the week" << std::endl; 16 | } 17 | 18 | } -------------------------------------------------------------------------------- /Sem. 02/Solutions/Task02.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | unsigned int n; 5 | std::cin >> n; 6 | 7 | if (n < 100) { 8 | std::cout << "Less than 100" << std::endl; 9 | } else if (n <= 200) { 10 | std::cout << "Between 100 and 200" << std::endl; 11 | } else { 12 | std::cout << "More than 200" << std::endl; 13 | } 14 | } -------------------------------------------------------------------------------- /Sem. 02/Solutions/Task03.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | double speed; 5 | std::cin >> speed; 6 | 7 | if (speed <= 10) { 8 | std::cout << "Slow" << std::endl; 9 | } else if (speed < 50) { 10 | std::cout << "Average" << std::endl; 11 | } else if (speed < 150) { 12 | std::cout << "Fast" << std::endl; 13 | } else if (speed < 1000) { 14 | std::cout << "Ultra fast" << std::endl; 15 | } else { 16 | std::cout << "Extremely fast" << std::endl; 17 | } 18 | } -------------------------------------------------------------------------------- /Sem. 02/Solutions/Task04.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | const double PI = 3.14; 4 | 5 | int main() { 6 | // s r c t 7 | char figure; 8 | std::cin >> figure; 9 | 10 | switch (figure) { 11 | case 's': { 12 | int side; 13 | std::cin >> side; 14 | std::cout << side * side; 15 | }; break; 16 | case 'r': { 17 | int sideA, sideB; 18 | std::cin >> sideA >> sideB; 19 | std::cout << sideA * sideB; 20 | }; break; 21 | case 'c': { 22 | int radius; 23 | std::cin >> radius; 24 | std::cout << radius * radius * PI; 25 | }; break; 26 | case 't': { 27 | int sideA, height; 28 | std::cin >> sideA >> height; 29 | std::cout << (sideA * height) / 2; 30 | }; break; 31 | default: 32 | std::cout << "Invalid Figure"; 33 | break; 34 | } 35 | } -------------------------------------------------------------------------------- /Sem. 02/Solutions/Task05.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | int hours, minutes; 5 | std::cin >> hours >> minutes; 6 | 7 | minutes += 15; 8 | 9 | if (minutes >= 60) { 10 | minutes -= 60; 11 | hours++; 12 | } 13 | 14 | hours %= 24; 15 | 16 | std::cout << 17 | (hours < 10 ? "0" : "") << hours << ":" << 18 | (minutes < 10 ? "0" : "") << minutes << std::endl; 19 | 20 | // Equal to: 21 | // if (hours < 10) { 22 | // std::cout << "0"; 23 | // } 24 | // std::cout << hours << ":"; 25 | 26 | // if (minutes < 10) { 27 | // std::cout << "0"; 28 | // } 29 | // std::cout << minutes; 30 | } -------------------------------------------------------------------------------- /Sem. 02/Solutions/Task06.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | int a, b, c, d, e; 5 | std::cin >> a >> b >> c >> d >> e; 6 | 7 | bool isSaw = (a >= b && b <= c && c >= d && d <= e) 8 | || (a <= b && b >= c && c <= d && d >= e); 9 | 10 | std::cout << (isSaw ? "yes" : "no") << std::endl; 11 | } -------------------------------------------------------------------------------- /Sem. 02/Solutions/Task07.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | const double EPSILON = 0.0001; 5 | 6 | int main() { 7 | double x, y; 8 | std::cin >> x >> y; 9 | double r; 10 | std::cin >> r; 11 | 12 | double length = sqrt((x * x) + (y * y)); 13 | 14 | if (std::fabs(length - r) < EPSILON) { 15 | std::cout << "On the border" << std::endl; 16 | } else if (length < r) { 17 | std::cout << "Inside" << std::endl; 18 | } else { 19 | std::cout << "Outside" << std::endl; 20 | } 21 | } -------------------------------------------------------------------------------- /Sem. 03/Pract.03/Task01.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | int main() { 3 | int n,m; 4 | std::cin>>n>>m; 5 | if(n<0 || m > 255 || n > 255 || (n>m) || m<0){ 6 | std::cout<<"Invalid codes"; 7 | return 0; 8 | } 9 | for(int i=n;i<=m;i++){ 10 | std::cout< " <<(char)i<<"\n"; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Sem. 03/Pract.03/Task02.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | int main() { 3 | int n,factorialOfN=1; 4 | std::cin>>n; 5 | while(n!=0){ 6 | factorialOfN *=n; 7 | n--; 8 | } 9 | std::cout< 2 | int main() { 3 | int n,sum=0; 4 | std::cin>>n; 5 | while(n>0 || sum > 9){ 6 | if(n==0){ 7 | n=sum; 8 | sum=0; 9 | } 10 | sum += n%10; 11 | n/=10; 12 | } 13 | std::cout< 2 | int main() { 3 | int n,sum=0,copyOfN; 4 | std::cin>>n; 5 | copyOfN=n; 6 | for(int i=1;i<=n;i++){ 7 | sum += i*copyOfN; 8 | copyOfN--; 9 | } 10 | std::cout< 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int sum = 0; 8 | 9 | for (int i = 100; i <= 999; i++) 10 | { 11 | int sumDigits = 0; 12 | int n = i; 13 | 14 | while (n != 0) 15 | { 16 | int lastDigit = n % 10; 17 | sumDigits += lastDigit; 18 | n /= 10; 19 | } 20 | 21 | if (sumDigits < 10 || sumDigits > 99) continue; 22 | 23 | bool isPrime = true; 24 | 25 | if (sumDigits < 2) isPrime = false; 26 | 27 | double sqrtn = sqrt(sumDigits); 28 | 29 | for (int j = 2; j <= sqrtn; j++) 30 | { 31 | if (sumDigits % j == 0) 32 | { 33 | isPrime = false; 34 | break; 35 | } 36 | } 37 | 38 | if (isPrime) sum += i; 39 | } 40 | 41 | cout << sum; 42 | 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /Sem. 03/Pract.03/Task06.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int main() { 4 | int sumOfPrimes=0; 5 | for(int i=100;i<=999;i++){ 6 | int sum=i%10 + (i/10)%10 + i/100; 7 | if(sum>1){ 8 | int sqrtOfSum=sqrt(sum); 9 | bool isPrime=true; 10 | for(int j = 2;j<=sqrtOfSum;j++){ 11 | if(sum%j==0) { 12 | isPrime = false; 13 | break; 14 | } 15 | } 16 | if(isPrime && sum>9 )sumOfPrimes+=i; 17 | } 18 | } 19 | std::cout< 2 | int main() { 3 | int n,sum=0; 4 | std::cin>>n; 5 | for (int i=1;i 2 | #include 3 | int main() { 4 | int n,length=0,armstrong=0; 5 | std::cin>>n; 6 | int copyOfN=n; 7 | while(copyOfN!=0){ 8 | length++; 9 | copyOfN/=10; 10 | } 11 | copyOfN=n; 12 | while(copyOfN!=0){ 13 | armstrong += std::pow((copyOfN%10),length); 14 | copyOfN/=10; 15 | } 16 | std::cout<<(n==armstrong); 17 | } 18 | -------------------------------------------------------------------------------- /Sem. 03/Pract.03/Task09.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int num = 0; 6 | std::cin >> num; 7 | 8 | if (num < 0) num *= -1; 9 | 10 | int bound = num / 2; 11 | 12 | for (int i = 2; i <= bound; i++) 13 | { 14 | int x = i; 15 | 16 | bool isPrimeX = true; 17 | double xSqrt = sqrt(x); 18 | 19 | for (int i = 2; i <= xSqrt; i++) 20 | { 21 | if (x % i == 0) 22 | { 23 | isPrimeX = false; 24 | break; 25 | } 26 | } 27 | 28 | if (!isPrimeX) continue; 29 | 30 | int y = num - i; 31 | 32 | bool isPrimeY = true; 33 | double ySqrt = sqrt(y); 34 | 35 | for (int i = 2; i <= ySqrt; i++) 36 | { 37 | if (y % i == 0) 38 | { 39 | isPrimeY = false; 40 | break; 41 | } 42 | } 43 | 44 | if (isPrimeY) 45 | { 46 | std::cout << num << " = " << x << " + " << y << std::endl; 47 | } 48 | } 49 | 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /Sem. 03/Pract.03/Task10.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int num = 0, reversed = 0; 6 | std::cin >> num; 7 | 8 | while (num != 0) 9 | { 10 | int lastDigit = num % 10; 11 | (reversed *= 10) += lastDigit; 12 | num /= 10; 13 | } 14 | 15 | int idx = 1; 16 | 17 | while (reversed != 0) 18 | { 19 | int lastDigit = reversed % 10; 20 | 21 | if (idx++ % 2 == 0) 22 | { 23 | std::cout << lastDigit << " "; 24 | } 25 | 26 | reversed /= 10; 27 | } 28 | 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /Sem. 03/Pract.03/Task11.cpp: -------------------------------------------------------------------------------- 1 | #include ; 2 | 3 | int main() 4 | { 5 | int a, b, c, d, e; 6 | std::cin >> a >> b >> c >> d >> e; 7 | 8 | for (int x = -100; x <= 100; x++) 9 | { 10 | int f_x = a * x * x * x * x + b * x * x * x + c * x * x + d * x + e; 11 | 12 | if (f_x >= 0) 13 | { 14 | std::cout << "x = " << x << " is a solution. f(x) = " << f_x << std::endl; 15 | } 16 | } 17 | 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /Sem. 03/Pract.03/Task12.cpp: -------------------------------------------------------------------------------- 1 | #include ; 2 | 3 | int main() { 4 | int n, k = 0, sum = 0; 5 | std::cin >> n >> k; 6 | 7 | while (k != -1) 8 | { 9 | int first = n; 10 | int second = k; 11 | 12 | if (first < second) 13 | { 14 | int temp = first; 15 | first = second; 16 | second = temp; 17 | } 18 | 19 | while (second != 0) 20 | { 21 | int mod = first % second; 22 | first = second; 23 | second = mod; 24 | } 25 | 26 | if (first == 1) 27 | { 28 | sum += k; 29 | } 30 | 31 | std::cin >> k; 32 | } 33 | 34 | std::cout << sum << std::endl; 35 | 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /Sem. 03/Pract.03/Task14.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int n; 8 | cin >> n; 9 | 10 | int sum = 0; 11 | int max = 0; 12 | 13 | for (int i = 0; i < n; i++) 14 | { 15 | int currentNum = 0; 16 | cin >> currentNum; 17 | 18 | sum += currentNum; 19 | 20 | if (currentNum > max) 21 | { 22 | max = currentNum; 23 | } 24 | } 25 | 26 | if (max == (sum - max)) { 27 | cout << "Yes: " << max << endl; 28 | } 29 | else { 30 | cout << "No" << endl; 31 | } 32 | 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /Sem. 03/Pract.03/Task15.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int k = 0; 6 | std::cin >> k; 7 | 8 | int num = 0; 9 | std::cin >> num; 10 | 11 | int count = 0, maxSuffix = 0; 12 | 13 | while (num != 0) 14 | { 15 | int copyK = k, copyNum = num; 16 | bool isSuffix = true; 17 | 18 | while (copyNum != 0) 19 | { 20 | int lastKDigit = copyK % 10; 21 | int lastNumDigit = copyNum % 10; 22 | 23 | if (lastKDigit != lastNumDigit) 24 | { 25 | isSuffix = false; 26 | } 27 | 28 | copyNum /= 10; 29 | copyK /= 10; 30 | } 31 | 32 | if (isSuffix && copyNum == 0) 33 | { 34 | std::cout << num << " is suffix of " << k << std::endl; 35 | count++; 36 | 37 | if (num > maxSuffix) 38 | { 39 | maxSuffix = num; 40 | } 41 | } 42 | else 43 | { 44 | std::cout << num << " is not suffix of " << k << std::endl; 45 | } 46 | 47 | std::cin >> num; 48 | } 49 | 50 | std::cout << "Found suffix count: " << count << std::endl; 51 | std::cout << "Max suffix: " << maxSuffix << std::endl; 52 | 53 | return 0; 54 | } 55 | -------------------------------------------------------------------------------- /Sem. 03/Pract.03/Task16.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int main(){ 4 | int n,start=1; 5 | std::cin>>n; 6 | for(int i=1;i<=n;i++) 7 | { 8 | for(int j=1;j<=n;j++) 9 | { 10 | if(i%2==1) 11 | { 12 | std::cout<< start << " "; 13 | start ++; 14 | } 15 | if(i%2==0) 16 | { 17 | start--; 18 | std::cout<< start<< " "; 19 | } 20 | } 21 | std::cout << "\n"; 22 | start+=n; 23 | } 24 | 25 | } -------------------------------------------------------------------------------- /Sem. 03/Pract.03/Theory.md: -------------------------------------------------------------------------------- 1 | # Теоретични задачи: 2 | 3 | **Задача 1**: Какво ще се отпечата на конзолата? 4 | 5 | ```c++ 6 | #include 7 | 8 | int main() 9 | { 10 | int i; 11 | 12 | for (i = 0; i < 5; i++) { 13 | if (i == 3) { 14 | continue; 15 | } 16 | std::cout << i << " "; 17 | } 18 | 19 | std::cout << i << std::endl; 20 | return 0; 21 | } 22 | ``` 23 | 24 | **Задача 2**: Какво ще се отпечата на конзолата? 25 | 26 | ```c++ 27 | #include 28 | 29 | int main() 30 | { 31 | int i = 9; 32 | 33 | while (i = 12) 34 | { 35 | if (i == 0) 36 | break; 37 | if (i == 9) 38 | continue; 39 | i--; 40 | std::cout << i << std::endl; 41 | } 42 | 43 | return 0; 44 | } 45 | ``` 46 | 47 | **Задача 3**: Какво ще се отпечата на конзолата? 48 | 49 | ```c++ 50 | #include 51 | 52 | using namespace std; 53 | 54 | int main() 55 | { 56 | int iter = 10; 57 | 58 | while (true) 59 | { 60 | cout << iter << endl; 61 | 62 | if (iter == 0) 63 | { 64 | break; 65 | } 66 | 67 | if (iter == 1) 68 | { 69 | continue; 70 | } 71 | 72 | iter--; 73 | } 74 | 75 | return 0; 76 | } 77 | ``` 78 | 79 | **Задача 4**: Какво ще се отпечата на конзолата? 80 | 81 | ```c++ 82 | #include 83 | 84 | int main() 85 | { 86 | for (int i = 0, j = 10; i < 2, j > 1; i++, j -= 2) { 87 | std::cout << i << " " << j << std::endl; 88 | } 89 | 90 | return 0; 91 | } 92 | ``` 93 | 94 | 95 | **Задача 5**: Какво ще се отпечата на конзолата? 96 | 97 | ```c++ 98 | #include 99 | 100 | int main() { 101 | int i = 0; 102 | 103 | do { 104 | std::cout << i << " "; 105 | i++; 106 | } while (i < 5, i % 2 == 0); 107 | 108 | std::cout << std::endl; 109 | 110 | return 0; 111 | } 112 | ``` 113 | 114 | **Задача 6**: Какво ще се отпечата на конзолата? 115 | 116 | ```c++ 117 | do { 118 | int y = 1; 119 | std::cout << y++ << " "; 120 | } while (y <= 10); 121 | ``` 122 | -------------------------------------------------------------------------------- /Sem. 03/Pract.03/task16.1.cpp: -------------------------------------------------------------------------------- 1 | //Задача 16: Да се напише програма, която приема цяло положително число n и отпечатва числата от 1 до n*n в спираловиден вид. 2 | 3 | #include 4 | 5 | int main() { 6 | int n = 0; 7 | int row = 1; 8 | std::cin >> n; 9 | int sum = n * n; 10 | 11 | for(int i = 1; i <= sum;i++) { 12 | if(row % 2 == 1) { 13 | std::cout << i << ' '; 14 | } else { 15 | int swapped = i; 16 | swapped = n * row - (( i - 1) - (row * n - n)); 17 | std::cout << swapped << ' '; 18 | } 19 | if(i % n == 0) { 20 | row++; 21 | std::cout << '\n'; 22 | } 23 | } 24 | 25 | return 0; 26 | } -------------------------------------------------------------------------------- /Sem. 03/Solutions/Task01.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | int number, sum = 0; 5 | 6 | do { 7 | std::cin >> number; 8 | sum += number; 9 | } while (number != 0); 10 | 11 | std::cout << sum; 12 | } -------------------------------------------------------------------------------- /Sem. 03/Solutions/Task02.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | int number; 5 | std::cin >> number; 6 | 7 | int reversed = 0; 8 | while (number > 0) { 9 | int lastDigit = number % 10; 10 | reversed = reversed * 10 + lastDigit; 11 | number /= 10; 12 | } 13 | 14 | std::cout << reversed + 1; 15 | } -------------------------------------------------------------------------------- /Sem. 03/Solutions/Task03.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | int main() { 3 | int mostCommonDigit = 0; 4 | int mostCommonDigitCount = 0; 5 | 6 | int number; 7 | std::cin >> number; 8 | 9 | for (int i = 0; i <= 9; i++) { 10 | int currentCount = 0; 11 | int copy = number; 12 | 13 | while (copy != 0) { 14 | if (copy % 10 == i) { 15 | currentCount++; 16 | } 17 | 18 | copy /= 10; 19 | } 20 | 21 | if (mostCommonDigitCount > currentCount) { 22 | mostCommonDigitCount = currentCount; 23 | mostCommonDigit = i; 24 | } 25 | } 26 | 27 | std::cout << mostCommonDigit << " has appeared " << mostCommonDigitCount; 28 | } -------------------------------------------------------------------------------- /Sem. 03/Solutions/Task04.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | int a, b; 5 | std::cin >> a >> b; 6 | 7 | int i = a > b ? b : a; 8 | while (a % i != 0 || b % i != 0) { 9 | i--; 10 | } 11 | 12 | std::cout << i; 13 | } -------------------------------------------------------------------------------- /Sem. 03/Solutions/Task05.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | int a, b; 5 | std::cin >> a >> b; 6 | int i = a < b ? b : a; 7 | 8 | while (i % a != 0 || i % b != 0){ 9 | i++; 10 | } 11 | 12 | std::cout << i; 13 | } -------------------------------------------------------------------------------- /Sem. 03/Solutions/Task06.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() { 7 | int num; 8 | cin >> num; 9 | 10 | if (num == 1) { 11 | cout << "Not prime" << endl; 12 | return 0; 13 | } 14 | 15 | int sqrtN = sqrt(num); 16 | for (int i = 2; i <= sqrtN; i++) { 17 | if (num % i == 0) { 18 | cout << "Not prime" << endl; 19 | return 0; 20 | } 21 | } 22 | 23 | cout << "Prime" << endl; 24 | return 0; 25 | } -------------------------------------------------------------------------------- /Sem. 03/Solutions/Task07.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | int number; 5 | std::cin >> number; 6 | 7 | for (int i = number; i >= 1; i--) { 8 | bool isPrime = true; 9 | 10 | if (i == 2) { 11 | // divide as many times as you can 12 | while (number % i == 0) { 13 | std::cout << i << " "; 14 | number /= i; 15 | } 16 | 17 | continue; 18 | } 19 | 20 | if (i == 1 || i % 2 == 0) { 21 | isPrime = false; 22 | continue; 23 | } 24 | 25 | double sqrtN = sqrt(i); 26 | for (int j = 3; j <= sqrtN; j += 2) { 27 | if (i % j == 0) { 28 | isPrime = false; 29 | break; 30 | } 31 | } 32 | 33 | if (isPrime) { 34 | // divide as many times as you can 35 | while (number % i == 0) { 36 | std::cout << i << " "; 37 | number /= i; 38 | } 39 | } 40 | } 41 | } 42 | 43 | -------------------------------------------------------------------------------- /Sem. 04/Pract.04/Task14.cpp: -------------------------------------------------------------------------------- 1 | #include ; 2 | 3 | int gcd(int a, int b); 4 | int lcm(int a, int b); 5 | void gcdAndLcmOfMultipleNumbers(); 6 | 7 | int main() 8 | { 9 | gcdAndLcmOfMultipleNumbers(); 10 | 11 | return 0; 12 | } 13 | 14 | int gcd(int a, int b) { 15 | if (a < b) 16 | { 17 | int temp = a; 18 | a = b; 19 | b = temp; 20 | } 21 | 22 | while (b != 0) 23 | { 24 | int mod = a % b; 25 | a = b; 26 | b = mod; 27 | } 28 | 29 | return a; 30 | } 31 | 32 | int lcm(int a, int b) { 33 | return (a / gcd(a, b)) * b; 34 | } 35 | 36 | void gcdAndLcmOfMultipleNumbers() { 37 | int a, n; 38 | std::cin >> n >> a; 39 | int gcdRes = a; 40 | int lcmRes = a; 41 | 42 | for (; n - 1 > 0; n--) 43 | { 44 | std::cin >> a; 45 | gcdRes = gcd(gcdRes, a); 46 | lcmRes = lcm(lcmRes, a); 47 | } 48 | 49 | std::cout << "GCD: " << gcdRes << '\n'; 50 | std::cout << "LCM: " << lcmRes << '\n'; 51 | } 52 | -------------------------------------------------------------------------------- /Sem. 04/Pract.04/Task15.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | int getCountOfADigit(int number, int digit) { 6 | int count = 0; 7 | while (number != 0) { 8 | int lastDigit = number % 10; 9 | if (lastDigit == digit) 10 | count++; 11 | number /= 10; 12 | } 13 | return count; 14 | } 15 | 16 | int sortDigits( int num) { 17 | int result = 0; 18 | for (int i = 9; i >= 0; i--){ 19 | int count = getCountOfADigit(num, i); 20 | while (count > 0) { 21 | (result *= 10) += i; 22 | count--; 23 | } 24 | } 25 | return result; 26 | } 27 | int main() 28 | { 29 | cout << sortDigits(536241); 30 | } 31 | 32 | -------------------------------------------------------------------------------- /Sem. 04/Pract.04/Task17.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int getAbs(int num){ 5 | return (num < 0 ? -num : num); 6 | } 7 | 8 | int getDivision(int first, int second) { 9 | if (second == 0) 10 | return 0;//impossible division 11 | 12 | int sign = (((first * second) > 0) ? +1 : -1); 13 | 14 | first = getAbs(first); 15 | second = getAbs(second); 16 | 17 | 18 | int count = 0; 19 | while (first - second >= 0) { 20 | first -= second; 21 | count++; 22 | } 23 | 24 | 25 | return count * sign; 26 | } 27 | 28 | int main() 29 | { 30 | cout << getDivision(-8, 2); 31 | 32 | } 33 | 34 | -------------------------------------------------------------------------------- /Sem. 04/Pract.04/Theory.md: -------------------------------------------------------------------------------- 1 | # Теоретични задачи: 2 | 3 | **Задача.1** Какво ще се отпечата? 4 | 5 | ```c++ 6 | void f(int b) { 7 | b++; 8 | a += 100; 9 | std::cout << (b % 2 == 0) << std::endl; 10 | } 11 | 12 | int main() { 13 | int a = 200, b = 3; 14 | f(b); 15 | std::cout << a << " " << b << std::endl; 16 | } 17 | ``` 18 | 19 | **Задача.2** Какво ще се отпечата на конзолата? 20 | 21 | ```c++ 22 | #include 23 | int a = 100; 24 | int main() 25 | { 26 | { 27 | int a = 10; 28 | { 29 | a += 5; 30 | ::a += 5; 31 | int a = 3; 32 | a += 2; 33 | } 34 | std::cout << a << std::endl; 35 | } 36 | std::cout << a << std::endl; 37 | } 38 | ``` 39 | 40 | **Задача.3** Какво ще се отпечата? 41 | 42 | ```c++ 43 | void f(double a = 2, double b) { 44 | 45 | } 46 | 47 | void print(int a) { 48 | std::cout << a; 49 | } 50 | 51 | void print(double a) { 52 | std::cout << a; 53 | } 54 | 55 | int main() { 56 | double b = 22.2; 57 | char c = 'A'; 58 | 59 | print(b); 60 | print(c); 61 | 62 | f(b); 63 | } 64 | ``` 65 | 66 | **Задача.4** Какво ще се отпечата? 67 | 68 | ```c++ 69 | int num = 10; 70 | int fun(int num) { 71 | std::cout << ++num << std::endl; 72 | return num * 3; 73 | } 74 | 75 | int main() { 76 | int num = 10; 77 | int res = fun(num); 78 | std::cout << num << " " << res; 79 | } 80 | ``` 81 | -------------------------------------------------------------------------------- /Sem. 04/Solutions/IsPalindrome.cpp: -------------------------------------------------------------------------------- 1 | unsigned int reverseNumber(unsigned int number) { 2 | unsigned int reversed = 0; 3 | 4 | while (number != 0) { 5 | (reversed *= 10) += number % 10; 6 | number /= 10; 7 | } 8 | 9 | return reversed; 10 | } 11 | 12 | bool isPalindrome(unsigned int number) { 13 | return number == reverseNumber(number); 14 | } 15 | -------------------------------------------------------------------------------- /Sem. 04/Solutions/IsPrime.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | bool isPrime(unsigned int number) { 4 | if (number == 2) { 5 | return true; 6 | } 7 | 8 | if (number == 1 || number % 2 == 0) { 9 | return false; 10 | } 11 | 12 | double sqrtN = sqrt(number); 13 | for (int i = 3; i <= sqrtN; i += 2) { 14 | if (number % i == 0) { 15 | return false; 16 | } 17 | } 18 | 19 | return true; 20 | } -------------------------------------------------------------------------------- /Sem. 04/Solutions/LogK.cpp: -------------------------------------------------------------------------------- 1 | unsigned int log(unsigned int n, unsigned int k) { 2 | unsigned int powerOfK = 1; 3 | unsigned int count = 0; 4 | 5 | while (powerOfK <= n) { 6 | powerOfK *= k; 7 | count++; 8 | } 9 | 10 | return count - 1; 11 | } -------------------------------------------------------------------------------- /Sem. 04/Solutions/Points.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | const double EPSILON = 0.00001; 4 | 5 | double distBetweenTwoPoints(int p1x, int p1y, int p2x, int p2y) { 6 | int dx = p1x - p2x; 7 | int dy = p1y - p2y; 8 | 9 | return sqrt(dx * dx + dy * dy); 10 | } 11 | 12 | bool myAbs(int n) { 13 | return n < 0 ? -n : n; 14 | } 15 | 16 | bool areOnOneCircleV1(int p1x, int p1y, int p2x, int p2y) { 17 | return myAbs(distBetweenTwoPoints(p1x, p1y, 0, 0) - distBetweenTwoPoints(p2x, p2y, 0, 0)) <= EPSILON; 18 | } 19 | 20 | // without epsilon 21 | bool areOnOneCircleV2(int p1x, int p1y, int p2x, int p2y) { 22 | return p1x * p1x + p1y * p1y == p2x * p2x + p2y * p2y; 23 | } -------------------------------------------------------------------------------- /Sem. 04/Solutions/Pow.cpp: -------------------------------------------------------------------------------- 1 | // n^k 2 | unsigned int myPow(unsigned int n, unsigned int k) { 3 | unsigned result = 1; 4 | for (int i = 0; i < k; i++) { 5 | result *= n; 6 | } 7 | 8 | return result; 9 | } 10 | -------------------------------------------------------------------------------- /Sem. 04/Solutions/Prefix-Infix-Suffix.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | bool isSuffix(unsigned int number, unsigned int sufix) { 4 | if (number < sufix) { 5 | return false; 6 | } 7 | 8 | while (sufix != 0) { 9 | if (number % 10 != sufix % 10) { 10 | return false; 11 | } 12 | 13 | number /= 10; 14 | sufix /= 10; 15 | } 16 | 17 | return true; 18 | } 19 | 20 | bool isPrefix(unsigned int number, unsigned int expectedPrefix) { 21 | // this check is done in the loop condition 22 | // if (number < expectedPrefix) { 23 | // return false; 24 | // } 25 | 26 | while (number >= expectedPrefix) { 27 | if (number == expectedPrefix) { 28 | return true; 29 | } 30 | 31 | number /= 10; 32 | } 33 | 34 | return false; 35 | } 36 | 37 | bool isInfix(unsigned int number, unsigned int expectedInfix) { 38 | // this check is done in the loop condition 39 | // if (number < expectedInfix) { 40 | // return false; 41 | // } 42 | 43 | while (number >= expectedInfix) { 44 | if (isSuffix(number, expectedInfix)) { 45 | return true; 46 | } 47 | 48 | number /= 10; 49 | } 50 | 51 | return false; 52 | } 53 | 54 | int main() { 55 | int a, b; 56 | std::cin >> a >> b; 57 | std::cout << isPrefix(a, b); 58 | } -------------------------------------------------------------------------------- /Sem. 04/Solutions/ReverseNumber.cpp: -------------------------------------------------------------------------------- 1 | unsigned int reverseNumber(unsigned int number) { 2 | unsigned int reversed = 0; 3 | 4 | while (number != 0) { 5 | (reversed *= 10) += number % 10; 6 | number /= 10; 7 | } 8 | 9 | return reversed; 10 | } -------------------------------------------------------------------------------- /Sem. 05/Pract.05/Task04.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | void concat(int& num, int digit) 6 | { 7 | num = num * 10 + digit; 8 | } 9 | 10 | int reverse(int number) { 11 | int res = 0; 12 | 13 | while (number != 0) { 14 | int digit = number % 10; 15 | concat(res, digit); 16 | number /= 10; 17 | } 18 | 19 | return res; 20 | } 21 | 22 | void evensAndOdds(int num, int& evens, int& odds) 23 | { 24 | int reversed = reverse(num); 25 | int idx = 1; 26 | 27 | while (reversed != 0) { 28 | int lastDigit = reversed % 10; 29 | 30 | if (idx % 2 == 0) { 31 | concat(evens, lastDigit); 32 | } 33 | else { 34 | concat(odds, lastDigit); 35 | } 36 | 37 | idx++; 38 | reversed /= 10; 39 | } 40 | } 41 | 42 | int main() { 43 | int a; 44 | cin >> a; 45 | 46 | int evens = 0, odds = 0; 47 | 48 | evensAndOdds(a, evens, odds); 49 | 50 | std::cout << evens << " " << odds << std::endl; 51 | 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /Sem. 05/Pract.05/Task05.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | void concat(int& n, int digit) { 6 | n = n * 10 + digit; 7 | } 8 | 9 | void setKthdigit(int& number, int k, int newDigit) { 10 | int digit, reversed = 0; 11 | 12 | for (int i = 1; i <= k; i++) { 13 | digit = number % 10; 14 | number /= 10; 15 | if (i == k) digit = newDigit; 16 | concat(reversed, digit); 17 | } 18 | 19 | while (reversed != 0) { 20 | digit = reversed % 10; 21 | concat(number, digit); 22 | reversed /= 10; 23 | } 24 | } 25 | 26 | int findK(int number, int k) { 27 | for (int i = 1; i < k; i++) { 28 | number /= 10; 29 | } 30 | 31 | return number % 10; 32 | } 33 | 34 | void reverse(int& number) { 35 | int reversedNum = 0; 36 | int n = number; 37 | 38 | while (n != 0) { 39 | int digit = n % 10; 40 | concat(reversedNum, digit); 41 | n /= 10; 42 | } 43 | 44 | number = reversedNum; 45 | } 46 | 47 | void swapDigits(int& m, int& n, int k) { 48 | reverse(m); 49 | reverse(n); 50 | 51 | int km = findK(m, k); 52 | int kn = findK(n, k); 53 | 54 | setKthdigit(n, k, km); 55 | setKthdigit(m, k, kn); 56 | 57 | reverse(m); 58 | reverse(n); 59 | } 60 | 61 | int main() { 62 | int m, n, k; 63 | cin >> m >> n >> k; 64 | 65 | swapDigits(m, n, k); 66 | 67 | cout << m << " " << n; 68 | 69 | return 0; 70 | } 71 | -------------------------------------------------------------------------------- /Sem. 05/Pract.05/Task06.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | void an(double& a, int n) { 6 | double c; 7 | 8 | for (int i = 1; i <= n; i++) { 9 | c = (a * 3) / 2; 10 | a = c; 11 | } 12 | } 13 | 14 | bool isRowEvenOrOdd(int n) { 15 | double a = 1.0; 16 | 17 | an(a, n); 18 | 19 | int number = a; 20 | return number % 2 == 0; 21 | } 22 | 23 | int main() { 24 | int n; 25 | cin >> n; 26 | 27 | if (isRowEvenOrOdd(n)) { 28 | cout << "is even"; 29 | } 30 | else { 31 | cout << "not even"; 32 | } 33 | 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /Sem. 05/Pract.05/Task08.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int digitsInNum(int num) { 4 | int count = 0; 5 | 6 | while (num != 0) { 7 | count++; 8 | num /= 10; 9 | } 10 | 11 | return count; 12 | } 13 | 14 | int sumOfDigitsInNum(int num) { 15 | int sum = 0; 16 | 17 | while (num != 0) { 18 | sum += num % 10; 19 | num /= 10; 20 | } 21 | 22 | return sum; 23 | } 24 | 25 | int aritmeticMean(int num) { 26 | return sumOfDigitsInNum(num) / digitsInNum(num); 27 | } 28 | 29 | bool aritmeticMeanGreaterOrEqual(int num, int k) { 30 | return aritmeticMean(num) >= k; 31 | } 32 | 33 | void run() { 34 | int m, n, k; 35 | std::cin >> m >> n >> k; 36 | 37 | for (int i = m; i <= n; i++) { 38 | if (aritmeticMeanGreaterOrEqual(i, k)) std::cout << i << " "; 39 | } 40 | } 41 | 42 | int main() { 43 | run(); 44 | } 45 | 46 | -------------------------------------------------------------------------------- /Sem. 05/Pract.05/Task09.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void swap(int& a, int& b); 4 | void getNumsWithTwoAdjacentEqualDigits(int k, int l); 5 | bool hasAdjacentDigits(int num); 6 | 7 | int main() { 8 | std::cout << "Enter interval [k l]: "; 9 | int k, l; 10 | std::cin >> k >> l; 11 | std::cout << "\n"; 12 | getNumsWithTwoAdjacentEqualDigits(k, l); 13 | } 14 | 15 | void swap(int& a, int& b) { 16 | int temp = a; 17 | a = b; 18 | b = temp; 19 | } 20 | 21 | bool hasAdjacentDigits(int num) { 22 | while (num >= 10) { 23 | int lastDigit = num % 10; 24 | int secondLastDigit = (num / 10) % 10; 25 | 26 | if (lastDigit == secondLastDigit) { 27 | return true; 28 | } 29 | num /= 10; 30 | } 31 | 32 | return false; 33 | } 34 | 35 | void getNumsWithTwoAdjacentEqualDigits(int k, int l) { 36 | if (k > l) swap(k, l); 37 | 38 | for (int num = k; num <= l; num++) { 39 | if (hasAdjacentDigits(num)) 40 | { 41 | std::cout << num << " "; 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /Sem. 05/Pract.05/Task10.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int powOfTen(int k) { 4 | int powerOfTen = 1; 5 | 6 | while (k != 0) { 7 | powerOfTen *= 10; 8 | k--; 9 | } 10 | 11 | return powerOfTen; 12 | } 13 | 14 | int getNumberLength(int b) { 15 | int length = 0; 16 | 17 | while (b != 0) { 18 | length++; 19 | b /= 10; 20 | } 21 | 22 | return length; 23 | } 24 | 25 | void newNumbers(int& a, int& b, int k) { 26 | int tempLastKDigits = a % powOfTen(k); 27 | 28 | b = tempLastKDigits * powOfTen(getNumberLength(b)) + b; 29 | a /= powOfTen(k); 30 | } 31 | 32 | int main() { 33 | int a, b, k; 34 | std::cin >> a >> b >> k; 35 | 36 | newNumbers(a, b, k); 37 | 38 | std::cout << a << " " << b; 39 | } -------------------------------------------------------------------------------- /Sem. 05/Pract.05/Task11.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | bool isLeapYear(unsigned year); 4 | unsigned getDaysInMonth(unsigned month, unsigned year); 5 | bool isDateValid(unsigned day, unsigned month, unsigned year); 6 | void goToNextDay(unsigned int& day, unsigned int& month, unsigned int& year); 7 | void printDateAfterNDays(unsigned day, unsigned month, unsigned year, unsigned daysToAdd); 8 | 9 | int main() { 10 | std::cout << "Enter date in format dd//mm//yyyy and then days, which will be added to it: "; 11 | 12 | unsigned day, month, year, n; 13 | std::cin >> day >> month >> year >> n; 14 | 15 | std::cout << std::endl; 16 | 17 | printDateAfterNDays(day, month, year, n); 18 | 19 | return 0; 20 | } 21 | 22 | bool isLeapYear(unsigned year) { 23 | return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); 24 | } 25 | 26 | unsigned getDaysInMonth(unsigned month, unsigned year) { 27 | if (month == 2) { 28 | return isLeapYear(year) ? 29 : 28; 29 | } 30 | if (month == 4 || month == 6 || month == 9 || month == 11) { 31 | return 30; 32 | } 33 | 34 | return 31; 35 | } 36 | 37 | bool isDateValid(unsigned day, unsigned month, unsigned year) { 38 | if (month < 1 || month > 12 || year == 0) return false; 39 | return day >= 1 && day <= getDaysInMonth(month, year); 40 | } 41 | 42 | void goToNextDay(unsigned int& day, unsigned int& month, unsigned int& year) 43 | { 44 | if (!isDateValid(day, month, year)) return; 45 | 46 | day++; 47 | 48 | if (day > getDaysInMonth(month, year)) 49 | { 50 | day = 1; 51 | 52 | (month == 12) ? month = 1 : month++; 53 | 54 | if (month == 1) year++; 55 | } 56 | } 57 | 58 | void printDateAfterNDays(unsigned day, unsigned month, unsigned year, unsigned daysToAdd) { 59 | if (!isDateValid(day, month, year)) { 60 | std::cout << "This date is invalid!"; 61 | return; 62 | } 63 | 64 | int copyNDays = daysToAdd; 65 | 66 | while (copyNDays != 0) 67 | { 68 | goToNextDay(day, month, year); 69 | copyNDays--; 70 | } 71 | 72 | std::cout << "Date after " << daysToAdd << " days: " 73 | << day << "/" << month << "/" << year << std::endl; 74 | } 75 | -------------------------------------------------------------------------------- /Sem. 05/Pract.05/Theory.md: -------------------------------------------------------------------------------- 1 | # Подготовка за контролно 2 | 3 | **Задача 1:** Опишете последователно какво ще изведе на екрана следният програмен фрагмент. Обосновете отговора си. 4 | 5 | ```c++ 6 | for (int i = 0; i <= 20; i*=2, cout << ++i << " " << endl); 7 | ``` 8 | 9 | **Задача 2:** Напишете еквивалентен код на следния програмен фрагмент, като използвате само оператор switch: 10 | 11 | ```c++ 12 | int a; 13 | if (a == 7) cout << “seven”; 14 | if ( (a == 3) || (a == 5) ) cout << “three and five”; 15 | if (a != 3) cout << “FMI rullz”; 16 | ``` 17 | 18 | **Задача 3:** Напишете еквивалентен код на следния програмен фрагмент, като използвате оператор switch: 19 | 20 | ```c++ 21 | int x, y; 22 | cin >> x >> y; 23 | 24 | if (x == 3 && y == 2) 25 | cout << "it is ok"; 26 | else if (x == 4) 27 | cout << "not ok"; 28 | else cout << "4567"; 29 | ``` 30 | 31 | **Задача 4:** Забелязвате ли някакъв проблем в следния код? Обяснете защо. Може ли да се подобри нещо в този код? 32 | 33 | ```C++ 34 | double num; 35 | cin >> num; 36 | cout << num%4; 37 | ``` 38 | -------------------------------------------------------------------------------- /Sem. 05/Pract.05/bullsAndCows.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | const unsigned int DIGIT_COUNT = 4; 4 | 5 | unsigned int countDigitOccurences(unsigned int n, unsigned int digit) 6 | { 7 | if (n == 0 && digit == 0) return 1; 8 | 9 | unsigned int count = 0; 10 | 11 | while (n != 0) 12 | { 13 | unsigned lastDigit = n % 10; 14 | 15 | if (lastDigit == digit) 16 | { 17 | count++; 18 | } 19 | 20 | n /= 10; 21 | } 22 | 23 | return count; 24 | } 25 | 26 | bool areDistinctDigits(unsigned int n) 27 | { 28 | for (unsigned int i = 0; i <= 9; i++) 29 | { 30 | if (countDigitOccurences(n, i) > 1) 31 | { 32 | return false; 33 | } 34 | } 35 | 36 | return true; 37 | } 38 | 39 | unsigned int digitsCount(unsigned int n) 40 | { 41 | if (n == 0) return 1; 42 | 43 | unsigned int count = 0; 44 | 45 | while (n != 0) 46 | { 47 | count++; 48 | n /= 10; 49 | } 50 | 51 | return count; 52 | } 53 | 54 | bool isValidInput(unsigned int n) 55 | { 56 | return areDistinctDigits(n) && digitsCount(n) == DIGIT_COUNT; 57 | } 58 | 59 | unsigned int getBulls(unsigned int toGuess, unsigned int myGuess) 60 | { 61 | unsigned int bullsCount = 0; 62 | 63 | while (toGuess != 0) 64 | { 65 | if (toGuess % 10 == myGuess % 10) 66 | { 67 | bullsCount++; 68 | } 69 | 70 | toGuess /= 10; 71 | myGuess /= 10; 72 | } 73 | 74 | return bullsCount; 75 | } 76 | 77 | unsigned int getBullsAndCowsSum(unsigned int toGuess, unsigned int myGuess) 78 | { 79 | unsigned int sum = 0; 80 | 81 | while (toGuess != 0) 82 | { 83 | unsigned int lastDigit = toGuess % 10; 84 | 85 | if (countDigitOccurences(myGuess, lastDigit) == 1) 86 | { 87 | sum++; 88 | } 89 | 90 | toGuess /= 10; 91 | } 92 | 93 | return sum; 94 | } 95 | 96 | void getBullsAndCows(unsigned int toGuess, unsigned int myGuess, unsigned int& bulls, unsigned int& cows) 97 | { 98 | bulls = getBulls(toGuess, myGuess); 99 | cows = getBullsAndCowsSum(toGuess, myGuess) - bulls; 100 | } 101 | 102 | unsigned int input() 103 | { 104 | unsigned int n = 0; 105 | 106 | do 107 | { 108 | std::cin >> n; 109 | } while (!isValidInput(n)); 110 | 111 | return n; 112 | } 113 | 114 | void runGame() 115 | { 116 | unsigned int toGuess = input(); 117 | std::cout << "Success! You provided a valid secret code!" << std::endl; 118 | 119 | unsigned int bulls = 0, cows = 0; 120 | 121 | do 122 | { 123 | unsigned int myGuess = input(); 124 | 125 | getBullsAndCows(toGuess, myGuess, bulls, cows); 126 | 127 | std::cout << "Bulls: " << bulls << " Cows: " << cows << std::endl; 128 | } while (bulls != DIGIT_COUNT); 129 | 130 | std::cout << "Congratulations! You guessed the secret code: " << toGuess << std::endl; 131 | } 132 | 133 | int main() 134 | { 135 | runGame(); 136 | 137 | return 0; 138 | } 139 | -------------------------------------------------------------------------------- /Sem. 06/Pract.06/Task10.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | constexpr int MAX_SIZE = 50; 5 | 6 | bool chekcIfDistinct(const int arr[], int size) { 7 | for (int i = 0; i < size - 1; i++) { 8 | for (int j = i + 1; j < size; j++) { 9 | if (arr[i] == arr[j]) { 10 | return false; 11 | } 12 | } 13 | } 14 | 15 | return true; 16 | } 17 | 18 | int main() { 19 | int n; 20 | cin >> n; 21 | int arr[MAX_SIZE]; 22 | 23 | for (int i = 0; i < n; i++) { 24 | cin >> arr[i]; 25 | } 26 | 27 | cout << (chekcIfDistinct(arr, n) ? "true" : "false") << endl; 28 | } -------------------------------------------------------------------------------- /Sem. 06/Pract.06/Task10_bonus.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | constexpr int MAX_SIZE = 50; 5 | constexpr int MAX_ELEMENT = 30; 6 | 7 | bool chekcIfDistinct(const int arr[], int size) { 8 | int seen[MAX_ELEMENT] = { false }; 9 | 10 | for (int i = 0; i < size; i++) { 11 | int num = arr[i]; 12 | 13 | if (num < 1 || num >= MAX_ELEMENT) return false; 14 | 15 | if (seen[num]) return false; 16 | 17 | seen[num] = true; 18 | } 19 | 20 | return true; 21 | } 22 | 23 | int main() { 24 | int n; 25 | cin >> n; 26 | int arr[MAX_SIZE]; 27 | 28 | for (int i = 0; i < n; i++) { 29 | cin >> arr[i]; 30 | } 31 | 32 | cout << (chekcIfDistinct(arr, n) ? "true" : "false") << endl; 33 | } -------------------------------------------------------------------------------- /Sem. 06/Pract.06/Task11.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | bool findSubarray(const int[], int, const int[], int); 5 | 6 | int main() { 7 | int arr1[4] = { 1, 2, 3, 4 }; 8 | int arr2[3] = { 1, 2, 3 }; 9 | 10 | cout << (findSubarray(arr1, 4, arr2, 3) ? "true" : "false") << endl; 11 | 12 | return 0; 13 | } 14 | 15 | bool findSubarray(const int arr1[], int size1, const int arr2[], int size2) { 16 | if (size2 > size1) return false; 17 | 18 | for (int i = 0; i <= size1 - size2; i++) { 19 | bool areEqual = true; 20 | for (int j = 0; j < size2; j++) { 21 | if (arr1[i + j] != arr2[j]) { 22 | areEqual = false; 23 | break; 24 | } 25 | } 26 | 27 | if (areEqual) return true; 28 | } 29 | 30 | return false; 31 | } 32 | -------------------------------------------------------------------------------- /Sem. 06/Pract.06/Task12.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | constexpr int DIGIT_SIZE = 5; 5 | 6 | void printArray(const int[], int); 7 | 8 | void addOneToArray(int[]); 9 | 10 | int main() { 11 | int num[DIGIT_SIZE] = { 0, 1, 0, 0, 9 }; 12 | 13 | addOneToArray(num); 14 | 15 | printArray(num, DIGIT_SIZE); 16 | 17 | return 0; 18 | } 19 | 20 | void printArray(const int arr[], int size) { 21 | for (int i = 0; i < size; i++) { 22 | cout << arr[i] << " "; 23 | } 24 | 25 | cout << endl; 26 | } 27 | 28 | void addOneToArray(int num[]) { 29 | int memory = 0; 30 | 31 | num[DIGIT_SIZE - 1]++; 32 | 33 | if (num[DIGIT_SIZE - 1] == 10) { 34 | num[DIGIT_SIZE - 1] = 0; 35 | memory = 1; 36 | 37 | for (int i = DIGIT_SIZE - 2; i >= 0; i--) { 38 | num[i] += memory; 39 | memory = 0; 40 | 41 | if (num[i] == 10) { 42 | num[i] = 0; 43 | memory = 1; 44 | } else { 45 | break; 46 | } 47 | } 48 | } 49 | } -------------------------------------------------------------------------------- /Sem. 06/Pract.06/Task13.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | constexpr int MAX_SIZE = 100; 5 | 6 | bool checkIfResultHasElement(const int[], int, int); 7 | 8 | void unionArrays(const int[], int, const int[], int, int[], int&); 9 | 10 | void intersectionArrays(const int[], int, const int[], int, int[], int&); 11 | 12 | void printArray(const int[], int); 13 | 14 | int main() { 15 | int arr1[5] = { 2, 4, 1, 7, 8 }; 16 | int arr2[4] = { 1, 2, 3, 5 }; 17 | 18 | int unionArray[MAX_SIZE]; 19 | int unionArrLength = 0; 20 | 21 | int intersectionArray[MAX_SIZE]; 22 | int interArrLength = 0; 23 | 24 | unionArrays(arr1, 5, arr2, 4, unionArray, unionArrLength); 25 | cout << "Union: "; 26 | printArray(unionArray, unionArrLength); 27 | 28 | intersectionArrays(arr1, 5, arr2, 4, intersectionArray, interArrLength); 29 | cout << "Intersection: "; 30 | printArray(intersectionArray, interArrLength); 31 | 32 | return 0; 33 | } 34 | 35 | bool checkIfResultHasElement(const int result[], int size, int element) { 36 | for (int j = 0; j < size; j++) { 37 | if (element == result[j]) { 38 | return true; 39 | } 40 | } 41 | 42 | return false; 43 | } 44 | 45 | void unionArrays(const int arr1[], int size1, const int arr2[], int size2, int result[], int& size3) { 46 | for (int i = 0; i < size1; i++) { 47 | bool isPresent = checkIfResultHasElement(result, size3, arr1[i]); 48 | 49 | if (!isPresent) { 50 | result[size3++] = arr1[i]; 51 | } 52 | } 53 | 54 | for (int i = 0; i < size2; i++) { 55 | bool isPresent = checkIfResultHasElement(result, size3, arr2[i]); 56 | 57 | if (!isPresent) { 58 | result[size3++] = arr2[i]; 59 | } 60 | } 61 | } 62 | 63 | void intersectionArrays(const int arr1[], int size1, const int arr2[], int size2, int result[], int& size3) { 64 | for (int i = 0; i < size1; i++) { 65 | if (checkIfResultHasElement(arr2, size2, arr1[i]) && !checkIfResultHasElement(result, size3, arr1[i])) 66 | { 67 | result[size3++] = arr1[i]; 68 | } 69 | } 70 | } 71 | 72 | void printArray(const int arr[], int size) { 73 | for (int i = 0; i < size; i++) { 74 | cout << arr[i] << " "; 75 | } 76 | 77 | cout << endl; 78 | } 79 | -------------------------------------------------------------------------------- /Sem. 06/Pract.06/Task14.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | constexpr int MAX_SIZE = 100; 5 | 6 | void mergeArrays(const int[], int, const int[], int, int[], int &); 7 | 8 | void printArray(const int[], int); 9 | 10 | int main() { 11 | int arr1[4] = { 1, 5, 7, 8 }; 12 | int arr2[3] = { 2, 3, 6 }; 13 | int result[MAX_SIZE]; 14 | 15 | int size3 = 0; 16 | 17 | mergeArrays(arr1, 4, arr2, 3, result, size3); 18 | printArray(result, size3); 19 | 20 | return 0; 21 | } 22 | 23 | void mergeArrays(const int arr1[], int size1, const int arr2[], int size2, int result[], int & size3) { 24 | int i = 0, j = 0; 25 | 26 | while (i < size1 && j < size2) { 27 | if (arr1[i] > arr2[j]) { 28 | result[size3++] = arr2[j++]; 29 | } else { 30 | result[size3++] = arr1[i++]; 31 | } 32 | } 33 | 34 | while (i < size1) { 35 | result[size3++] = arr1[i++]; 36 | } 37 | 38 | while (j < size2) { 39 | result[size3++] = arr2[j++]; 40 | } 41 | } 42 | 43 | void printArray(const int arr[], int size) { 44 | for (int i = 0; i < size; i++) { 45 | cout << arr[i] << " "; 46 | } 47 | 48 | cout << endl; 49 | } -------------------------------------------------------------------------------- /Sem. 06/Pract.06/Task15.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | constexpr int MAX_SIZE = 100; 5 | 6 | int binarySearch(const int[], int, int, int); 7 | 8 | int main() { 9 | int n; 10 | cin >> n; 11 | int arr[MAX_SIZE]; 12 | 13 | for (int i = 0; i < n; i++) { 14 | cin >> arr[i]; 15 | } 16 | 17 | int result = binarySearch(arr, 0, n - 1, 0); 18 | cout << result << endl; 19 | 20 | return 0; 21 | } 22 | 23 | int binarySearch(const int arr[], int left, int right, int lookupVal) { 24 | while (left < right) { 25 | int mid = left + (right - left) / 2; 26 | 27 | if (arr[mid] == lookupVal) { 28 | return mid; 29 | } 30 | 31 | if (arr[mid] % 2 == 0) { 32 | left = mid + 1; 33 | } else { 34 | right = mid - 1; 35 | } 36 | } 37 | 38 | return -1; 39 | } -------------------------------------------------------------------------------- /Sem. 06/Pract.06/Theory.md: -------------------------------------------------------------------------------- 1 | # Теоретични задачи: 2 | 3 | **Задача 1:** Какво ще изведе програмата? 4 | 5 | ```c++ 6 | #include 7 | 8 | int main() 9 | { 10 | int a = 4; 11 | int b = 12; 12 | 13 | do { 14 | a++; 15 | } while (b = 0); 16 | 17 | int arr[] = { a++, b > a }; 18 | std::cout << (arr[0] <= arr[1]); 19 | 20 | return 0; 21 | } 22 | ``` 23 | 24 | **Задача 2:** Какво прави следният код? 25 | 26 | ```c++ 27 | #include 28 | 29 | bool checkArr(int arr[], int n) 30 | { 31 | for (int i = 0; i < n; i++) 32 | { 33 | if (arr[i] > arr[i + 1]) return false; 34 | } 35 | 36 | return true; 37 | } 38 | 39 | int main() 40 | { 41 | int arr[100] = { 1,4,6,8,9,9 }; 42 | std::cout << checkArr(arr, 6); 43 | return 0; 44 | } 45 | ``` 46 | 47 | **Задача 3:** Какво ще отпечата кодът? 48 | 49 | ```c++ 50 | #include 51 | 52 | int checkEquals(int arr[], int arr1[], int size1, int size2) 53 | { 54 | int size = (size1 < size2) ? size1 : size2; 55 | 56 | int count = 0; 57 | 58 | for (int i = 0; i < size; i++) 59 | { 60 | if (arr[i] == arr1[i]) count++; 61 | } 62 | 63 | return count; 64 | } 65 | 66 | int main() 67 | { 68 | int arr[100] = { 5,12,7,33 }; 69 | int arr1[10]{ 1 }; 70 | 71 | std::cout << checkEquals(arr, arr1, 100, 10); 72 | 73 | return 0; 74 | } 75 | ``` 76 | -------------------------------------------------------------------------------- /Sem. 06/Solutions/BinarySearch.cpp: -------------------------------------------------------------------------------- 1 | int binarySearch(const int* arr, int size, int x) { 2 | int leftIndex = 0, rightIndex = size - 1; 3 | 4 | while (leftIndex <= rightIndex) { 5 | // int midIndex = (leftIndex + rightIndex) / 2; 6 | // why the following is better 7 | int midIndex = leftIndex + (rightIndex - leftIndex) / 2; 8 | 9 | if (arr[midIndex] == x) { 10 | return midIndex; 11 | } 12 | 13 | if (arr[midIndex] < x) { 14 | leftIndex = midIndex + 1; 15 | } 16 | else { 17 | rightIndex = midIndex - 1; 18 | } 19 | } 20 | 21 | return -1; 22 | } 23 | -------------------------------------------------------------------------------- /Sem. 06/Solutions/ExerciseTemplate.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | const unsigned MAX_SIZE = 1024; 4 | 5 | bool isValidLength(unsigned length) { 6 | return 0 < length && length <= MAX_SIZE; 7 | } 8 | 9 | void readArray(int* arr, unsigned length) { 10 | for (unsigned i = 0; i < length; i++) { 11 | std::cin >> arr[i]; 12 | } 13 | } 14 | 15 | void printArray(const int* arr, unsigned length) { 16 | for (unsigned i = 0; i < length; i++) { 17 | std::cout << arr[i] << " "; 18 | } 19 | std::cout << std::endl; 20 | } 21 | 22 | int main() { 23 | int arr[MAX_SIZE]; 24 | 25 | // 1 <= length <= MAX_SIZE 26 | unsigned length; 27 | do { 28 | std::cin >> length; 29 | } while(!isValidLength(length)); 30 | 31 | readArray(arr, length); 32 | 33 | // Do sth 34 | 35 | printArray(arr, length); 36 | } 37 | -------------------------------------------------------------------------------- /Sem. 06/Solutions/LinearSearch.cpp: -------------------------------------------------------------------------------- 1 | bool linearSearch(int* arr, unsigned length, int x) { 2 | for (unsigned i = 0; i < length; i++) { 3 | if (arr[i] == x) { 4 | return true; 5 | } 6 | } 7 | 8 | return false; 9 | } -------------------------------------------------------------------------------- /Sem. 06/Solutions/PrintArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void printArray(int* arr, unsigned length) { 4 | for (unsigned i = 0; i < length; i++) { 5 | std::cout << arr[i] << " "; 6 | } 7 | std::cout << std::endl; 8 | } -------------------------------------------------------------------------------- /Sem. 06/Solutions/ReadArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void readArray(int* arr, unsigned length) { 4 | for (unsigned i = 0; i < length; i++) { 5 | std::cin >> arr[i]; 6 | } 7 | } -------------------------------------------------------------------------------- /Sem. 06/Solutions/ReverseArray.cpp: -------------------------------------------------------------------------------- 1 | void swap(int& a, int& b) { 2 | int temp = a; 3 | a = b; 4 | b = temp; 5 | } 6 | 7 | void reverseArray(int* arr, unsigned length) { 8 | for (int i = 0; i < length / 2; i++) { 9 | swap(arr[i], arr[length - i - 1]); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Sem. 06/Solutions/SelectionSort.cpp: -------------------------------------------------------------------------------- 1 | void selectionSort(int* arr, int size) { 2 | for (int i = 0; i < size; i++) { 3 | int minElementIndex = i; 4 | for (int j = i + 1; j < size; j++) { 5 | if (arr[j] < arr[minElementIndex]) { 6 | minElementIndex = j; 7 | } 8 | } 9 | 10 | if (i != minElementIndex) { 11 | swap(arr, i, minElementIndex); 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Sem. 06/Solutions/ЕratosthenesSieve.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | const unsigned MAX_SIZE = 1001; 4 | 5 | // function that sets a particular value to every element in an array 6 | void initArray(bool* arr, unsigned size, bool value) { 7 | for (unsigned i = 0; i < size; i++) { 8 | arr[i] = value; 9 | } 10 | } 11 | 12 | // Mark all numbers that are like x*startNumber as false (not prime) 13 | // (where x is less than size) 14 | void markAsNotPrime(bool* primes, unsigned size, unsigned startNumber) { 15 | // start from the square because all the numbers that are like 16 | // x*startNumber (where x is less than startNumber) 17 | // have already been marked by the previous invocations of this array 18 | // with smaller numbers 19 | 20 | for(int i = startNumber * startNumber; i < size; i += startNumber) { 21 | primes[i] = false; 22 | } 23 | } 24 | 25 | void calculateEratosthenesSieve(bool* primes, unsigned size) { 26 | // by default we know that 0 and 1 are not prime 27 | primes[0] = primes[1] = false; 28 | 29 | // No need to iterate after square of size 30 | // we will not mark anything after that, look at markAsNotPrime function 31 | int sqrtOfSize = sqrt(size); 32 | 33 | // Every time you find not marked number, it means it is prime 34 | // => mark all numbers where i is there multiple 35 | for (unsigned i = 2; i < sqrtOfSize; i++) { 36 | if (!primes[i]) { // if the number is marked as non prime skip 37 | continue; 38 | } 39 | 40 | markAsNotPrime(primes, size, i); 41 | } 42 | } 43 | 44 | // prints only the numbers that have been left as true 45 | void printSieve(const bool* primes, unsigned size) { 46 | for (unsigned i = 0; i < size; i++) { 47 | if (primes[i]) { 48 | std::cout << i << " "; 49 | } 50 | } 51 | } 52 | 53 | int main() { 54 | // array that holds if a number is prime or not 55 | // the index is equivalent to the number you will check 56 | // if the number(index) is prime -> sieve[index] will be true else false 57 | bool sieve[MAX_SIZE]; 58 | int size; 59 | std::cin >> size; 60 | 61 | // by default we set every number as prime 62 | initArray(sieve, size, true); 63 | calculateEratosthenesSieve(sieve, size); 64 | printSieve(sieve, size); 65 | } 66 | -------------------------------------------------------------------------------- /Sem. 07/Pract.07.2/Task 14.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | constexpr size_t SIZE = 8; 4 | constexpr size_t QUEUE_SIZE = 100; 5 | 6 | bool isValid(int x, int y, int size) 7 | { 8 | return x >= 0 && y >= 0 && x < size && y < size; 9 | } 10 | 11 | int shortestPathBetweenTwoPoints(int board[][SIZE], int startX, int startY, int endX, int endY) 12 | { 13 | int horseMovesX[] = { 2, 2, -2, -2, 1, 1, -1, -1 }; 14 | int horseMovesY[] = { 1, -1, 1, -1, 2, -2, -2, 2 }; 15 | 16 | if (startX == endX && startY == endY) 17 | { 18 | return 0; 19 | } 20 | 21 | int queueX[QUEUE_SIZE], queueY[QUEUE_SIZE]; 22 | int back = 0, front = 0; 23 | 24 | queueX[back] = startX; 25 | queueY[back] = startY; 26 | 27 | back++; 28 | 29 | bool visitedPoints[SIZE][SIZE] = { false }; 30 | visitedPoints[startX][startY] = true; 31 | 32 | while (back >= front) 33 | { 34 | int currentX = queueX[front]; 35 | int currentY = queueY[front]; 36 | 37 | front++; 38 | 39 | for (int i = 0; i < SIZE; i++) 40 | { 41 | int newX = currentX + horseMovesX[i]; 42 | int newY = currentY + horseMovesY[i]; 43 | 44 | if (isValid(newX, newY, SIZE) && !visitedPoints[newX][newY]) 45 | { 46 | board[newX][newY] = board[currentX][currentY] + 1; 47 | 48 | if (newX == endX && newY == endY) 49 | { 50 | return board[newX][newY]; 51 | } 52 | 53 | visitedPoints[newX][newY] = true; 54 | 55 | queueX[back] = newX; 56 | queueY[back] = newY; 57 | 58 | back++; 59 | } 60 | } 61 | } 62 | 63 | return -1; 64 | } 65 | 66 | int main() 67 | { 68 | int startX = 0, startY = 0, endX = 0, endY = 0; 69 | 70 | int board[SIZE][SIZE] = { 0 }; 71 | 72 | std::cin >> startX >> startY >> endX >> endY; 73 | 74 | int shortestPath = shortestPathBetweenTwoPoints(board, startX, startY, endX, endY); 75 | 76 | std::cout << shortestPath << std::endl; 77 | 78 | return 0; 79 | } 80 | -------------------------------------------------------------------------------- /Sem. 07/Pract.07/Task05.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | constexpr int SIZE = 10; 4 | 5 | void spiralPrint(const int arr[][SIZE], int size) { 6 | int direction = 0; // 0 - right, 1 - down, 2 - left, 3 - up 7 | int steps = size; 8 | int offset = 0; 9 | 10 | while(steps > 0) { 11 | switch(direction) { 12 | case 0: 13 | for(int i = 0;i < steps;i++) { 14 | std::cout << arr[offset][i + offset] << ' '; 15 | } 16 | steps--; 17 | break; 18 | case 1: 19 | for(int i = 1;i <= steps;i++) { 20 | std::cout << arr[i + offset][size - offset - 1] << ' '; 21 | } 22 | break; 23 | case 2: 24 | for(int i = steps - 1;i >= 0;i--) { 25 | std::cout << arr[size - offset - 1][i + offset] << ' '; 26 | } 27 | steps--; 28 | break; 29 | case 3: 30 | for(int i = steps;i > 0;i--) { 31 | std::cout << arr[i + offset][offset] << ' '; 32 | } 33 | break; 34 | } 35 | 36 | direction++; 37 | 38 | if(direction > 3) { 39 | offset++; 40 | direction = 0; 41 | } 42 | } 43 | } 44 | 45 | int main() { 46 | int size = 0; 47 | int array[SIZE][SIZE] = {0}; 48 | 49 | do { 50 | std::cout << "Size of matrix: "; 51 | std::cin >> size; 52 | } while(size < 1); 53 | 54 | for(int i = 0;i < size;i++) { 55 | for(int j = 0;j < size;j++) { 56 | std::cin >> array[i][j]; 57 | } 58 | } 59 | 60 | spiralPrint(array, size); 61 | 62 | return 0; 63 | } 64 | -------------------------------------------------------------------------------- /Sem. 07/Pract.07/Task08.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | constexpr int MAX_SIZE = 100; 4 | 5 | int sumOfArrayMembers(int arr[][MAX_SIZE], int n, int m, int s) { 6 | int result = 0; 7 | for (int i = 0;i < n;i++) { 8 | for (int j = 0;j < m;j++) { 9 | result += (i + j == s) ? arr[i][j] : 0; 10 | } 11 | } 12 | return result; 13 | } 14 | 15 | 16 | void readArray(int arr[][MAX_SIZE], int n,int m) { 17 | for (int i = 0;i < n;i++) { 18 | for (int j = 0; j < m;j++) { 19 | std::cin >> arr[i][j]; 20 | } 21 | } 22 | } 23 | 24 | void run() { 25 | int arr[MAX_SIZE][MAX_SIZE]; 26 | 27 | int n,m,s; 28 | std::cin >> n >> m >> s; 29 | 30 | readArray(arr, n, m); 31 | std::cout< 2 | 3 | constexpr int MAX_SIZE = 100; 4 | 5 | bool isItSymetrical(int arr[][MAX_SIZE], int n) { 6 | bool isSymetrical = true; 7 | 8 | for (int i = 0;i < n;i++) { 9 | for (int j = 0;j < n;j++) { 10 | if (arr[i][j] != arr[j][i]) return false; 11 | } 12 | } 13 | 14 | return true; 15 | } 16 | 17 | void readArray(int arr[][MAX_SIZE], int n) { 18 | for (int i = 0;i < n;i++) { 19 | for (int j = 0; j < n;j++) { 20 | std::cin >> arr[i][j]; 21 | } 22 | } 23 | } 24 | 25 | void run() { 26 | int arr[MAX_SIZE][MAX_SIZE]; 27 | int n; 28 | std::cin >> n; 29 | readArray(arr,n); 30 | std::cout< 2 | 3 | constexpr int MAX_SIZE = 100; 4 | 5 | int getTheNumber(int arr1[][MAX_SIZE], int arr2[][MAX_SIZE], int row, int col, int commonDimension) { 6 | int result = 0; 7 | for (int i = 0;i < commonDimension;i++) { 8 | result += arr1[row][i] * arr2[i][col]; 9 | } 10 | return result; 11 | } 12 | 13 | void multipliedArrays(int arrMultiplied[][MAX_SIZE], int arr1[][MAX_SIZE], int arr1_row, int arr1_col, 14 | int arr2[][MAX_SIZE], int arr2_row, int arr2_col) { 15 | for (int i = 0;i < arr1_row;i++) { 16 | for (int j = 0; j < arr2_col;j++) { 17 | arrMultiplied[i][j] = getTheNumber(arr1, arr2, i , j, arr1_col); 18 | } 19 | } 20 | } 21 | 22 | 23 | void sumOfArrays(int arrSum[][MAX_SIZE], int arr1[][MAX_SIZE], int arr2[][MAX_SIZE],int arr1_row,int arr1_col) { 24 | for (int i = 0;i < arr1_row;i++) { 25 | for (int j = 0; j < arr1_col;j++) { 26 | arrSum[i][j] = arr1[i][j] + arr2[i][j]; 27 | } 28 | } 29 | } 30 | 31 | void readArray(int arr[][MAX_SIZE],int arr_row, int arr_col) { 32 | for (int i = 0;i < arr_row;i++) { 33 | 34 | for (int j = 0;j < arr_col;j++) { 35 | 36 | std::cin >> arr[i][j]; 37 | 38 | } 39 | } 40 | } 41 | 42 | void printArray(int arr[][MAX_SIZE], int arr_row, int arr_col) { 43 | for (int i = 0;i < arr_row;i++) { 44 | 45 | for (int j = 0;j < arr_col;j++) { 46 | 47 | std::cout << arr[i][j] << " "; 48 | 49 | } 50 | 51 | std::cout << std::endl; 52 | 53 | } 54 | } 55 | 56 | void run() { 57 | int arr1[MAX_SIZE][MAX_SIZE], arr2[MAX_SIZE][MAX_SIZE]; 58 | 59 | int arr1_row, arr1_col, arr2_row, arr2_col; 60 | 61 | std::cin >> arr1_row >> arr1_col; 62 | readArray(arr1, arr1_row, arr1_col); 63 | 64 | std::cin >> arr2_row >> arr2_col; 65 | readArray(arr2, arr2_row, arr2_col); 66 | 67 | if (arr1_col == arr2_col && arr1_row == arr2_row) { 68 | int arrSum[MAX_SIZE][MAX_SIZE]; 69 | sumOfArrays(arrSum,arr1,arr2,arr1_row,arr1_col); 70 | printArray(arrSum,arr1_row,arr1_col); 71 | std::cout << std::endl; 72 | } 73 | 74 | if (arr1_col == arr2_row) { 75 | int arrMultiplied[MAX_SIZE][MAX_SIZE]; 76 | multipliedArrays(arrMultiplied, arr1, arr1_row, arr1_col, arr2, arr2_row,arr2_col); 77 | printArray(arrMultiplied,arr1_row,arr2_col); 78 | } 79 | } 80 | 81 | int main() 82 | { 83 | run(); 84 | } 85 | -------------------------------------------------------------------------------- /Sem. 07/Pract.07/Task11.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | constexpr int MAX_ROWS = 100; 5 | constexpr int MAX_COLS = 100; 6 | 7 | void enterMatrix(int matrix[][MAX_COLS], int m, int n); 8 | 9 | int getSubmatrixSum(const int matrix[][MAX_COLS], int startRow, int startCol, int endRow, int endCol); 10 | 11 | int maxSubmatrixSum(const int matrix[][MAX_COLS], int m, int n, int p, int q); 12 | 13 | int main() { 14 | int m, n, p, q; 15 | cin >> m >> n >> p >> q; 16 | 17 | int matrix[MAX_ROWS][MAX_COLS]; 18 | enterMatrix(matrix, m, n); 19 | 20 | cout << maxSubmatrixSum(matrix, m, n, p, q) << endl; 21 | } 22 | 23 | void enterMatrix(int matrix[][MAX_COLS], int m, int n) { 24 | for (int i = 0; i < m; i++) { 25 | for (int j = 0; j < n; j++) { 26 | cin >> matrix[i][j]; 27 | } 28 | } 29 | } 30 | 31 | int getSubmatrixSum(const int matrix[][MAX_COLS], int startRow, int startCol, int endRow, int endCol) { 32 | int sum = 0; 33 | 34 | for (int i = startRow; i < endRow; i++) { 35 | for (int j = startCol; j < endCol; j++) { 36 | sum += matrix[i][j]; 37 | } 38 | } 39 | 40 | return sum; 41 | } 42 | 43 | int maxSubmatrixSum(const int matrix[][MAX_COLS], int m, int n, int p, int q) { 44 | int rows = m - p + 1; 45 | int cols = n - q + 1; 46 | 47 | int maxSum = INT_MIN; 48 | for (int i = 0; i < rows; i++) { 49 | for (int j = 0; j < cols; j++) { 50 | int sum = getSubmatrixSum(matrix, i, j, i + p, j + q); 51 | 52 | if (sum > maxSum) { 53 | maxSum = sum; 54 | } 55 | } 56 | } 57 | 58 | return maxSum; 59 | } 60 | -------------------------------------------------------------------------------- /Sem. 07/Pract.07/Task12.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | constexpr int MAX_ROWS = 100; 5 | constexpr int COLS = 2; 6 | 7 | void enterMatrix(int matrix[][COLS], int n); 8 | 9 | void swapMatrixElements(int matrix[][COLS], int row, int col, int row1, int col1); 10 | 11 | void sortMatrixByRows(int matrix[][COLS], int n); 12 | 13 | void printMatrix(const int matrix[][COLS], int n); 14 | 15 | int main() { 16 | int matrix[MAX_ROWS][COLS]; 17 | int n; 18 | cin >> n; 19 | 20 | enterMatrix(matrix, n); 21 | 22 | sortMatrixByRows(matrix, n); 23 | 24 | printMatrix(matrix, n); 25 | } 26 | 27 | void enterMatrix(int matrix[][COLS], int n) { 28 | for (int i = 0; i < n; i++) { 29 | for (int j = 0; j < COLS; j++) { 30 | cin >> matrix[i][j]; 31 | } 32 | } 33 | } 34 | 35 | void swapMatrixElements(int matrix[][COLS], int row, int col, int row1, int col1) { 36 | int temp = matrix[row][col]; 37 | matrix[row][col] = matrix[row1][col1]; 38 | matrix[row1][col1] = temp; 39 | } 40 | 41 | void sortMatrixByRows(int matrix[][COLS], int n) { 42 | for (int i = 0; i < n - 1; i++) { 43 | int minIndex = i; 44 | 45 | for (int j = i + 1; j < n; j++) { 46 | if (matrix[j][0] < matrix[minIndex][0]) { 47 | minIndex = j; 48 | } else if ((matrix[j][0] == matrix[minIndex][0]) && matrix[j][1] < matrix[minIndex][1]) { 49 | minIndex = j; 50 | } 51 | } 52 | 53 | if (i != minIndex) { 54 | swapMatrixElements(matrix, i, 0, minIndex, 0); 55 | swapMatrixElements(matrix, i, 1, minIndex, 1); 56 | } 57 | } 58 | } 59 | 60 | void printMatrix(const int matrix[][COLS], int n) { 61 | for (int i = 0; i < n; i++) { 62 | for (int j = 0; j < COLS; j++) { 63 | cout << matrix[i][j] << " "; 64 | } 65 | 66 | cout << endl; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /Sem. 07/Pract.07/Task13.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | constexpr size_t SIZE = 100; 4 | constexpr char SPECIAL_SYMBOL = '^'; 5 | 6 | size_t getAbs(int n) 7 | { 8 | return n >= 0 ? n : -n; 9 | } 10 | 11 | double getArea(int x1, int y1, int x2, int y2, int x3, int y3) 12 | { 13 | return getAbs(x1 * y2 + x2 * y3 + x3 * y1 - y1 * x2 - y2 * x3 - y3 * x1) / 2.00; 14 | } 15 | 16 | void fillCoordinates(int coordinatesX[], int coordinatesY[], size_t& symbolsCounter, size_t N, size_t M) 17 | { 18 | for (int i = 0; i < N; i++) 19 | { 20 | for (int j = 0; j < M; j++) 21 | { 22 | char symbol; 23 | std::cin >> symbol; 24 | 25 | if (symbol == SPECIAL_SYMBOL) 26 | { 27 | coordinatesX[symbolsCounter] = i; 28 | coordinatesY[symbolsCounter] = j; 29 | 30 | symbolsCounter++; 31 | } 32 | } 33 | } 34 | } 35 | 36 | size_t countTriangles(const int coordinatesX[], const int coordinatesY[], size_t symbolsCounter) 37 | { 38 | size_t counter = 0; 39 | 40 | for (size_t i = 0; i < symbolsCounter; i++) 41 | { 42 | int x1 = coordinatesX[i]; 43 | int y1 = coordinatesY[i]; 44 | 45 | for (size_t j = i + 1; j < symbolsCounter; j++) 46 | { 47 | int x2 = coordinatesX[j]; 48 | int y2 = coordinatesY[j]; 49 | 50 | for (size_t s = j + 1; s < symbolsCounter; s++) 51 | { 52 | int x3 = coordinatesX[s]; 53 | int y3 = coordinatesY[s]; 54 | 55 | if (getArea(x1, y1, x2, y2, x3, y3) != 0) 56 | { 57 | counter++; 58 | } 59 | 60 | } 61 | } 62 | } 63 | 64 | return counter; 65 | } 66 | 67 | void run() 68 | { 69 | size_t N, M; 70 | std::cin >> N >> M; 71 | 72 | size_t symbolsCounter = 0; 73 | 74 | int coordinatesX[SIZE]; 75 | int coordinatesY[SIZE]; 76 | 77 | fillCoordinates(coordinatesX, coordinatesY, symbolsCounter, N, M); 78 | 79 | std::cout << countTriangles(coordinatesX, coordinatesY, symbolsCounter) << std::endl; 80 | } 81 | 82 | int main() 83 | { 84 | run(); 85 | 86 | return 0; 87 | } 88 | -------------------------------------------------------------------------------- /Sem. 07/README.md: -------------------------------------------------------------------------------- 1 | # Многомерни масиви 2 | 3 | ## Двумерни масиви. 4 | 5 | ```c++ 6 | int matrix1[3][4]; // създава се матрица с 3 реда и 4 колони 7 | 8 | int arr[3][4] = { { 1, 2, 3, 4 }, { 9, 8, 7, 6 }, { 11, 12, 13, 14 } }; // изреждаме редовете 9 | 10 | int matrix3[3][4] = { 1, 2, 3, 4, 9, 8, 7, 6, 11, 12, 13, 14 }; // изреждаме елементите 11 | 12 | int matrix4[][4] = { 1, 2, 3, 4, 9, 8, 7, 6, 11, 12, 13, 14 }; // можем да изпуснем най-лявата спецификация на дължина 13 | 14 | ``` 15 | В паметта: 16 | 17 | ![enter image description here](https://i.ibb.co/XbMWhW8/im.png) 18 | 19 | Как да си го представяме и как го използваме: 20 | ![2d=array](https://media.geeksforgeeks.org/wp-content/uploads/two-d.png) 21 | 22 | ### Достъп до елемент. 23 | 24 | ```c++ 25 | int* row = arr[1]; //ред 1 (масивът на индекс 1) 26 | std::cout << arr[2][0]<< std::endl //11; 27 | std::cout << row[2]<< std::endl //7; 28 | ``` 29 | 30 | ### Примери с n-мерни масиви. 31 | 32 | ```c++ 33 | int cube[3][3][3]; // създава се тримерен масив 34 | ``` 35 | ### Достъп до елемент. 36 | 37 | ```c++ 38 | cube[2] // двумерен масив; 39 | cube[2][1] // едномерен масив; 40 | cube[2][1][4] // конкретен елемент; 41 | 42 | ``` 43 | 44 | 45 | ![3d=array](https://media.geeksforgeeks.org/wp-content/uploads/3D-array.jpg) 46 | 47 | 48 | ## Примери: 49 | * умножение на матрица по скалар 50 | * Събиране на 2 матрици 51 | * транспониране на матрица 52 | 53 | ## Малък проект - Тic-Tac-Toe 54 | Да се реализира в конзолна играта Тic-Tac-Toe(морски шах). 55 | Играта започва с празна дъска, като на всяка стъпка: 56 | 57 | * единият играч въвежда две числа - ред и колона, които са неговия ход на дъската(Например: 0 2). 58 | * след всеки ход се актуализира конкретното състояние на играта. 59 | 60 | Играта приключва, ако единият играч победи или всички полета са запълнени 61 | 62 | ## Бонус задачи 63 | 64 | * Рефакторирайте Тic-Tac-Toe така, че да може да се играе с дължина n (3 <= n <= 50) на квадратната матрица и с брой играчи x (2 <= x <= 50) 65 | 66 | * Напишете функция, която приема матрица NxN+1 и решава системата от линейни уравнения (с ненулеви коефициенти), репрезентирана в матрицата. 67 | -------------------------------------------------------------------------------- /Sem. 07/Solutions/Task09.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | constexpr unsigned MAX_SIZE = 10; 4 | 5 | // Read/Write methods 6 | bool validateInput(size_t &rows, size_t &cols); 7 | void readMatrix(int mtx[][MAX_SIZE], size_t rows, size_t cols); 8 | void printMatrix(const int mtx[][MAX_SIZE], size_t rows, size_t cols); 9 | 10 | // Matrix operations 11 | bool isMatrixSymmetrical(const int mtx[][MAX_SIZE], size_t rows, size_t cols); 12 | 13 | 14 | int main() 15 | { 16 | int mtx[MAX_SIZE][MAX_SIZE]; 17 | 18 | size_t rows, cols; 19 | if (!validateInput(rows, cols)) 20 | return -1; 21 | std::cout << "Enter matrix one: \n"; 22 | readMatrix(mtx, rows, cols); 23 | 24 | std::cout << "Matrix is symmetrical: " << std::boolalpha << isMatrixSymmetrical(mtx, rows, cols) << "\n"; 25 | } 26 | 27 | bool validateInput(size_t &rows, size_t &cols) { 28 | std::cout << "Enter valid dimensions of matrix: "; 29 | std::cin >> rows >> cols; 30 | 31 | if (rows > MAX_SIZE || rows < 0 || cols >MAX_SIZE || cols < 0) 32 | return false; 33 | 34 | return true; 35 | } 36 | 37 | void readMatrix(int mtx[][MAX_SIZE], size_t rows, size_t cols) { 38 | for (size_t i = 0; i < rows; i++) 39 | for (size_t j = 0; j < cols; j++) 40 | std::cin >> mtx[i][j]; 41 | } 42 | 43 | bool isMatrixSymmetrical(const int mtx[][MAX_SIZE], size_t rows, size_t cols) { 44 | // only square matrixes can be symmetrical 45 | if (rows != cols) 46 | return false; 47 | 48 | for (size_t i = 0; i < rows; i++) 49 | for (size_t j = i + 1; j < cols; j++) 50 | if (mtx[i][j] != mtx[j][i]) 51 | return false; 52 | 53 | return true; 54 | } 55 | -------------------------------------------------------------------------------- /Sem. 08/Pract.09/NumberSystems.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void mySwap(char& first, char& second) 4 | { 5 | char temp = first; 6 | first = second; 7 | second = temp; 8 | } 9 | 10 | void reverseArray(char* array, unsigned length) 11 | { 12 | for (unsigned i = 0; i < length / 2; i++) { 13 | mySwap(array[i], array[length - i - 1]); 14 | } 15 | } 16 | 17 | int charToDigit(char ch) 18 | { 19 | 20 | if (ch >= '0' && ch <= '9') { 21 | return ch - '0'; 22 | } 23 | else if (ch >= 'A' && ch <= 'Z') { 24 | return 10 + ch - 'A'; 25 | } 26 | 27 | return 0; 28 | } 29 | 30 | char digitToChar(unsigned digit) 31 | { 32 | if (digit >= 0 && digit <= 9) { 33 | return digit + '0'; 34 | } 35 | else if (digit >= 10 && digit <= 26) { 36 | return digit - 10 + 'A'; 37 | } 38 | 39 | return 0; 40 | } 41 | 42 | void decimalToRandom(unsigned decimal, unsigned short base, char* result, unsigned short& resultLength) 43 | { 44 | resultLength = 0; 45 | while (decimal != 0) { 46 | unsigned lastDigit = decimal % base; 47 | result[resultLength++] = digitToChar(lastDigit); 48 | decimal /= base; 49 | } 50 | 51 | reverseArray(result, resultLength); 52 | } 53 | 54 | unsigned randomToDecimal(const char* source, unsigned short base, unsigned short& sourceLength) 55 | { 56 | unsigned result = 0; 57 | unsigned multiplier = 1; 58 | for (int i = sourceLength - 1; i >= 0; i--) { 59 | result += charToDigit(source[i]) * multiplier; 60 | multiplier *= base; 61 | } 62 | 63 | return result; 64 | } 65 | 66 | void printArray(const char* array, unsigned short length) 67 | { 68 | for (unsigned i = 0; i < length; i++) { 69 | std::cout << array[i]; 70 | } 71 | } 72 | 73 | unsigned short readBase(bool isSource) 74 | { 75 | unsigned short base; 76 | 77 | do 78 | { 79 | std::cout << "Enter number base [2, 36] for " << (isSource ? "source":"result") << ": "; 80 | std::cin >> base; 81 | } while (base < 2 || base > 36); // retry 82 | 83 | return base; 84 | } 85 | 86 | // Open to improvements 87 | bool isInPossibleChars(char ch, unsigned short base) 88 | { 89 | char possibleCharacter[36] = "0123456789ABCDEFGHIJKLMNOPQRSTUVXYZ"; 90 | for (size_t i = 0; i < base; i++) 91 | if (ch == possibleCharacter[i]) 92 | return true; 93 | 94 | return false; 95 | } 96 | 97 | void readNumber(char *number, unsigned short &numberLength, unsigned short base) 98 | { 99 | std::cout << "Enter source number [positive integer less than 16 symbols in length]: "; 100 | std::cin >> number; 101 | 102 | // validation 103 | for (size_t i = 0; number[i] != '\0'; i++, numberLength++) { 104 | if (!isInPossibleChars(number[i], base)) { 105 | std::cout << "Invalid number\n"; 106 | numberLength = 0; 107 | return readNumber(number, numberLength, base); // retry 108 | } 109 | } 110 | } 111 | 112 | int main() { 113 | 114 | unsigned short sourceBase = readBase(1); 115 | char source[16]; 116 | unsigned short sourceLength = 0; 117 | readNumber(source, sourceLength, sourceBase); 118 | 119 | unsigned short resultBase = readBase(0); 120 | char result[64]; 121 | unsigned short resultLength = 0; 122 | 123 | unsigned decimal = randomToDecimal(source, sourceBase, sourceLength); 124 | 125 | std::cout << "\nsource -> decimal -> result\n"; 126 | decimalToRandom(decimal, resultBase, result, resultLength); 127 | printArray(source, sourceLength); 128 | std::cout << " -> " << decimal << " -> "; 129 | printArray(result, resultLength); 130 | } -------------------------------------------------------------------------------- /Sem. 08/Pract.09/Subsets.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void printSubset(const int* arr, unsigned length, unsigned mask) { 4 | std::cout << "{ "; 5 | for (unsigned i = 0; i < length; i++) { 6 | // if the i-th bit of the mask is 1 7 | // then the i-th element of the array is in the subset 8 | if (mask & 1) { 9 | std::cout << arr[i] << " "; 10 | } 11 | // /= 2 12 | mask >>= 1; 13 | } 14 | std::cout << "}" << std::endl; 15 | } 16 | 17 | void printSubsets(const int* arr, unsigned length) { 18 | // every set has 2^N subsets 19 | unsigned subsetsCount = 1 << length; 20 | // every number from 0 to 2^N is a mask of a subset 21 | // because every number has a different binary representation 22 | for (unsigned i = 0; i < subsetsCount; i++) { 23 | printSubset(arr, length, i); 24 | } 25 | } 26 | 27 | int main() { 28 | const unsigned LENGTH = 5; 29 | int arr[LENGTH] = { 1, 2, 3, 4, 5 }; 30 | 31 | printSubsets(arr, LENGTH); 32 | } -------------------------------------------------------------------------------- /Sem. 08/Pract.09/Task07.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | unsigned flipRightmostSetBit(unsigned num) { 4 | return num & (num - 1); 5 | } 6 | 7 | int main() 8 | { 9 | unsigned n; 10 | std::cin >> n; 11 | std::cout << flipRightmostSetBit(n); 12 | } 13 | -------------------------------------------------------------------------------- /Sem. 08/Pract.09/Task08.cpp: -------------------------------------------------------------------------------- 1 | #include ; 2 | 3 | unsigned powerOfTwo(unsigned power) 4 | { 5 | if (power > 31) 6 | return 0; 7 | 8 | return 1 << power; 9 | } 10 | 11 | unsigned getNumFromBits(unsigned number, unsigned startIndex, unsigned length) 12 | { 13 | // shift само ако има смисъл, cast защото иначе unsigned overflows 14 | if (startIndex > length) 15 | number = number >> startIndex - length + 1; 16 | // намали дължината така че да вземе само останалите цифри 17 | else 18 | length = startIndex; 19 | 20 | // степен на двойката 2^k 0001 0000, k = 4 21 | // вадим 1 -> 0000 1111 22 | unsigned mask = powerOfTwo(length) - 1; // 0000 1111 23 | 24 | // побитово & 25 | // 1011 1001 26 | // 0000 1111 27 | return number & mask; 28 | } 29 | 30 | int main() 31 | { 32 | unsigned x, m, n; 33 | std::cin >> x >> m >> n; 34 | std::cout << getNumFromBits(x, m, n); 35 | } 36 | -------------------------------------------------------------------------------- /Sem. 08/Solutions/2To10AndReversed.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | const unsigned MAX_SIZE = 1024; 4 | 5 | void mySwap(char& first, char& second) { 6 | char temp = first; 7 | first = second; 8 | second = temp; 9 | } 10 | 11 | int charToDigit(char a) { 12 | if (a < '0' || a > '9') { 13 | return 0; 14 | } 15 | 16 | return a - '0'; 17 | } 18 | 19 | char digitToChar(unsigned digit){ 20 | if (digit > 9) { 21 | return 0; 22 | } 23 | 24 | return digit + '0'; 25 | } 26 | 27 | void reverseArray(char* arr, unsigned length) { 28 | for (unsigned i = 0; i < length / 2; i++) { 29 | mySwap(arr[i], arr[length - i - 1]); 30 | } 31 | } 32 | 33 | void decimalToBinary(unsigned decimal, char result[], unsigned& resultLength) { 34 | resultLength = 0; 35 | while (decimal != 0) { 36 | unsigned lastDigit = decimal % 2; 37 | result[resultLength++] = digitToChar(lastDigit); 38 | decimal /= 2; 39 | } 40 | 41 | reverseArray(result, resultLength); 42 | } 43 | 44 | unsigned binaryToDecimal(const char source[], unsigned& length) { 45 | unsigned result = 0; 46 | int multiplier = 1; 47 | for (int i = length - 1; i >= 0; i--) { 48 | result += charToDigit(source[i]) * multiplier; 49 | multiplier *= 2; 50 | } 51 | 52 | return result; 53 | } 54 | 55 | void printArr(const char* result, unsigned length) { 56 | for (unsigned i = 0; i < length; i++) { 57 | std::cout << result[i]; 58 | } 59 | std::cout << std::endl; 60 | } 61 | 62 | 63 | int main() { 64 | 65 | unsigned decimalNumber = 125; 66 | char binaryNumber[MAX_SIZE]; 67 | unsigned binaryNumberLength = 0; 68 | decimalToBinary(decimalNumber, binaryNumber, binaryNumberLength); 69 | 70 | printArr(binaryNumber, binaryNumberLength); 71 | 72 | unsigned afterConversionDecimal = binaryToDecimal(binaryNumber, binaryNumberLength); 73 | std::cout << afterConversionDecimal; 74 | } 75 | -------------------------------------------------------------------------------- /Sem. 08/Solutions/AnyBaseToAnyBaseConverter.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | const unsigned MAX_SIZE = 1024; 4 | 5 | void mySwap(char& first, char& second) { 6 | unsigned temp = first; 7 | first = second; 8 | second = temp; 9 | } 10 | 11 | void reverseArray(char* arr, unsigned length) { 12 | for (unsigned i = 0; i < length / 2; i++) { 13 | mySwap(arr[i], arr[length - i - 1]); 14 | } 15 | } 16 | 17 | char decimalToChar(unsigned number) { 18 | if (0 <= number && number <= 9) { 19 | return number + '0'; 20 | } 21 | if (10 <= number && number <= 36) { 22 | return (number - 10) + 'A'; 23 | } 24 | 25 | return 0; 26 | } 27 | 28 | unsigned charToDecimal(char ch) { 29 | if ('0' <= ch && ch <= '9') { 30 | return ch - '0'; 31 | } 32 | if ('A' <= ch && ch <= 'Z') { 33 | return ch - 'A' + 10; 34 | } 35 | 36 | return 0; 37 | } 38 | 39 | void fromDecimalToAnyBase(unsigned decimal, char* result, unsigned& resultLength, unsigned toBase) { 40 | resultLength = 0; 41 | while (decimal != 0) { 42 | unsigned lastDigit = decimal % toBase; 43 | result[resultLength++] = decimalToChar(lastDigit); 44 | decimal /= toBase; 45 | } 46 | 47 | reverseArray(result, resultLength); 48 | } 49 | 50 | unsigned fromAnyBaseToDecimal(const char* numberArr, unsigned& numberLength, unsigned fromBase) { 51 | unsigned result = 0; 52 | for ( 53 | int i = numberLength - 1, multiplier = 1; 54 | i >= 0; 55 | i--, multiplier *= fromBase 56 | ) { 57 | result += charToDecimal(numberArr[i]) * multiplier; 58 | } 59 | 60 | return result; 61 | } 62 | 63 | void fromAnyBaseToAnyBase( 64 | const char* fromNumber, 65 | unsigned fromNumberLength, 66 | char* toNumber, 67 | unsigned& toNumberLength, 68 | unsigned fromBase, 69 | unsigned toBase 70 | ) { 71 | unsigned decimal = fromAnyBaseToDecimal(fromNumber, fromNumberLength, fromBase); 72 | fromDecimalToAnyBase(decimal, toNumber, toNumberLength, toBase); 73 | } 74 | 75 | void printArr(const char* result, unsigned length) { 76 | for (unsigned i = 0; i < length; i++) { 77 | std::cout << result[i]; 78 | } 79 | std::cout << std::endl; 80 | } 81 | 82 | int main() { 83 | { 84 | unsigned decimalNumber = 101; 85 | char number[MAX_SIZE] = {}; 86 | unsigned numberLength = 0; 87 | fromDecimalToAnyBase(decimalNumber, number, numberLength, 2); 88 | 89 | printArr(number, numberLength); 90 | 91 | unsigned afterConversionDecimal = fromAnyBaseToDecimal(number, numberLength, 2); 92 | std::cout << afterConversionDecimal << std::endl; 93 | } 94 | { 95 | unsigned decimalNumber = 101; 96 | char number[MAX_SIZE] = {}; 97 | unsigned numberLength = 0; 98 | fromDecimalToAnyBase(decimalNumber, number, numberLength, 16); 99 | 100 | printArr(number, numberLength); 101 | 102 | unsigned afterConversionDecimal = fromAnyBaseToDecimal(number, numberLength, 16); 103 | std::cout << afterConversionDecimal << std::endl; 104 | } 105 | 106 | { 107 | unsigned numberLength = 2; 108 | char number[MAX_SIZE] = { 'F', 'E', '\0'}; 109 | 110 | char result[MAX_SIZE]; 111 | unsigned resultLength = 0; 112 | 113 | fromAnyBaseToAnyBase(number, numberLength, result, resultLength, 16, 2); 114 | 115 | printArr(result, resultLength); 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /Sem. 08/Solutions/BitManipulation.cpp: -------------------------------------------------------------------------------- 1 | bool checkBitValue(unsigned number, unsigned index) { 2 | unsigned int mask = 1; 3 | // 0000100000 4 | mask <<= index; 5 | 6 | // with equal to mask => the number is one => true 7 | // else it was zero 8 | // 0000100000 9 | // 1110100001 10 | // & 11 | // 0000100000 12 | return (mask & number) == mask; 13 | } 14 | 15 | unsigned setBitZero(unsigned int number, unsigned int index) { 16 | unsigned int mask = 1; 17 | // 0000100000 18 | mask <<= index; 19 | // 1111011111 20 | mask = ~mask; // everywhere one apart from the index where you want to set 0 21 | 22 | // 0000100010 23 | // 1111011111 24 | // & 25 | // 0000000010 26 | return number & mask; 27 | } 28 | 29 | unsigned setBitToOne(unsigned number, unsigned index) { 30 | unsigned int mask = 1; 31 | // 0000100000 32 | mask <<= index; // everywhere zero apart from the index where you want to set 1 33 | 34 | // 0000100000 35 | // 1110000111 36 | // | 37 | // 1110100111 38 | return number | mask; 39 | } 40 | 41 | unsigned setBitValue(unsigned number, unsigned index, bool value) { 42 | return value 43 | ? setBitToOne(number, index) 44 | : setBitZero(number, index); 45 | } 46 | 47 | unsigned toggleBit(unsigned number, unsigned index) { 48 | unsigned int mask = 1; 49 | // 0000100000 50 | mask <<= index; // everywhere zero apart from the index where you want to toggle 51 | 52 | // 0000100000 53 | // 1110000111 54 | // ^ 55 | // 1110100111 56 | // if it was zero => 0 ^ 1 => 1 57 | // if it was one => 1 ^ 1 => 0 58 | return number ^ mask; 59 | } -------------------------------------------------------------------------------- /Sem. 08/Solutions/BitwisePow.cpp: -------------------------------------------------------------------------------- 1 | unsigned powerOfTwo(unsigned power) { 2 | // 2^31 is the maximum power of two that can be represented as an unsigned int 3 | if(power > 31) { 4 | return 0; 5 | } 6 | 7 | // 1 << n is equivalent to 2^n 8 | return 1 << power; 9 | } -------------------------------------------------------------------------------- /Sem. 08/Solutions/FirstNotDuplicated.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int findNotDuplicated(const int* arr, unsigned length) { 4 | int result = 0; 5 | // XOR of a number with itself is 0 6 | // XOR of a number with 0 is the number itself 7 | // Every number has different binary representation 8 | // So the XOR of all numbers in the array will be the number that is not duplicated 9 | for (unsigned i = 0; i < length; i++) { 10 | result ^= arr[i]; 11 | } 12 | 13 | return result; 14 | } 15 | 16 | int main() { 17 | const unsigned LENGTH = 7; 18 | // Every number in the array is duplicated except one 19 | int arr1[] = { 5, 1, 5, 6, 1, 7, 6 }; 20 | int arr2[] = { 5, 5, 5, 5, 1, 5, 5 }; 21 | 22 | std::cout << findNotDuplicated(arr1, 7); 23 | // Will this work? Why? 24 | // std::cout << findNotDuplicated(arr2, 7); 25 | } -------------------------------------------------------------------------------- /Sem. 08/Solutions/IsEven.cpp: -------------------------------------------------------------------------------- 1 | bool isEven(int number) { 2 | int mask = 1; 3 | // check if the last bit is a 1 to see if it is odd 4 | // !isOdd => isEven 5 | return !(number & mask); 6 | } -------------------------------------------------------------------------------- /Sem. 08/Solutions/IsPowerOfTwo.cpp: -------------------------------------------------------------------------------- 1 | bool isPowerOfTwo(unsigned number) { 2 | if (number == 0) { 3 | return false; 4 | } 5 | 6 | int mask = number - 1; // 16 (10000) - 1 = 15 (01111) 7 | 8 | // 10000 & 01111 = 0 => powerOfTwo 9 | return (number & mask) == 0; 10 | } -------------------------------------------------------------------------------- /Sem. 09/Pract.10/Task01.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | constexpr int MAX_SIZE = 1024; 4 | 5 | unsigned int myStrLen(const char* str); 6 | void myStrCpy(char* dest, const char* src); 7 | void myStrCat(char* first, const char* second); 8 | 9 | void findMatch(const char* arr, char* updatedArray, const char* searched, const char* replacing); 10 | bool isPrefix(const char* searched, const char*& text); 11 | void replace(const char* replacing, char*& updatedArray); 12 | 13 | int main() 14 | { 15 | char str[MAX_SIZE + 1] = "i am the best of the best!"; 16 | 17 | char updatedArray[MAX_SIZE + 1]{ '\0' }; 18 | updatedArray[MAX_SIZE] = '\0'; 19 | 20 | findMatch(str, updatedArray, "best", "worst"); 21 | 22 | std::cout << updatedArray << std::endl; 23 | 24 | return 0; 25 | } 26 | 27 | unsigned int myStrLen(const char* str) 28 | { 29 | if (!str) return 0; 30 | 31 | unsigned int result = 0; 32 | while (*str++ && ++result); 33 | return result; 34 | } 35 | 36 | void myStrCpy(char* dest, const char* src) 37 | { 38 | if (!dest || !src) return; 39 | 40 | while (*dest++ = *src++); 41 | } 42 | 43 | void myStrCat(char* first, const char* second) 44 | { 45 | if (!first || !second) return; 46 | 47 | first += myStrLen(first); 48 | myStrCpy(first, second); 49 | } 50 | 51 | bool isPrefix(const char* searched, const char*& text) 52 | { 53 | if (!searched || !text) return false; 54 | 55 | while (*searched) 56 | { 57 | if (*searched != *text) 58 | { 59 | return false; 60 | } 61 | 62 | searched++; 63 | text++; 64 | } 65 | 66 | return true; 67 | } 68 | 69 | void replace(const char* replacing, char*& updatedArray) 70 | { 71 | if (!replacing || !updatedArray) return; 72 | 73 | myStrCat(updatedArray, replacing); 74 | 75 | updatedArray += myStrLen(replacing); 76 | } 77 | 78 | void findMatch(const char* arr, char* updatedArray, const char* searched, const char* replacing) 79 | { 80 | if (!arr || !updatedArray || !searched || !replacing) return; 81 | 82 | while (*arr) 83 | { 84 | if (*arr == *searched) 85 | { 86 | if (isPrefix(searched, arr)) 87 | { 88 | replace(replacing, updatedArray); 89 | continue; 90 | } 91 | } 92 | else 93 | { 94 | *updatedArray = *arr; 95 | } 96 | 97 | updatedArray++; 98 | arr++; 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /Sem. 09/Pract.10/Task02.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | constexpr int DIFFERENCE = ('a' - 'A'); 4 | 5 | bool isLower(char letter) { 6 | return (letter >= 'a' && letter <= 'z'); 7 | } 8 | 9 | bool isUpper(char letter) { 10 | return (letter >= 'A' && letter <= 'Z'); 11 | } 12 | 13 | void convertString(char *str) { 14 | if (!str) return; 15 | 16 | while(*str != '\0') { 17 | if(isLower(*str)) { 18 | (*str) -= DIFFERENCE; 19 | } else if(isUpper(*str)) { 20 | (*str) += DIFFERENCE; 21 | } 22 | 23 | str++; 24 | } 25 | } 26 | 27 | 28 | int main() { 29 | char str[] = "HeLlo WORLD!"; 30 | 31 | convertString(str); 32 | 33 | std::cout << str; 34 | 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /Sem. 09/Pract.10/Task12.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | const int UPPER_TO_LOWER_DIFF = 'a'-'A'; 5 | 6 | void convertString(char* str){ 7 | if(!str) return ; 8 | 9 | while(*str){ 10 | if(*str >= 'a' && *str <= 'z') *str = *str - UPPER_TO_LOWER_DIFF; 11 | else if(*str >='A' && *str <= 'Z') *str = *str + UPPER_TO_LOWER_DIFF; 12 | str++; 13 | } 14 | } 15 | int main(){ 16 | char str[]="abcd56ABCD"; 17 | convertString(str); 18 | cout< 2 | using namespace std; 3 | constexpr int MAX=1024; 4 | int len(const char * text){ 5 | int len=0; 6 | while(*text){ 7 | len++; 8 | text++; 9 | } return len; 10 | } 11 | void insertSymbol( const char* text, char* result, char symbol, unsigned int index){ 12 | unsigned int currentIndex=0; 13 | if(!text || !result) return; 14 | int lengthText=len(text); 15 | if((lengthText - 1)> symbol>> index; 35 | char result[MAX]{'\0'}; 36 | insertSymbol(text, result, symbol, index ); 37 | cout< 2 | using namespace std; 3 | constexpr int MAX=100000; 4 | char digitToChar(int digit){ 5 | char a = '\0'; 6 | if(digit>=0 && digit<=9){ 7 | a = digit + '0'; 8 | } 9 | return a; 10 | } 11 | 12 | int charToDigit(char a){ 13 | int n = 0; 14 | if(a >= '0' && a<= '9') { 15 | n = a - '0'; 16 | } 17 | return n; 18 | } 19 | 20 | void getDigitOccurences (const char* digit, char* result){ 21 | if(!digit || !result) return; 22 | 23 | int counter[10]={0}; 24 | for (const char* ptr = digit; *ptr; ptr++){ 25 | if(*ptr>='0'&& *ptr<='9'){ 26 | counter[charToDigit(*ptr)]++; 27 | } 28 | } 29 | 30 | for(int i=0; i<10; i++){ 31 | if(counter[i]>0){ 32 | int count=counter[i]; 33 | if(count>=10){ 34 | *result=digitToChar(count/10); 35 | result++; 36 | } 37 | *result=digitToChar(count%10); 38 | result++; 39 | *result= 'x'; 40 | result++; 41 | *result= digitToChar(i); 42 | result++; 43 | *result=','; 44 | result++; 45 | } 46 | 47 | } 48 | *(result-1)='\0'; 49 | } 50 | 51 | int main(){ 52 | const char* digits="123458432345434"; 53 | char result[MAX]{'\0'}; 54 | getDigitOccurences(digits, result); 55 | cout< 2 | using namespace std; 3 | constexpr int MAX=1000; 4 | bool isLowerCaseLetter(char c){ 5 | return(c >='a' && c <= 'z'); 6 | } 7 | bool isUpperCaseLetter(char c){ 8 | return (c >= 'A' && c<='Z'); 9 | } 10 | bool isSeparator(char c){ 11 | return !(isUpperCaseLetter(c) || isLowerCaseLetter(c)); 12 | } 13 | unsigned int getWordsCount(const char* words){ 14 | if(!words) return 0; 15 | unsigned int counter=0; 16 | bool inWord=0; 17 | for(const char* ptr=words; *ptr; ptr++){ 18 | if(isSeparator(*ptr)){ 19 | if(inWord) { 20 | counter++; 21 | inWord=false; 22 | } 23 | } 24 | else inWord=true; 25 | } 26 | if(inWord) counter++; 27 | return counter; 28 | } 29 | 30 | int main(){ 31 | char str[MAX]={'\0'}; 32 | cin.getline(str,MAX); 33 | cout<< getWordsCount(str); 34 | } 35 | -------------------------------------------------------------------------------- /Sem. 09/Pract.10/Task16.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | constexpr int MAX=1000; 4 | void swap(int & ptr1, int &ptr2){ 5 | int temp=ptr1; 6 | ptr1=ptr2; 7 | ptr2=temp; 8 | 9 | } 10 | void copyArr(const char* str, char* result){ 11 | while(*str){ 12 | if(*str >= 'A' && *str <= 'Z'){ 13 | *result = *str + 32; 14 | result++; 15 | } 16 | else if(*str >= 'a' && *str <= 'z'){ 17 | *result = *str; 18 | result++; 19 | } 20 | str++; 21 | } *result = '\0'; 22 | } 23 | 24 | void sortCharacters(const char* str, char* result){ 25 | if(!str || *result) return; 26 | copyArr(str, result); 27 | 28 | for(char *ptr = result; *ptr; ptr++){ 29 | char *min = ptr; 30 | for(char *jtr= (ptr+1); *jtr; jtr++){ 31 | if(*min > *jtr) min=jtr; 32 | } 33 | if(*min != *ptr) swap(*min,*ptr); 34 | } 35 | } 36 | int main(){ 37 | const char* str="Hello World!"; 38 | char result[MAX]{'\0'}; 39 | sortCharacters(str,result); 40 | cout< 2 | using namespace std; 3 | constexpr int MAX_STR=10000; 4 | constexpr int MAX_WORDS=100; 5 | constexpr int MAX_SYMBOLS_WORDS=1024; 6 | 7 | const char NULL_TERMINATOR = '\0'; 8 | 9 | bool isSpaceOrPunctuation(char a){ 10 | return (a>=32 && a<=47 || a>=58 && a<=64 || a>=91 && a<=96 || a>=123 && a<=126); 11 | } 12 | 13 | void strToMatrix(char *str, char matrix[MAX_WORDS][MAX_SYMBOLS_WORDS]){ 14 | if(!str || !matrix) return; 15 | 16 | int symbol = 0; 17 | int word = 0; 18 | bool inWord = false; 19 | 20 | for(char* ptr= str; *ptr; ptr++){ 21 | 22 | if(!isSpaceOrPunctuation(*ptr)){ 23 | inWord=true; 24 | matrix[word][symbol++]=*ptr; 25 | } 26 | else{ 27 | if(inWord) { 28 | matrix[word][symbol]=NULL_TERMINATOR; 29 | word++; 30 | symbol=0; 31 | } 32 | 33 | inWord=false; 34 | } 35 | 36 | } 37 | matrix[word][symbol] = NULL_TERMINATOR; 38 | } 39 | void printMatrix(char matrix[MAX_WORDS][MAX_SYMBOLS_WORDS]){ 40 | for(int i = 0; i < MAX_WORDS && matrix[i][0] != '\0'; i++){ 41 | cout<; 2 | 3 | constexpr size_t SIZE = 1024; 4 | 5 | void getLongestPrefix(const char* const* mtx, char* result) 6 | { 7 | if (!mtx || !result) return; 8 | 9 | const char* firstWord = mtx[0]; 10 | unsigned prefixLength = 0; 11 | 12 | while (true) 13 | { 14 | char currentChar = firstWord[prefixLength]; 15 | 16 | for (unsigned i = 0; mtx[i] != nullptr; i++) 17 | { 18 | if (mtx[i][prefixLength] != currentChar) 19 | { 20 | result[prefixLength] = '\0'; 21 | return; 22 | } 23 | } 24 | 25 | result[prefixLength++] = currentChar; 26 | } 27 | } 28 | 29 | int main() 30 | { 31 | // another variant would be to pass an additional variable rows to the function 32 | const char* mtx[4]{ "flower", "flow", "flight", nullptr }; 33 | char result[SIZE]{ '\0' }; 34 | 35 | getLongestPrefix(mtx, result); 36 | 37 | std::cout << result << std::endl; 38 | 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /Sem. 10/Pract.11/Task13.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int charToDigit(char ch) 4 | { 5 | if (ch >= 'A' && ch <= 'Z') 6 | return 10 + (ch - 'A'); 7 | else if (ch >= '0' && ch <= '9') 8 | return ch - '0'; 9 | 10 | return -1; 11 | } 12 | 13 | unsigned int getLength(const char* src) 14 | { 15 | if (!src) return 0; 16 | 17 | unsigned int length = 0; 18 | 19 | while (*src) 20 | { 21 | length++; 22 | src++; 23 | } 24 | 25 | return length; 26 | } 27 | 28 | int fromAnyBaseToDecimal(const char* src, unsigned srcBase) 29 | { 30 | if (!src) return -1; 31 | 32 | int result = 0, mult = 1, srcLength = getLength(src); 33 | 34 | for (int index = srcLength - 1; index >= 0; index--, mult *= srcBase) 35 | { 36 | int nextDigit = charToDigit(src[index]); 37 | 38 | if (nextDigit < 0) return -1; 39 | 40 | result += mult * nextDigit; 41 | } 42 | 43 | return result; 44 | } 45 | 46 | int main() 47 | { 48 | std::cout << fromAnyBaseToDecimal("IC7", 24) << std::endl; 49 | std::cout << fromAnyBaseToDecimal("11001", 2) << std::endl; 50 | 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /Sem. 10/Pract.11/Task14.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | char toLower(char ch) 4 | { 5 | return (ch >= 'A' && ch <= 'Z') ? ch + ('a' - 'A') : ch; 6 | } 7 | 8 | bool isPrefix(const char* pattern, const char* text) { 9 | if (!pattern || !text) 10 | return false; 11 | 12 | while (*pattern && *text && (toLower(*pattern) == toLower(*text))) { 13 | pattern++; 14 | text++; 15 | } 16 | 17 | return !*pattern; 18 | } 19 | 20 | void censor(char* text, const char* substring) { 21 | if (!text || !substring) 22 | return; 23 | 24 | char* start = text; 25 | int subLen = 0; 26 | 27 | while (substring[subLen]) 28 | subLen++; 29 | 30 | while (*start) { 31 | if (isPrefix(substring, start)) { 32 | for (int i = 0; i < subLen; i++) 33 | start[i] = '*'; 34 | 35 | start += subLen; 36 | } 37 | else 38 | start++; 39 | } 40 | } 41 | 42 | int main() { 43 | char text[] = "Howdy! How are you? How was your day?"; 44 | char substring[] = "How"; 45 | censor(text, substring); 46 | std::cout << text; 47 | } 48 | -------------------------------------------------------------------------------- /Sem. 10/README.md: -------------------------------------------------------------------------------- 1 | ## Динамична памет 2 | 3 | ### Стекова памет/Stack 4 | - predefined size/предварително определен размер(~2MB) 5 | - паметта се заделя ПО ВРЕМЕ на компилацията на програмата (compile time). 6 | - паметта се освобождава/трие/маркира като свободна автоматично - при излизането от scope-а, в който е дефинирана. 7 | 8 | ```c++ 9 | int value = 5; //allocated on the Stack 10 | ``` 11 | 12 | ### Динамична памет/Heap 13 | - паметта се заделя по време на изпълнение на програмата(runtime). 14 | - Масиви и обекти без предварително да е известна големината. 15 | 16 | ```c++ 17 | int value = 5; //allocated on the Stack 18 | int* p = &value; //pointer allocated on the Stack 19 | int* hValue = new int; //hValue is allocated on the stack 20 | //allocates 1 integer on the Heap 21 | *hValue = 5; //dereference to give value to the Heap allocated int 22 | ``` 23 | 24 | ![Memory](images/Memory.png) 25 | 26 | #### Оператор **new** 27 | - Връща указтел към началото на паметта 28 | 29 | ```c++ 30 | new int[n]; //n НЕ е задължително да е константа! 31 | ``` 32 | 33 | - Заделянето на динамична памет е много "бавна" операция!! 34 | - Динамична памет НЕ се трие автоматично. 35 | 36 | #### Оператор delete/delete[] 37 | Oсвобождава/маркира като свободна динамична памет!
38 | 39 | ```c++ 40 | void f() 41 | { 42 | int x = 40; //allocated on the Stack 43 | char ch[2] = {'a', 'b'}; //allocated on the Stack 44 | int* ptr = new int[3]; //allocated on the Heap 45 | } 46 | ``` 47 | 48 | ![Memory-Leak-example](images/exampleMemoryLeak.png) 49 | 50 | След приключването на функцията ще се изчисти паметта в стека, но НЕ и паметта в heap-а.
51 | За това ние трябва ръчно да я маркираме като свободна.
52 | 53 | ```c++ 54 | void f() 55 | { 56 | int x = 40; 57 | char ch[2] = {'a', 'b'}; 58 | int* ptr = new int[3]; 59 | delete[] ptr; //free allocated Heap memory 60 | } 61 | ``` 62 | ## Memory leak (Утечка на памет) 63 | Утечка на памет имаме тогава, когато дадена памет в heap-а бъде заделена, но не бъде зачистена след това. При дълга работа на дадена програма и често възникване на утечки, паметта в heap-a може да свърши! Когато пренасочим указател без да зачистим блока heap памет, към който е сочил, имаме гарантирана утечка! 64 | 65 | ```c++ 66 | int *createArr(int size) { 67 | return new int[size]; 68 | } 69 | 70 | int main() { 71 | int *ptr = new int[5]; //this memory is leaked! 72 | 73 | ptr = createArr(4); //we move the pointer without deleting the memory it was pointing to 74 | delete[] ptr; 75 | } 76 | ``` -------------------------------------------------------------------------------- /Sem. 10/images/Memory.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nikola354/Introduction-to-programming-FMI/1b26ba380133c1919893c672bf3fca6c95f7e34c/Sem. 10/images/Memory.png -------------------------------------------------------------------------------- /Sem. 10/images/exampleMemoryLeak.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nikola354/Introduction-to-programming-FMI/1b26ba380133c1919893c672bf3fca6c95f7e34c/Sem. 10/images/exampleMemoryLeak.png -------------------------------------------------------------------------------- /Sem. 11/Pract.12/Task08.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | size_t* readArr(size_t size) { 5 | size_t* arr = new size_t[size]; 6 | for (size_t i = 0; i < size; i++) { 7 | cin >> arr[i]; 8 | } 9 | return arr; 10 | } 11 | 12 | void reverseNum(size_t& num) { 13 | size_t result = 0; 14 | while (num) { 15 | result *= 10; 16 | result += (num % 10); 17 | num /= 10; 18 | } 19 | num = result; 20 | } 21 | 22 | // - firstsecond 24 | // 0 first==second 25 | int compareLex(size_t first, size_t second) { 26 | reverseNum(first); 27 | reverseNum(second); 28 | while (first && second) { 29 | if ((first % 10) < (second % 10)) { 30 | return -1; 31 | } 32 | else if ((first % 10) > (second % 10)) { 33 | return 1; 34 | } 35 | else { 36 | first /= 10; 37 | second /= 10; 38 | } 39 | } 40 | 41 | return first - second; 42 | } 43 | 44 | void swap(size_t& first, size_t& second) { 45 | size_t temp = first; 46 | first = second; 47 | second = temp; 48 | } 49 | 50 | void sortLex(size_t*& nums, size_t N) { 51 | if (!nums) { 52 | return; 53 | } 54 | 55 | for (size_t i = 0; i < N-1; i++) { 56 | size_t smallest = i; 57 | for (int j = i + 1; j < N; j++) { 58 | if (compareLex(nums[smallest], nums[j]) > 0) { 59 | smallest = j; 60 | } 61 | } 62 | if (smallest != i) { 63 | swap(nums[i], nums[smallest]); 64 | } 65 | } 66 | } 67 | 68 | void printArr(const size_t* arr, size_t size) { 69 | if (!arr) 70 | return; 71 | 72 | for (size_t i = 0; i < size; i++) { 73 | cout << arr[i] << " "; 74 | } 75 | } 76 | int main() 77 | { 78 | size_t size; 79 | cin >> size; 80 | 81 | size_t* arr = readArr(size); 82 | sortLex(arr, size); 83 | printArr(arr, size); 84 | 85 | delete[] arr; 86 | } -------------------------------------------------------------------------------- /Sem. 11/Pract.12/Task09.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int** readMatrix(int rows, int cols) { 5 | int** matrix = new int* [rows]; 6 | for (int i = 0; i < rows; i++) { 7 | matrix[i] = new int[cols]; 8 | for (int j = 0; j < cols; j++) { 9 | cin >> matrix[i][j]; 10 | } 11 | } 12 | return matrix; 13 | } 14 | 15 | bool doesExist(const int* const* edgesMatrix, int edgesCount, int n, int k) { 16 | if (!edgesMatrix) { 17 | return false; 18 | } 19 | 20 | for (int i = 0; i < edgesCount; i++) { 21 | if (edgesMatrix[i][0] == n && edgesMatrix[i][1] == k) { 22 | return true; 23 | } 24 | } 25 | return false; 26 | } 27 | 28 | int** matrixGraph(const int* const* edges, int maxNodeIndexFromEdges) { 29 | if (!edges) { 30 | return nullptr; 31 | } 32 | 33 | int matrixSize = maxNodeIndexFromEdges + 1; 34 | int** matrixGraph = new int* [matrixSize]; 35 | 36 | for (int i = 0; i < matrixSize; i++) { 37 | matrixGraph[i] = new int[matrixSize]; 38 | 39 | for (int j = 0; j < matrixSize; j++) { 40 | if (doesExist(edges, maxNodeIndexFromEdges, i, j) || doesExist(edges, maxNodeIndexFromEdges, j, i)) { 41 | matrixGraph[i][j] = 1; 42 | } 43 | else { 44 | matrixGraph[i][j] = 0; 45 | } 46 | } 47 | } 48 | 49 | return matrixGraph; 50 | } 51 | 52 | void printMatrix(const int* const* matrix, int rows, int cols) { 53 | if (!matrix) { 54 | return; 55 | } 56 | 57 | for (int i = 0; i < rows; i++) { 58 | for (int j = 0; j < cols; j++) { 59 | cout << matrix[i][j] << " "; 60 | } 61 | cout << endl; 62 | } 63 | 64 | } 65 | 66 | void freeMatrix(const int* const* matrix, int rows) { 67 | 68 | for (int i = 0; i < rows; i++) { 69 | delete[] matrix[i]; 70 | } 71 | delete[] matrix; 72 | } 73 | 74 | 75 | int main() 76 | { 77 | int maxNodeIndexFromEdges; 78 | cin >> maxNodeIndexFromEdges; 79 | 80 | int** edges = readMatrix(maxNodeIndexFromEdges, 2); 81 | int** result = matrixGraph(edges, maxNodeIndexFromEdges); 82 | 83 | int matrixGraphSize = maxNodeIndexFromEdges + 1; 84 | printMatrix(result, matrixGraphSize, matrixGraphSize); 85 | 86 | freeMatrix(result, matrixGraphSize); 87 | freeMatrix(edges, maxNodeIndexFromEdges); 88 | } -------------------------------------------------------------------------------- /Sem. 11/Pract.12/Task10.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int** createMatrix(int rows, int cols); 5 | 6 | int getRowSum(const int* const* matrix, int row, int cols); 7 | 8 | void rowsSwap(int** matrix, int from, int to); 9 | 10 | void removeOddRows(int** matrix, int& n, int m); 11 | 12 | void printMatrix(const int* const* matrix, int n, int m); 13 | 14 | int main() { 15 | int n, m; 16 | cin >> n >> m; 17 | 18 | int** matrix = createMatrix(n, m); 19 | 20 | removeOddRows(matrix, n, m); 21 | 22 | printMatrix(matrix, n, m); 23 | 24 | for (int i = 0; i < n; i++) { 25 | delete[] matrix[i]; 26 | } 27 | 28 | delete[] matrix; 29 | } 30 | 31 | int** createMatrix(int rows, int cols) { 32 | int** matrix = new int* [rows]; 33 | 34 | for (int i = 0; i < rows; i++) { 35 | matrix[i] = new int [cols]; 36 | 37 | for (int j = 0; j < cols; j++) { 38 | cin >> matrix[i][j]; 39 | } 40 | } 41 | 42 | return matrix; 43 | } 44 | 45 | int getRowSum(const int* const* matrix, int row, int cols) { 46 | if (!matrix) { 47 | return 0; 48 | } 49 | 50 | int sum = 0; 51 | for (int i = 0; i < cols; i++) { 52 | sum += matrix[row][i]; 53 | } 54 | 55 | return sum; 56 | } 57 | 58 | void rowsSwap(int** matrix, int from, int to) { 59 | if (!matrix) { 60 | return; 61 | } 62 | 63 | int* temp = matrix[from]; 64 | matrix[from] = matrix[to]; 65 | matrix[to] = temp; 66 | } 67 | 68 | void removeOddRows(int** matrix, int& n, int m) { 69 | if (!matrix) { 70 | return; 71 | } 72 | 73 | for (int i = 0; i < n;) { 74 | int sum = getRowSum(matrix, i, m); 75 | 76 | if (sum % 2 != 0) { 77 | rowsSwap(matrix, i, n - 1); 78 | n--; 79 | } else { 80 | i++; 81 | } 82 | } 83 | } 84 | 85 | void printMatrix(const int* const* matrix, int n, int m) { 86 | if (!matrix) { 87 | return; 88 | } 89 | 90 | for (int i = 0; i < n; i++) { 91 | for (int j = 0; j < m; j++) { 92 | cout << matrix[i][j] << " "; 93 | } 94 | cout << endl; 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /Sem. 11/Pract.12/Task11.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int* readArr(size_t len) { 5 | int* arr = new int[len]; 6 | for (int i = 0; i < len; i++) { 7 | cin >> arr[i]; 8 | } 9 | return arr; 10 | } 11 | 12 | void insertAt(int*& arr, size_t& len, int index, int elem) { 13 | if (!arr) { 14 | return; 15 | } 16 | 17 | if (index < 0 || index > len) { 18 | return; 19 | } 20 | 21 | len++; 22 | int* result = new int[len]; 23 | int currentIndex = 0; 24 | int oldArrIndex = 0; 25 | for (int i = 0; i < len; i++) { 26 | if (index == i) { 27 | result[currentIndex++] = elem; 28 | } 29 | else { 30 | result[currentIndex++] = arr[oldArrIndex++]; 31 | } 32 | } 33 | 34 | delete[] arr; 35 | arr = result; 36 | } 37 | 38 | void removeAt(int*& arr, size_t& len, int index) { 39 | if (!arr) { 40 | return; 41 | } 42 | 43 | if (index < 0 || index >= len) { 44 | return; 45 | } 46 | 47 | len--; 48 | int* result = new int[len]; 49 | 50 | int resultIndex = 0; 51 | int oldIndex = 0; 52 | for (int i = 0; i < len + 1; i++) { 53 | if (index == i) { 54 | oldIndex++; 55 | } 56 | else { 57 | result[resultIndex++] = arr[oldIndex++]; 58 | } 59 | } 60 | 61 | delete[] arr; 62 | arr = result; 63 | } 64 | 65 | void printArr(const int* arr, size_t len) { 66 | if (!arr) { 67 | return; 68 | } 69 | 70 | for (int i = 0; i < len; i++) { 71 | cout << arr[i] << " "; 72 | } 73 | } 74 | 75 | int main() 76 | { 77 | size_t len; 78 | cin >> len; 79 | int* arr = readArr(len); 80 | insertAt(arr, len, 4, 123); 81 | removeAt(arr, len, 1); 82 | printArr(arr, len); 83 | 84 | delete[] arr; 85 | 86 | } -------------------------------------------------------------------------------- /Sem. 11/Pract.12/Task12.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | constexpr int MAX_SIZE = 100; 5 | constexpr char TERMINATE_SYMBOL = '\0'; 6 | 7 | bool isDigit(char s); 8 | 9 | int getDigitsCount(const char* str); 10 | 11 | int getNumbersCount(const char* str); 12 | 13 | int getStringLength(const char* str); 14 | 15 | char* censoreNumbers(const char* str); 16 | 17 | int main() { 18 | char str[MAX_SIZE]; 19 | cin.getline(str, MAX_SIZE); 20 | 21 | char* result = censoreNumbers(str); 22 | 23 | cout << result << endl; 24 | 25 | delete[] result; 26 | return 0; 27 | } 28 | 29 | bool isDigit(char s) { 30 | return s >= '0' && s <= '9'; 31 | } 32 | 33 | int getDigitsCount(const char* str) { 34 | if (!str) { 35 | return 0; 36 | } 37 | 38 | int count = 0; 39 | while (*str != TERMINATE_SYMBOL) { 40 | if (isDigit(*str)) { 41 | count++; 42 | } 43 | str++; 44 | } 45 | 46 | return count; 47 | } 48 | 49 | int getNumbersCount(const char* str) { 50 | if (!str) { 51 | return 0; 52 | } 53 | 54 | int count = 0; 55 | while (*str != TERMINATE_SYMBOL) { 56 | if (isDigit(*str) && !isDigit(*(str + 1))) { 57 | count++; 58 | } 59 | str++; 60 | } 61 | 62 | return count; 63 | } 64 | 65 | int getStringLength(const char* str) { 66 | if (!str) { 67 | return 0; 68 | } 69 | 70 | int length = 0; 71 | while (*str != TERMINATE_SYMBOL) { 72 | length++; 73 | str++; 74 | } 75 | 76 | return length; 77 | } 78 | 79 | char* censoreNumbers(const char* str) { 80 | if (!str) { 81 | return nullptr; 82 | } 83 | 84 | int length = getStringLength(str) - getDigitsCount(str) + getNumbersCount(str); 85 | 86 | char* result = new char[length + 1]; // +1 for terminate symbol 87 | result[length] = TERMINATE_SYMBOL; 88 | 89 | int index = 0; 90 | 91 | while (*str != TERMINATE_SYMBOL) { 92 | if (!isDigit(*str)) 93 | result[index++] = *str; 94 | else if (!isDigit(*(str + 1))) 95 | result[index++] = '*'; 96 | 97 | str++; 98 | } 99 | 100 | return result; 101 | } 102 | -------------------------------------------------------------------------------- /Sem. 11/README.md: -------------------------------------------------------------------------------- 1 | ## Динамична памет - задачи 2 | 3 | ## Примери: 4 | 5 | - Да се напише функция, която приема стринг и връща нов стринг с ТОЧНА ГОЛЕМИНА, в който всички числа са цензурирани. (Всяко число е заменено с '*') 6 | - Да се напише функция, която приема стринг и връща два стринга с ТОЧНА големина. Първият да бъде съставен само от малките букви, а другият да бъде съставен само от главните букви. 7 | - Да се напише функция, която приема масив от целия числа, който е получен след конкатенация на два сортирани масив, и го сортира. 8 | - Да се напише функция, която приема стринг и връща нов стринг, който е съставен от малките латински букви на подадения, но в сортиран вид. 9 | 10 | ## Задачи 11 | 12 | **Задача 1:** Напишете програма, която въвежда от клавиатурата цяло число N и след това създава масив с размер N. 13 | 14 | **Задача 2:** Напишете програма, която въвежда от клавиатурата цели числа N и M и след това създава матрица с размер NxM. 15 | 16 | **Задача 3:** Напишете програма, която въвежда от клавиатурата цели числа N, M, Q и след това създава триизмерен масив с размер NxMxQ. 17 | 18 | **Задача 4:** Напишете програма, която намира сумата на елементите над главния диагонал на квадратна матрица NxN, където N се въвежда от потребителя. 19 | 20 | **Задача 5:** Напишете функция, която приема като параметър матрица NxM и връща транспонирата й матрица. 21 | 22 | **Задача 6:** Напишете функция, която приема като параметър матрица NxM и матрица PxQ и връща тяхното матрично произведение.
23 | **Note**: NxM . PxQ = NxQ , тоест трябва m == p. 24 | 25 | **Задача 7:** Напишете функция, която приема масив от цели числа и цяло число и елемент на масива. Функцията да преподрежда елементите, така че всички по-малки елементи от подадения да са в ляво от него, а всички по-големи - в дясно. (Забележка: Задачата да се реши с помощта на допълнителен масив - същестува и решение без допълнителна памет (Hoare's partition, Lomuto partition и други), но то не се изисква) 26 | 27 | *Вход: [1, 5, 6, 3, 0, -1, 2, 9, 7] ,3* *Изход: [1, 0, 2, ,-1, 3, 6, 5, 9, 7]* 28 | 29 | 30 | **Задача 8:** Напишете функция, която приема масив и връща масив от масиви, на който елементите му са всички непразни подмасиви на дадения. 31 | 32 | *Вход: [1, 2, 3]* 33 | 34 | *Изход: [1], [2], [3], [1, 2], [2, 3], [1, 3], [1, 2, 3]* 35 | 36 | 37 | -------------------------------------------------------------------------------- /Sem. 11/Solutions/Censor.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | size_t strLen(const char* str) { 4 | if (!str) { 5 | return 0; 6 | } 7 | 8 | size_t index = 0; 9 | while (str[index]) { 10 | index++; 11 | } 12 | 13 | return index; 14 | } 15 | 16 | bool isDigit(char c) { 17 | return '0' <= c && c <= '9'; 18 | } 19 | 20 | size_t getDigitsCount(const char* str) { 21 | if (!str) { 22 | return 0; 23 | } 24 | 25 | size_t result = 0; 26 | while (*str) { 27 | if (isDigit(*str)) { 28 | result++; 29 | } 30 | str++; 31 | } 32 | 33 | return result; 34 | } 35 | 36 | size_t getNumbersCount(const char* str) { 37 | if (!str) { 38 | return 0; 39 | } 40 | 41 | size_t result = 0; 42 | 43 | while (*str) { 44 | // '\0' saves the day 45 | if (isDigit(*str) && !isDigit(*(str + 1))) { 46 | result++; 47 | } 48 | 49 | str++; 50 | } 51 | 52 | return result; 53 | } 54 | 55 | char* censor(const char* str) { 56 | if (!str) { 57 | return nullptr; 58 | } 59 | 60 | size_t resultLength = strLen(str) - getDigitsCount(str) + getNumbersCount(str); 61 | char* result = new char[resultLength + 1]; 62 | size_t resultIndex = 0; 63 | 64 | while (*str) { 65 | if (!isDigit(*str)) { 66 | result[resultIndex++] = *str; 67 | } 68 | else if (!isDigit(*(str + 1))) { 69 | result[resultIndex++] = '*'; 70 | } 71 | 72 | str++; 73 | } 74 | 75 | result[resultLength] = '\0'; 76 | return result; 77 | } 78 | 79 | int main() { 80 | char* censoredString = censor("0A1B23C12345a5"); 81 | std::cout << censoredString; 82 | delete[] censoredString; // !!! 83 | } 84 | -------------------------------------------------------------------------------- /Sem. 11/Solutions/DynamicCube.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | int rows, cols, height; 5 | std::cin >> rows >> cols >> height; 6 | 7 | // create cube 8 | int*** cube = new int**[height]; 9 | for (int i = 0; i < height; i++) { 10 | cube[i] = new int*[rows]; 11 | for (int j = 0; j < rows; j++) { 12 | cube[i][j] = new int[cols]; 13 | for(int k = 0; k < cols; k++) { 14 | std::cin >> cube[i][j][k]; 15 | } 16 | } 17 | } 18 | 19 | // delete cube 20 | for (int i = 0; i < height; i++) { 21 | for (int j = 0; j < rows; j++) { 22 | delete[] cube[i][j]; 23 | } 24 | delete[] cube[i]; 25 | } 26 | delete[] cube; 27 | } -------------------------------------------------------------------------------- /Sem. 11/Solutions/DynamicMatrix.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | int rows, cols; 5 | std::cin >> rows >> cols; 6 | 7 | // create pointers for the rows of the matrix 8 | int** matrix = new int*[rows]; 9 | for (int i = 0; i < rows; ++i) { 10 | // create the cols for the row 11 | matrix[i] = new int[cols]; 12 | 13 | // read the cols of the row 14 | for (int j = 0; j < cols; ++j) { 15 | std::cin >> matrix[i][j]; 16 | } 17 | } 18 | 19 | // delete matrix 20 | for (int i = 0; i < rows; ++i) { 21 | // delete the cols of the row 22 | delete[] matrix[i]; 23 | } 24 | // delete the rows 25 | delete[] matrix; 26 | } -------------------------------------------------------------------------------- /Sem. 11/Solutions/DynamicMemoryExamples.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int dynamicMemoryTest() { 4 | int length; 5 | std::cin >> length; 6 | 7 | // ptr in the stack, pointing to just a int in the heap 8 | int* intPtr = new int(5); 9 | // ptr in the stack, pointing to arr of ints in the heap 10 | int* arr = new int[length]; 11 | 12 | // !!! 13 | delete intPtr; 14 | delete[] arr; 15 | } 16 | 17 | int* functionReturningDynamicArray() { 18 | int length; 19 | std::cin >> length; 20 | 21 | int* arr = new int[length]; 22 | arr[0] = 1; 23 | arr[1] = 5; 24 | return arr; 25 | } 26 | 27 | int main() { 28 | dynamicMemoryTest(); 29 | int* arr = functionReturningDynamicArray(); 30 | std::cout << arr[0] << " " << arr[1]; 31 | delete[] arr; 32 | } 33 | -------------------------------------------------------------------------------- /Sem. 11/Solutions/LowerUpper.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | bool isLower(char c) { 4 | return 'a' <= c && c <= 'z'; 5 | } 6 | bool isUpper(char c) { 7 | return 'A' <= c && c <= 'Z'; 8 | } 9 | 10 | void getLowerAndUpperCount( 11 | const char* str, 12 | size_t& lowerCount, 13 | size_t& upperCount 14 | ) { 15 | if (!str) { 16 | return; 17 | } 18 | 19 | lowerCount = upperCount = 0; 20 | 21 | while (*str) { 22 | if (isLower(*str)) { 23 | lowerCount++; 24 | } 25 | else if (isUpper(*str)) { 26 | upperCount++; 27 | } 28 | 29 | str++; 30 | } 31 | } 32 | 33 | void getLowerAndUpperString( 34 | const char* str, 35 | char*& lowerString, 36 | char*& upperString 37 | ) { 38 | if (!str) { 39 | return; 40 | } 41 | 42 | size_t lowerCount = 0, upperCount = 0; 43 | getLowerAndUpperCount(str, lowerCount, upperCount); 44 | lowerString = new char[lowerCount + 1]; 45 | upperString = new char[upperCount + 1]; 46 | lowerString[lowerCount] = upperString[upperCount] = '\0'; 47 | if (lowerCount == 0 && upperCount == 0) { 48 | return; 49 | } 50 | 51 | size_t lowerIndex = 0, upperIndex = 0; 52 | while (*str) { 53 | if (isLower(*str)) { 54 | lowerString[lowerIndex++] = *str; 55 | } 56 | else if (isUpper(*str)) { 57 | upperString[upperIndex++] = *str; 58 | } 59 | 60 | str++; 61 | } 62 | } 63 | 64 | int main() { 65 | char* lowerString = nullptr; 66 | char* upperString = nullptr; 67 | getLowerAndUpperString("Pa1a2a3B4B5Bz", lowerString, upperString); 68 | 69 | std::cout << lowerString << std::endl; // aaaz 70 | std::cout << upperString << std::endl; // PBBB 71 | 72 | delete[] lowerString; // !!! 73 | delete[] upperString; // !!! 74 | } -------------------------------------------------------------------------------- /Sem. 11/Solutions/SortLower.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | const unsigned ALPHABET_LETTERS_COUNT = 26; 4 | 5 | bool isLower(char c) { 6 | return 'a' <= c && c <= 'z'; 7 | } 8 | 9 | size_t getLowerCount(const char* str, size_t* counter) { 10 | if (!str) { 11 | return 0; 12 | } 13 | 14 | size_t lowerCount = 0; 15 | while (*str) { 16 | if (isLower(*str)) { 17 | lowerCount++; 18 | counter[*str - 'a']++; 19 | } 20 | 21 | str++; 22 | } 23 | 24 | return lowerCount; 25 | } 26 | 27 | char* getSortLowerLetters(const char* str) { 28 | if (!str) { 29 | return nullptr; 30 | } 31 | 32 | size_t counter[ALPHABET_LETTERS_COUNT] = {}; 33 | size_t lowerLettersCount = getLowerCount(str, counter); 34 | char* result = new char[lowerLettersCount + 1]; 35 | result[lowerLettersCount] = '\0'; 36 | if (lowerLettersCount == 0) { 37 | return result; 38 | } 39 | 40 | size_t resultIndex = 0; 41 | for (size_t i = 0; i < ALPHABET_LETTERS_COUNT; i++) { 42 | if (counter[i] == 0) { 43 | continue; 44 | } 45 | 46 | while (counter[i]) { 47 | result[resultIndex++] = 'a' + i; 48 | counter[i]--; 49 | } 50 | } 51 | 52 | return result; 53 | } 54 | 55 | int main() { 56 | char* sortedLowerLetters = getSortLowerLetters("a123fZsdaf"); 57 | 58 | std::cout << sortedLowerLetters; 59 | 60 | delete[] sortedLowerLetters; 61 | } -------------------------------------------------------------------------------- /Sem. 11/Solutions/Task07.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // 5 | void printResult(int* arr, unsigned size) { 6 | if (!arr)return; 7 | 8 | for (unsigned i = 0; i < size; i++) { 9 | cout << arr[i] << " "; 10 | } 11 | } 12 | void rearrangeArray(int* arr, unsigned size, int element) { 13 | if (!arr) return; 14 | int* result = new int[size]; 15 | unsigned resultIndex = 0; 16 | 17 | for (unsigned i = 0; i < size; i++) { 18 | if (arr[i] < element){ 19 | result[resultIndex++] = arr[i]; 20 | } 21 | } 22 | 23 | for (unsigned i = 0; i < size; i++) { 24 | if (arr[i] == element) { 25 | result[resultIndex++] = arr[i]; 26 | } 27 | } 28 | 29 | for (unsigned i = 0; i < size; i++) { 30 | if (arr[i] > element && resultIndex < size) { 31 | result[resultIndex++] = arr[i]; 32 | } 33 | } 34 | printResult(result, size); 35 | delete[] result; 36 | } 37 | int main() { 38 | const unsigned size = 9; 39 | int arr[size]; 40 | 41 | for (int i = 0; i < size; i++) { 42 | cin >> arr[i]; 43 | } 44 | 45 | int element; 46 | bool isElement = false; 47 | do { 48 | cin >> element; 49 | 50 | for (unsigned i = 0; i < size; i++) { 51 | if (element == arr[i]) { 52 | isElement = true; 53 | break; 54 | } 55 | } 56 | if(!isElement) cout << "Invalid input! Enter element: "; 57 | } 58 | while (!isElement); 59 | rearrangeArray(arr, size, element); 60 | 61 | cout << endl; 62 | } 63 | -------------------------------------------------------------------------------- /Sem. 11/Solutions/Task08.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void printSubset(const int* arr, unsigned length, unsigned mask) { 5 | if (!arr)return; 6 | 7 | unsigned subsetSize = 0; 8 | for (unsigned i = 0; i < length; i++) { 9 | if (mask & (1< 2 | using namespace std; 3 | 4 | int sumAboveMainDiagonal(const int *const *matrix, int N) { 5 | int sum = 0; 6 | 7 | for (int i = 0; i < N; i++) { 8 | for (int j = i + 1; j < N; j++) { 9 | sum += matrix[i][j]; 10 | } 11 | } 12 | 13 | return sum; 14 | } 15 | 16 | int main() { 17 | int N; 18 | cin >> N; 19 | int** matrix = new int* [N]; 20 | 21 | for (int i = 0; i < N; i++) { 22 | matrix[i] = new int[N]; 23 | for (int j = 0; j < N; j++) { 24 | cin >> matrix[i][j]; 25 | } 26 | } 27 | 28 | 29 | cout << sumAboveMainDiagonal(matrix, N); 30 | 31 | for (int i = 0; i < N; i++) { 32 | delete[] matrix[i]; 33 | } 34 | delete[] matrix; 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /Sem. 11/Task05.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void printMatrix(const int* const* temp, unsigned rows, unsigned cols) { 5 | if (!temp)return; 6 | for (int i = 0; i < rows; i++) { 7 | for (int j = 0; j < cols; j++) { 8 | cout << temp[i][j] << " "; 9 | } 10 | cout << endl; 11 | } 12 | } 13 | void transpose(const int* const* matr, unsigned N, unsigned M) { 14 | if (!matr)return; 15 | int**temp = new int*[M]; 16 | 17 | for (int i = 0; i < M; i++) { 18 | temp[i] = new int[N]; 19 | } 20 | 21 | for (int i = 0; i < N; i++) { 22 | for (int j = 0; j < M; j++) { 23 | temp[j][i] = matr[i][j]; 24 | } 25 | } 26 | printMatrix(temp, M, N); 27 | 28 | for (int i = 0; i < M; i++) { 29 | delete[] temp[i]; 30 | } 31 | delete[] temp; 32 | } 33 | 34 | int main() { 35 | unsigned N, M; 36 | cin >> N >> M; 37 | 38 | int** matrix = new int* [N]; 39 | 40 | for (int i = 0; i < N; i++) { 41 | matrix[i] = new int[M]; 42 | for (int j = 0; j < M; j++) { 43 | cin >> matrix[i][j]; 44 | } 45 | } 46 | 47 | transpose(matrix, N, M); 48 | for (int i = 0; i < N; i++) { 49 | delete[] matrix[i]; 50 | } 51 | delete[] matrix; 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /Sem. 11/Task06.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int** allocateMatrix(unsigned rows, unsigned cols) { 5 | int** matrix = new int*[rows]; 6 | for (unsigned i = 0; i < rows; i++) { 7 | matrix[i] = new int[cols]; 8 | } 9 | return matrix; 10 | } 11 | 12 | void readMatrix(int** matrix, unsigned rows, unsigned cols) { 13 | if (!matrix)return; 14 | 15 | for (unsigned i = 0; i < rows; i++) { 16 | for (unsigned j = 0; j < cols; j++) { 17 | cin >> matrix[i][j]; 18 | } 19 | } 20 | } 21 | 22 | void printMatrix(const int *const *result, unsigned rows, unsigned cols) { 23 | if (!result)return; 24 | 25 | for (unsigned i = 0; i < rows; i++) { 26 | for (unsigned j = 0; j < cols; j++) { 27 | cout << result[i][j] << " "; 28 | } 29 | cout << endl; 30 | } 31 | } 32 | 33 | void freeMatrix(int** matrix, unsigned rows) { 34 | if (!matrix)return; 35 | 36 | for (unsigned i = 0; i < rows; i++) { 37 | delete[] matrix[i]; 38 | } 39 | delete[] matrix; 40 | } 41 | 42 | int ** multiplyTwoMatrices (const int *const * matr1, const int *const * matr2, unsigned rows1, unsigned cols1, unsigned cols2) { 43 | if (!matr1 || !matr2)return; 44 | 45 | int** result = allocateMatrix(rows1, cols2); 46 | 47 | for (unsigned i = 0; i < rows1; i++) { 48 | for (unsigned j = 0; j < cols2; j++) { 49 | result[i][j] = 0; 50 | 51 | for (unsigned k = 0; k < cols1; k++) { 52 | 53 | result[i][j] += matr1[i][k] * matr2[k][j]; 54 | } 55 | } 56 | } 57 | 58 | return result; 59 | } 60 | 61 | int main() { 62 | unsigned N, M, P, Q; 63 | 64 | cout << "Enter N: " << endl; 65 | cin >> N; 66 | 67 | do { 68 | cout << "Enter M and P: "<> M >> P; 70 | if (M != P) cout << "Invalid input. Matrices with such size can not be multilied!"<> Q; 76 | 77 | int** matrix1 = allocateMatrix(N, M); 78 | int** matrix2 = allocateMatrix(P, Q); 79 | 80 | cout << "Enter the first matrix: " << endl; 81 | readMatrix(matrix1, N, M); 82 | 83 | cout << "Enter the second matrix: " << endl; 84 | readMatrix(matrix2, P, Q); 85 | 86 | int ** result = multiplyTwoMatrices(matrix1, matrix2, N, M, Q); 87 | printMatrix(result, N, Q); 88 | 89 | freeMatrix(result, N); 90 | freeMatrix(matrix1, N); 91 | freeMatrix(matrix2, P); 92 | 93 | return 0; 94 | } 95 | -------------------------------------------------------------------------------- /Sem. 12/Bonus_Theory.md: -------------------------------------------------------------------------------- 1 | ## Бонус теория - видове рекурсии 2 | ### **Пряка и косвена рекурсия** 3 | Когато в тялото на метод се извършва извикване на същия метод, казваме, че методът е **пряко рекурсивен**.
4 | ```c++ 5 | // An example of direct recursion 6 | void directRecFun() { 7 | // Some code.... 8 | directRecFun(); 9 | // Some code... 10 | } 11 | ``` 12 | 13 | **Видове пряка рекурсия:** 14 | - **Tail** - ако рекурсивното извикване е последната команда/израз. 15 | 16 | ```c++ 17 | #include 18 | 19 | void fun(int n) { 20 | if (n > 0) { 21 | std::cout << n << " "; 22 | fun(n - 1); // Last statement in the function 23 | } 24 | } 25 | 26 | int main() { 27 | fun(3); 28 | return 0; 29 | } 30 | ``` 31 | 32 | ![Tail-recursion](images/Tail-recursion.jpg) 33 | 34 | - **Head** - ако рекурсивното извикване е първата команда/израз. 35 | 36 | ```c++ 37 | #include 38 | 39 | void fun(int n) { 40 | if (n > 0) { 41 | fun(n - 1); // First statement in the function 42 | std::cout << " "<< n; 43 | } 44 | } 45 | 46 | int main() { 47 | fun(3); 48 | return 0; 49 | } 50 | ``` 51 | 52 | ![Head-recursion](images/Head-recursion.jpg) 53 | 54 | - **Linear** vs **Tree** 55 | - **Linear** - ако в тялото на функцията, тя се извиква само веднъж. 56 | - **Tree** - ако в тялото на функцията, тя се извиква повече от веднъж. 57 | 58 | ```c++ 59 | #include 60 | 61 | // Recursive function 62 | void fun(int n) { 63 | if (n > 0) { 64 | std::cout << " " << n; 65 | 66 | // Calling once 67 | fun(n - 1); 68 | 69 | // Calling twice 70 | fun(n - 1); 71 | } 72 | } 73 | 74 | int main() { 75 | fun(3); 76 | return 0; 77 | } 78 | ``` 79 | 80 | ![Tree-recursion](images/Tree-recursion.jpg) 81 | 82 | - **Nested** - рекурсия в рекурсията. Когато се подаде рекурсия като параметър. 83 | 84 | ```c++ 85 | #include 86 | 87 | int fun(int n) { 88 | if (n > 100) { 89 | return n - 10; 90 | } 91 | 92 | // A recursive function passing parameter as a recursive call 93 | // or recursion inside the recursion 94 | return fun(fun(n + 11)); 95 | } 96 | 97 | int main() { 98 | std::cout << " " << fun(95); 99 | 100 | return 0; 101 | } 102 | ``` 103 | 104 | ![Nested-recursion](images/Nested-recursion.jpg) 105 | 106 | 107 | Ако метод A се обръща към метод B, B към C, а С отново към А, казваме, че методът А, както и методите В и C са **непряко (косвено) рекурсивни** или **взаимно-рекурсивни**.
108 | Веригата от извиквания при косвената рекурсия може да съдържа множество методи, както и разклонения, т.е. при наличие на едно условие да се извиква един метод, а при различно условие да се извиква друг.
109 | ```c++ 110 | // An example of indirect recursion 111 | void indirectRecFun1() { 112 | // Some code... 113 | indirectRecFun2(); 114 | } 115 | 116 | void indirectRecFun2() { 117 | // Some code... 118 | indirectRecFun3(); 119 | } 120 | 121 | void indirectRecFun3() { 122 | // Some code... 123 | indirectRecFun1(); 124 | } 125 | ``` 126 | 127 | ![Direct-Indirect-Recursion](images/Indirect-direct-recursion.png) 128 | 129 | -------------------------------------------------------------------------------- /Sem. 12/Pract.13/Task08.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | bool contains(const int* arr, int x) 4 | { 5 | if (!arr) return false; 6 | return *arr != x ? contains(arr + 1, x) : true; 7 | } 8 | 9 | int main() 10 | { 11 | size_t N = 0; 12 | std::cin >> N; 13 | 14 | int num = 0; 15 | std::cin >> num; 16 | 17 | int* arr = new int[N]; 18 | 19 | for (size_t i = 0; i < N; i++) 20 | { 21 | std::cin >> arr[i]; 22 | } 23 | 24 | std::cout << contains(arr, num) << std::endl; 25 | 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /Sem. 12/Pract.13/Task09.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | bool binarySearch(const int* arr, int x, size_t len) 4 | { 5 | if (!arr || len == 0) return false; 6 | 7 | size_t mid = len / 2; 8 | 9 | if (arr[mid] == x) 10 | { 11 | return true; 12 | } 13 | else if (arr[mid] < x) 14 | { 15 | return binarySearch(arr + mid + 1, x, len - mid - 1); 16 | } 17 | else 18 | { 19 | return binarySearch(arr, x, mid); 20 | } 21 | } 22 | 23 | int main() 24 | { 25 | size_t N = 0; 26 | std::cin >> N; 27 | 28 | int num = 0; 29 | std::cin >> num; 30 | 31 | int* arr = new int[N]; 32 | 33 | for (size_t i = 0; i < N; i++) 34 | { 35 | std::cin >> arr[i]; 36 | } 37 | 38 | std::cout << binarySearch(arr, num, N) << std::endl; 39 | 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /Sem. 12/Pract.13/Task12.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | bool isValid(int **mtx, int rows, int cols, int row, int col, bool ** visited) { 4 | return row >= 0 && row < rows && col >= 0 && col < cols && mtx[row][col] == 1 && !visited[row][col]; 5 | } 6 | 7 | bool canReachEnd(int **mtx, int rows, int cols, int startRow, 8 | int startCol, int endRow, int endCol, bool **visited) { 9 | 10 | if (startRow == endRow && startCol == endCol) 11 | return true; 12 | 13 | visited[startRow][startCol] = true; 14 | 15 | int dRow[] = {1, -1, 0, 0}; 16 | int dCol[] = {0, 0, 1, -1}; 17 | 18 | for (int i = 0; i < 4; i++) { 19 | int currRow = startRow + dRow[i]; 20 | int currCol = startCol + dCol[i]; 21 | 22 | if (isValid(mtx, rows, cols, currRow, currCol, visited) && 23 | canReachEnd(mtx, rows, cols, currRow, currCol, endRow, endCol, visited)) 24 | return true; 25 | } 26 | 27 | return false; 28 | } 29 | 30 | int main() { 31 | int rows, cols; 32 | std::cin >> rows >> cols; 33 | 34 | int **mtx = new int *[rows]; 35 | bool **visited = new bool *[rows]; 36 | 37 | for (int i = 0; i < rows; i++) { 38 | mtx[i] = new int[cols]; 39 | visited[i] = new bool[cols](); 40 | 41 | for (int j = 0; j < cols; j++) 42 | std::cin >> mtx[i][j]; 43 | } 44 | 45 | int startRow = 0, startCol = 0, endRow = rows - 1, endCol = cols - 1; 46 | std::cout << std::boolalpha << canReachEnd(mtx, rows, cols, startRow, startCol, endRow, endCol, visited); 47 | 48 | for (int i = 0; i < rows; i++) { 49 | delete[] mtx[i]; 50 | delete[] visited[i]; 51 | } 52 | delete[] mtx; 53 | delete[] visited; 54 | 55 | return 0; 56 | } 57 | -------------------------------------------------------------------------------- /Sem. 12/RecursionQuestions.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // What type of recursion is this, how will it print the array? 4 | // Array: [1, 2, 3, 4, 5], size: 5 5 | // Answer: Head recursion => 1 2 3 4 5 6 | void printArr1(int* arr, size_t size) { 7 | if (size == 0) { 8 | return; 9 | } 10 | 11 | printArr1(arr, size - 1); 12 | std::cout << arr[size - 1] << " "; 13 | } 14 | 15 | // What type of recursion is this, how will it print the array? 16 | // Array: [1, 2, 3, 4, 5], size: 5 17 | // Answer: Tail recursion => 5 4 3 2 1 18 | void printArr2(int* arr, int size) { 19 | if (size == 0) { 20 | return; 21 | } 22 | 23 | std::cout << arr[size - 1] << " "; 24 | printArr2(arr, size - 1); 25 | } 26 | 27 | // What will the function return if n = 5? 28 | // Answer: the result will always be 0 29 | // because when N is 1 we should calculate fact with N * fact(--N) 30 | // --N will give us 0 31 | // => we have to calculate fact(0) so we return 1 32 | // but N * 1 is actually 0 * 1, because N is already decremented 33 | size_t fact1(size_t n) { 34 | if (n == 0) { 35 | return 1; 36 | } 37 | 38 | return n * fact1(--n); 39 | } 40 | 41 | // What will the function return if n = 5? 42 | size_t fact2(size_t n) { 43 | if (n == 0) { 44 | return 1; 45 | } 46 | 47 | return n * fact2(n--); 48 | } 49 | -------------------------------------------------------------------------------- /Sem. 12/Solutions/BinarySearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | bool binarySearch(const int* arr, size_t size, int target) { 4 | if (size == 0) { 5 | return false; 6 | } 7 | 8 | size_t midIndex = size / 2; 9 | 10 | if (arr[midIndex] == target) { 11 | return true; 12 | } 13 | 14 | if (target < arr[midIndex]) { 15 | return binarySearch(arr, midIndex, target); 16 | } 17 | else { 18 | return binarySearch(arr + midIndex + 1, size - midIndex - 1, target); 19 | } 20 | } 21 | 22 | int main() { 23 | const size_t ARRAY_SIZE = 10; 24 | int arr[ARRAY_SIZE] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 25 | 26 | std::cout << binarySearch(arr, ARRAY_SIZE, 8) << std::endl; 27 | std::cout << binarySearch(arr, ARRAY_SIZE, 3) << std::endl; 28 | std::cout << binarySearch(arr, ARRAY_SIZE, 11) << std::endl; 29 | std::cout << binarySearch(arr, ARRAY_SIZE, 0) << std::endl; 30 | } 31 | -------------------------------------------------------------------------------- /Sem. 12/Solutions/Factoriel.cpp: -------------------------------------------------------------------------------- 1 | size_t fact(size_t n) { 2 | if (n == 0) { 3 | return 1; 4 | } 5 | 6 | return n * fact(n - 1); 7 | } -------------------------------------------------------------------------------- /Sem. 12/Solutions/FastPow.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | size_t fastPow(size_t n, size_t k) { 4 | if (k == 0) { 5 | return 1; 6 | } 7 | 8 | if (k & 1) { 9 | return n * fastPow(n, k - 1); 10 | } 11 | else { 12 | return fastPow(n * n, k / 2); 13 | } 14 | } 15 | 16 | int main() { 17 | std::cout << fastPow(2, 8); 18 | } 19 | -------------------------------------------------------------------------------- /Sem. 12/Solutions/Fibonacci.cpp: -------------------------------------------------------------------------------- 1 | size_t fibonacci(size_t n) { 2 | if (n == 0 || n == 1) { 3 | return 1; 4 | } 5 | 6 | return fibonacci(n - 1) + fibonacci(n - 2); 7 | } -------------------------------------------------------------------------------- /Sem. 12/Solutions/Fibonacci_Cache.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | size_t _fibonacci_rec(size_t n, size_t* cache) { 4 | if (n == 0 || n == 1) { 5 | return n; 6 | } 7 | 8 | if (!cache[n]) { 9 | cache[n] = _fibonacci_rec(n - 1, cache) + _fibonacci_rec(n - 2, cache); 10 | } 11 | 12 | return cache[n]; 13 | } 14 | 15 | size_t fibonacci(size_t n) { 16 | size_t* cache = new size_t[n + 1](); 17 | size_t result = _fibonacci_rec(n, cache); 18 | delete[] cache; 19 | 20 | return result; 21 | } 22 | 23 | int main() { 24 | // 1 1 2 3 5 8 25 | std::cout << fibonacci(50); 26 | } -------------------------------------------------------------------------------- /Sem. 12/Solutions/LinearSearch.cpp: -------------------------------------------------------------------------------- 1 | bool linearSearch(const int* arr, size_t size, int target) { 2 | if (size == 0) { 3 | return false; 4 | } 5 | 6 | return *arr == target || linearSearch(arr + 1, size - 1, target); 7 | } -------------------------------------------------------------------------------- /Sem. 12/Solutions/Pow.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int power(int n, int k) { 4 | if(k == 0) { 5 | return 1; 6 | } 7 | 8 | return n * power(n , k - 1); 9 | } 10 | 11 | int main() { 12 | std::cout << power(2, 8); 13 | } -------------------------------------------------------------------------------- /Sem. 12/Solutions/SumArray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int sumArray(const int* arr, size_t size) { 4 | if(size == 0) { 5 | return 0; 6 | } 7 | 8 | return arr[0] + sumArray(arr + 1, size - 1); 9 | } 10 | 11 | int main() { 12 | int arr[] = { 1, 2, 3, 4, 5 }; 13 | std::cout << sumArray(arr, 5); 14 | } -------------------------------------------------------------------------------- /Sem. 12/images/Head-recursion.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nikola354/Introduction-to-programming-FMI/1b26ba380133c1919893c672bf3fca6c95f7e34c/Sem. 12/images/Head-recursion.jpg -------------------------------------------------------------------------------- /Sem. 12/images/Indirect-direct-recursion.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nikola354/Introduction-to-programming-FMI/1b26ba380133c1919893c672bf3fca6c95f7e34c/Sem. 12/images/Indirect-direct-recursion.png -------------------------------------------------------------------------------- /Sem. 12/images/Nested-recursion.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nikola354/Introduction-to-programming-FMI/1b26ba380133c1919893c672bf3fca6c95f7e34c/Sem. 12/images/Nested-recursion.jpg -------------------------------------------------------------------------------- /Sem. 12/images/Recursion-simpsons.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nikola354/Introduction-to-programming-FMI/1b26ba380133c1919893c672bf3fca6c95f7e34c/Sem. 12/images/Recursion-simpsons.gif -------------------------------------------------------------------------------- /Sem. 12/images/SumRange.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nikola354/Introduction-to-programming-FMI/1b26ba380133c1919893c672bf3fca6c95f7e34c/Sem. 12/images/SumRange.gif -------------------------------------------------------------------------------- /Sem. 12/images/Tail-recursion.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nikola354/Introduction-to-programming-FMI/1b26ba380133c1919893c672bf3fca6c95f7e34c/Sem. 12/images/Tail-recursion.jpg -------------------------------------------------------------------------------- /Sem. 12/images/Tree-recursion.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nikola354/Introduction-to-programming-FMI/1b26ba380133c1919893c672bf3fca6c95f7e34c/Sem. 12/images/Tree-recursion.jpg -------------------------------------------------------------------------------- /Sem. 12/images/factorial-formula.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nikola354/Introduction-to-programming-FMI/1b26ba380133c1919893c672bf3fca6c95f7e34c/Sem. 12/images/factorial-formula.png -------------------------------------------------------------------------------- /Sem. 12/images/factorial.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nikola354/Introduction-to-programming-FMI/1b26ba380133c1919893c672bf3fca6c95f7e34c/Sem. 12/images/factorial.gif -------------------------------------------------------------------------------- /Sem. 12/images/fib.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nikola354/Introduction-to-programming-FMI/1b26ba380133c1919893c672bf3fca6c95f7e34c/Sem. 12/images/fib.gif -------------------------------------------------------------------------------- /Sem. 12/images/fib.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nikola354/Introduction-to-programming-FMI/1b26ba380133c1919893c672bf3fca6c95f7e34c/Sem. 12/images/fib.png -------------------------------------------------------------------------------- /Sem. 12/images/gcd-definition.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nikola354/Introduction-to-programming-FMI/1b26ba380133c1919893c672bf3fca6c95f7e34c/Sem. 12/images/gcd-definition.png -------------------------------------------------------------------------------- /Sem. 13/Algorithms/Complexity/CompareFunctions.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void constant(int n) { 5 | n += 5; 6 | } 7 | 8 | void n(int n) { 9 | int num = 0; 10 | for (int i = 1; i < n; i++) { 11 | num++; 12 | } 13 | } 14 | 15 | void logN(int n) { 16 | int num = 0; 17 | for (int i = 1; i < n; i *= 2) { 18 | num++; 19 | } 20 | } 21 | 22 | void nLogN(int n) { 23 | int num = 0; 24 | for (int i = 0; i < n; i++) { 25 | for (int j = 1; j < n; j *= 2) { 26 | num++; 27 | } 28 | } 29 | } 30 | 31 | void nPow2(int n) { 32 | int num = 0; 33 | for (int i = 0; i < n; i++) { 34 | for (int j = 0; j < n; j++) { 35 | num++; 36 | } 37 | } 38 | } 39 | 40 | void measureAndPrint(int n, void(*func)(int)) { 41 | auto begin = std::chrono::high_resolution_clock::now(); 42 | func(n); 43 | auto end = std::chrono::high_resolution_clock::now(); 44 | std::cout << "n = " << n << ", Time: " << std::chrono::duration_cast(end - begin).count() << "ns" << std::endl; 45 | } 46 | 47 | void measureAndPrintAll(void(*func)(int)) { 48 | measureAndPrint(500, func); 49 | measureAndPrint(5000, func); 50 | measureAndPrint(50000, func); 51 | measureAndPrint(500000, func); 52 | measureAndPrint(5000000, func); 53 | } 54 | 55 | int main() 56 | { 57 | std::cout << "Constant Algo" << std::endl; 58 | measureAndPrintAll(constant); 59 | std::cout << "LogN Algo" << std::endl; 60 | measureAndPrintAll(logN); 61 | std::cout << std::endl; 62 | std::cout << "Linear Algo" << std::endl; 63 | measureAndPrintAll(n); 64 | std::cout << std::endl; 65 | std::cout << "NLogN Algo" << std::endl; 66 | measureAndPrintAll(nLogN); 67 | std::cout << std::endl; 68 | std::cout << "N^2 Algo" << std::endl; 69 | measureAndPrintAll(nPow2); 70 | } -------------------------------------------------------------------------------- /Sem. 13/Algorithms/Complexity/ComplexityExamples.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // O(1) 4 | void example0(size_t n) { 5 | cout << "Hello"; 6 | } 7 | 8 | // N 9 | void example1(size_t n) { 10 | for (size_t i = 0; i < n; i++) { 11 | /* code */ 12 | } 13 | } 14 | 15 | // N 16 | void example1a(size_t n) { 17 | for (size_t i = 0; i < n; i++) { 18 | /* code */ 19 | } 20 | 21 | for (size_t i = 0; i < n; i++) { 22 | /* code */ 23 | } 24 | 25 | for (size_t i = 0; i < n; i++) { 26 | /* code */ 27 | } 28 | } 29 | 30 | // N^2 31 | void example2(size_t n) { 32 | for(size_t i = 0; i < n; i++) { 33 | for(size_t j = 0; j < n; j += 2) { 34 | /* code */ 35 | } 36 | } 37 | } 38 | 39 | // NLogN 40 | void example3(size_t n) { 41 | for(size_t i = 0; i < n; i++) { 42 | for(size_t j = 1; j < n; j *= 2) { 43 | /* code */ 44 | } 45 | } 46 | } 47 | 48 | // N^2 49 | void example4(const char* str) { 50 | for(size_t i = 0; i < strlen(str); i++) { 51 | /* code */ 52 | } 53 | } 54 | 55 | // NLogN 56 | void example5(size_t n) { 57 | for(size_t i = 0; i < n; i++) { 58 | for(size_t j = 0; j < n; j *= 2) { 59 | /* code */ 60 | } 61 | } 62 | 63 | for(size_t i = 0; i < n; i++) { 64 | for(size_t j = 0; j < n; j *= 2) { 65 | /* code */ 66 | } 67 | } 68 | } 69 | 70 | int main() { 71 | } 72 | 73 | // N^2 74 | void example2(size_t n) { 75 | for(size_t i = 0; i < n; i++) { 76 | for(size_t j = 0; j < n; j += 2) { 77 | /* code */ 78 | } 79 | } 80 | } 81 | 82 | // NLogN 83 | void example3(size_t n) { 84 | for(size_t i = 0; i < n; i++) { 85 | for(size_t j = 1; j < n; j *= 2) { 86 | /* code */ 87 | } 88 | } 89 | } 90 | 91 | // N^2 92 | void example4(const char* str) { 93 | for(size_t i = 0; i < strlen(str); i++) { 94 | /* code */ 95 | } 96 | } 97 | 98 | // NLogN 99 | void example5(size_t n) { 100 | for(size_t i = 0; i < n; i++) { 101 | for(size_t j = 0; j < n; j *= 2) { 102 | /* code */ 103 | } 104 | } 105 | 106 | for(size_t i = 0; i < n; i++) { 107 | for(size_t j = 0; j < n; j *= 2) { 108 | /* code */ 109 | } 110 | } 111 | } 112 | 113 | int main() { 114 | } 115 | -------------------------------------------------------------------------------- /Sem. 13/Algorithms/Searching/BinarySearch.cpp: -------------------------------------------------------------------------------- 1 | int binarySearch(const int* arr, size_t length, int target) { 2 | size_t leftIndex = 0, rightIndex = length - 1; 3 | 4 | while (leftIndex <= rightIndex) { 5 | // int midIndex = (leftIndex + rightIndex) / 2; 6 | // Why the following is better? 7 | size_t midIndex = leftIndex + (rightIndex - leftIndex) / 2; 8 | 9 | if (arr[midIndex] == target) { 10 | return midIndex; 11 | } 12 | else if (arr[midIndex] < target) { 13 | leftIndex = midIndex + 1; 14 | } 15 | else { 16 | rightIndex = midIndex - 1; 17 | } 18 | } 19 | 20 | return -1; 21 | } -------------------------------------------------------------------------------- /Sem. 13/Algorithms/Searching/LinearSearch.cpp: -------------------------------------------------------------------------------- 1 | int linearSearch(const int* arr, size_t length, int x) { 2 | for(size_t i = 0; i < length; ++i) { 3 | if(arr[i] == x) { 4 | return i; 5 | } 6 | } 7 | 8 | return -1; 9 | } -------------------------------------------------------------------------------- /Sem. 13/Algorithms/Searching/LinearchVsBinarySearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int linearSearch(const int* arr, size_t length, int x) { 5 | for (size_t i = 0; i < length; ++i) { 6 | if (arr[i] == x) { 7 | return i; 8 | } 9 | } 10 | 11 | return -1; 12 | } 13 | 14 | int binarySearch(const int* arr, size_t length, int x) { 15 | size_t leftIndex = 0, rightIndex = length - 1; 16 | 17 | while (leftIndex <= rightIndex) { 18 | size_t midIndex = leftIndex + (rightIndex - leftIndex) / 2; 19 | 20 | if (arr[midIndex] == x) { 21 | return midIndex; 22 | } 23 | else if (arr[midIndex] < x) { 24 | leftIndex = midIndex + 1; 25 | } 26 | else { 27 | rightIndex = midIndex - 1; 28 | } 29 | } 30 | 31 | return -1; 32 | } 33 | 34 | void measureSearchFunction( 35 | const int* arr, 36 | size_t length, 37 | int x, 38 | int (*searchFunction)(const int*, size_t, int) 39 | ) { 40 | auto begin = std::chrono::high_resolution_clock::now(); 41 | searchFunction(arr, length, x); 42 | auto end = std::chrono::high_resolution_clock::now(); 43 | std::cout << "Found in:" << std::chrono::duration_cast(end - begin).count() << "ns" << std::endl; 44 | } 45 | 46 | int main() { 47 | const size_t ARR_LENGTH = 10000; 48 | int arr[ARR_LENGTH]; 49 | for (size_t i = 0; i < ARR_LENGTH; i++) { 50 | arr[i] = i + 1; 51 | } 52 | 53 | measureSearchFunction(arr, ARR_LENGTH, 30101, binarySearch); 54 | measureSearchFunction(arr, ARR_LENGTH, 30101, linearSearch); 55 | } -------------------------------------------------------------------------------- /Sem. 13/Algorithms/Sorting/BubbleSort.cpp: -------------------------------------------------------------------------------- 1 | void swap(int& a, int& b) { 2 | int temp = a; 3 | a = b; 4 | b = temp; 5 | } 6 | 7 | void bubbleSort(int* arr, size_t size) { 8 | for (size_t i = 0; i < size; i++) { 9 | bool swapped = false; 10 | for(size_t j = 0; j < size - i - 1; j++) { 11 | if(arr[j] > arr[j + 1]) { 12 | swap(arr[j], arr[j + 1]); 13 | swapped = true; 14 | } 15 | } 16 | 17 | if(!swapped) { 18 | break; 19 | } 20 | } 21 | } 22 | 23 | void evenMoreOptimizedBubbleSort(int* arr, size_t size) { 24 | int lastSwappedIndex = size - 1; 25 | for (size_t i = 0; i < size; i++) { 26 | int currentSwappedIndex = -1; 27 | for (size_t j = 0; j < lastSwappedIndex; j++) { 28 | if (arr[j] > arr[j + 1]) { 29 | currentSwappedIndex = j; 30 | swap(arr[j], arr[j + 1]); 31 | } 32 | } 33 | 34 | if (currentSwappedIndex == -1) { 35 | return; 36 | } 37 | lastSwappedIndex = currentSwappedIndex; 38 | } 39 | } -------------------------------------------------------------------------------- /Sem. 13/Algorithms/Sorting/CountingSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | const int CHARACTERS_COUNT = 256; 4 | 5 | void unstableCountingSort(char* arr, size_t length) { 6 | size_t arrLength = strlen(arr); 7 | int counter[CHARACTERS_COUNT] = { 0 }; 8 | // count every char 9 | for (size_t i = 0; i < length; i++) { 10 | counter[arr[i]]++; 11 | } 12 | 13 | size_t index = 0; 14 | for (size_t i = 0; i < CHARACTERS_COUNT; i++) { 15 | while (counter[i] != 0) { 16 | arr[index++] = i; 17 | counter[i]--; 18 | } 19 | } 20 | } 21 | 22 | int main() { 23 | char arr[] = "ababababababa"; 24 | unstableCountingSort(arr, 13); 25 | std::cout << arr; 26 | } -------------------------------------------------------------------------------- /Sem. 13/Algorithms/Sorting/DemoMain.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void print(int* arr, size_t size) { 4 | for (size_t i = 0; i < size; i++) { 5 | std::cout << arr[i] << " "; 6 | } 7 | std::cout << std::endl; 8 | } 9 | 10 | int main() { 11 | const int size = 10; 12 | int arr[size] = { 5, 3, 2, 6, 4, 7, 9, 10, 1, 8 }; 13 | 14 | // Place here your sorting function 15 | 16 | print(arr, size); 17 | } -------------------------------------------------------------------------------- /Sem. 13/Algorithms/Sorting/InsertionSort.cpp: -------------------------------------------------------------------------------- 1 | void insertionSort(int* arr, size_t size) { 2 | for (int i = 1; i < size; i++) { 3 | int currentElement = arr[i]; 4 | int currentIndex = i - 1; 5 | while (currentIndex >= 0 && arr[currentIndex] > currentElement) { 6 | arr[currentIndex + 1] = arr[currentIndex]; 7 | currentIndex--; 8 | } 9 | 10 | arr[currentIndex + 1] = currentElement; 11 | } 12 | } -------------------------------------------------------------------------------- /Sem. 13/Algorithms/Sorting/SelectionSort.cpp: -------------------------------------------------------------------------------- 1 | void swap(int& a, int& b) { 2 | int temp = a; 3 | a = b; 4 | b = temp; 5 | } 6 | 7 | void selectionSort(int* arr, size_t size) { 8 | for (size_t i = 0; i < size - 1; i++) { 9 | size_t minIndex = i; 10 | for (size_t j = i + 1; j < size; j++) { 11 | if(arr[j] < arr[minIndex]) { 12 | minIndex = j; 13 | } 14 | } 15 | 16 | if(minIndex != i) { 17 | swap(arr[i], arr[minIndex]); 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /Sem. 13/Algorithms/Sorting/StableCountingSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void stableCountingSort(char* arr, size_t length) { 4 | size_t arrLength = strlen(arr); 5 | char* copy = new char[arrLength]; 6 | // copy the original 7 | for (size_t i = 0; i < arrLength; i++) { 8 | copy[i] = arr[i]; 9 | } 10 | 11 | int counter[256] = { 0 }; 12 | // count every char 13 | for (size_t i = 0; i < length; i++) { 14 | counter[arr[i]]++; 15 | } 16 | 17 | // the counter will become the index where the next element 18 | // of every different type should be placed 19 | for (size_t i = 1; i < 256; i++) { 20 | counter[i] += counter[i - 1]; 21 | } 22 | 23 | // put the characters in the initial array sorted 24 | // started backwards so that the sorting is stable 25 | for (int i = arrLength - 1; i >= 0; i--) { 26 | // counter[copy[i] - 1 => where the element should be placed 27 | arr[counter[copy[i]] - 1] = copy[i]; 28 | // the next element of this type should be placed one index behind this one 29 | --counter[copy[i]]; 30 | } 31 | 32 | delete[] copy; 33 | } 34 | 35 | int main() { 36 | char arr[] = "ababababababa"; 37 | stableCountingSort(arr, 13); 38 | std::cout << arr; 39 | } -------------------------------------------------------------------------------- /Sem. 13/Pract.14/README.md: -------------------------------------------------------------------------------- 1 |

УП - Практикум - 17.01.2025 - Седмица 14

2 | 3 | **Задача 1:** Да се напише функция, която приема масив и го интерпретира като два конкатенирани масива. Първата част да се сортира възходящо, а втората нисходящо. 4 | 5 | ```c++ 6 | [4, 1, 2, 8, 9, -4, 0, -6, 11, 3] 7 | ``` 8 | 9 | ```c++ 10 | [ 1, 2, 4, 8, 9, 11, 3, 0, -4, -6 ] 11 | ``` 12 | 13 | **Задача 2:** Даден ви е масив, който съдържа само **цифри**. Вашата задача е да го сортирате в линейно време. 14 | 15 | **Задача 3:** Да се реализира сортировката CoctailShaker, която е много подобна на BubbleSort. 16 | 17 | Алгоритъмът е следният: 18 | Проверяваме първия и втория елемент. Ако първия е по-голям от втория, **ги разместваме**. След това проверяваме втория и третия, като правим същото. Стъпката се изпълнява, докато не стигнем до края на колекцията. Щом стигнем до края на колекцията, **най-големият елемент е на мястото си** т.е. няма нужда да го пипаме. 19 | 20 | Сега тръгваме наобратно и сравняваме **предпоследния с пред-предпоследния**. Ако предпоследния е по-малък `arr[i] < arr[i - 1]`, ги разменяме. Прилагаме подобна на първоначалната стратегия докато най-малкият елемент не заеме мястото си. 21 | 22 | След това започваме пак отначало. Този път сравняваме втория и третия. 23 | 24 | Процедурата се повтаря в двете посоки, докато масивът не се сортира. 25 | 26 | [Визуализатор](https://www.sortvisualizer.com/shakersort/) 27 | 28 | **Пример:** 29 | 30 | ```c++ 31 | [4, 1, 2, 8, 9, 15, -4, 0, -6, 11, 3] 32 | ``` 33 | 34 | ```c++ 35 | 1во => [ 4, 1, 2, 8, 9, -4, 0, -6, 11, 3, 15 ] 36 | 2ро <= [ -6, 4, 1, 2, 8, 9, -4, 0, 11, 3, 15 ] 37 | ``` 38 | 39 | **Задача 4:** Да се напише функция, която приема двумерен масив arr[3][N] от числа. 40 | 41 | ```c++ 42 | arr[0] наричаме първичен ключ; 43 | arr[1] наричаме вторичен ключ; 44 | arr[2] наричаме стойност; 45 | ``` 46 | 47 | Тройката `(arr[0][i], arr[1][i], arr[2][i])` е по-малка от тройката `(arr[0][j], arr[1][j], arr[2][j])` ако 48 | 49 | ```c++ 50 | arr[0][i] < arr[0][j] или arr[0][i] == arr[0][j] & arr[1][i] < arr[1][j] 51 | ``` 52 | 53 | Сортирайте двумерния масив така, че за всяко `i < j` е вярно `(arr[0][i], arr[1][i], arr[2][i]) < (arr[0][j], arr[1][j], arr[2][j])`. 54 | 55 | **Пример:** 56 | 57 | ```c++ 58 | [ 59 | [4 7 4 9 4 12], 60 | [2 4 1 5 3 0], 61 | [1 2 3 4 5 6] 62 | ] 63 | ``` 64 | 65 | ```c++ 66 | [ 67 | [4 4 4 7 9 12], 68 | [1 2 3 4 5 0], 69 | [3 1 5 2 4 6] 70 | ] 71 | ``` 72 | 73 | **Задача 5:** Да се напише функция, която намира колко инверсии има в масив от цели числа. 74 | 75 | **Инверсия:** `Всяка двойка (i, j) за която i < j и arr[i] > arr[j]` 76 | 77 | *Бонус: Помислете има ли как да се напише решение по-бързо от O(n^2)* 78 | -------------------------------------------------------------------------------- /Sem. 13/README.md: -------------------------------------------------------------------------------- 1 | ### Сложност и алгоритми. Алгоритми за търсене и сортиране. 2 | Сложност: Функция по големината на входа (N) 3 | 4 | **Пример**: 5 | 6 | - При търсене в масив - големината на входа е големината на масива 7 | - При проверка число дали е просто - големината на входа е числото. 8 | 9 | При анализа на алгоритми НЕ се интересуваме от точната функция! 10 | Интересуваме се само то асимптотиката на функцията. 11 | Колко бързо расте функцията при n->безкрайност. 12 | 13 | ### Определяне на сложност по време и памет 14 | Примери в Solutions - Complexity 15 | 16 | Cheatsheet - https://www.bigocheatsheet.com/ 17 | 18 | ![](https://devopedia.org/images/article/17/4996.1513922020.jpg) 19 | 20 | ### Алгоритми за търсене 21 | * Linear Seach - сложност O(n) 22 | * Binary Search - сложност O(log n) 23 | 24 | ### Алгоритми за сортиране 25 | 26 | Как работят нагледно: https://visualgo.net/en/sorting 27 | 28 | Разгледайте качените cpp-та успоредно с интерактивните примери в visualgo 29 | 30 | *Стабилна сортировка - сортировка, при която два елемента с еднакви стойности остават в същата последователност в сортирания масив, в каквато са били и в първоначалния 31 | 32 | В курса по УП ще разгледаме следните сортировки: 33 | 34 | **Note!**: Не трябва да знаете свойствата, които не са показани в час 35 | 36 | #### Bubble sort (stable) 37 | ![image](images/bubble.png) 38 | 39 | #### Insertion sort (stable) 40 | ![image](images/insertion.png) 41 | 42 | #### Selection sort (unstable) 43 | ![image](images/selection.png) 44 | 45 | #### Counting sort (stable) 46 | ![image](images/counting.png) 47 | -------------------------------------------------------------------------------- /Sem. 13/images/bubble.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nikola354/Introduction-to-programming-FMI/1b26ba380133c1919893c672bf3fca6c95f7e34c/Sem. 13/images/bubble.png -------------------------------------------------------------------------------- /Sem. 13/images/counting.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nikola354/Introduction-to-programming-FMI/1b26ba380133c1919893c672bf3fca6c95f7e34c/Sem. 13/images/counting.png -------------------------------------------------------------------------------- /Sem. 13/images/insertion.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nikola354/Introduction-to-programming-FMI/1b26ba380133c1919893c672bf3fca6c95f7e34c/Sem. 13/images/insertion.png -------------------------------------------------------------------------------- /Sem. 13/images/selection.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nikola354/Introduction-to-programming-FMI/1b26ba380133c1919893c672bf3fca6c95f7e34c/Sem. 13/images/selection.png --------------------------------------------------------------------------------