diff options
new
88 files changed, 0 insertions, 3442 deletions
diff --git a/Sem. 01/README.md b/Sem. 01/README.md deleted file mode 100644 index e89e8dc..0000000 --- a/Sem. 01/README.md +++ /dev/null @@ -1,23 +0,0 @@ -# Основни типове. Преобразуване между типове. Оператори. - - -## Основни типове - -| Тип | Памет: | Стойности: | -|:----------------------:|:-------:|:-------------------------------:| -| unsigned char | 1 byte | 0 to 255 | -| signed char | 1 byte | -127 to 127 | -| int | 4 bytes | -2147483648 to 2147483647 | -| unsigned int | 4 bytes | 0 to 4294967295 | -| signed int | 4 bytes | -2147483648 to 2147483647 | -| short int | 2 bytes | -32768 to 32767 | -| unsigned short int | 2 bytes | 0 to 65,535 | -| signed short int | 2 bytes | -32768 to 32767 | -| long int | 8 bytes | -2,147,483,648 to 2,147,483,647 | -| signed long int | 8 bytes | same as long int | -| unsigned long int | 8 bytes | 0 to 4,294,967,295 | -| long long int | 8 bytes | -(2^63) to (2^63)-1 | -| unsigned long long int | 8 bytes | 0 to 18,446,744,073,709,551,615 | -| float | 4 bytes | | -| double | 4 bytes | | -| bool | 1 bytes | 0 to 1 | diff --git a/Sem. 01/Variables.cpp b/Sem. 01/Variables.cpp deleted file mode 100644 index f793a65..0000000 --- a/Sem. 01/Variables.cpp +++ /dev/null @@ -1,117 +0,0 @@ -#include<iostream> -using namespace std; - - -int main() -{ - //The reason why operator = returns a value! - int a, b, c, d, e, f; - a = b = c = d = e = f = 5; - - //Types - int t1 = 4; - double t2 = 4.5; - char t3 = 'v'; - bool t4 = true; - - - //Operators - - //Arithmetic operators - int num1 = 5; - int num2 = 2; - - int result = a + b; //7 - result = a - b; //3 - result = a * b; //10 - result = a / b; // 2 (not 2.5) (both are ints) - result = a%b; //1 5:2 = 2 (rem :1) - - double num2Copy = 2; - double resultCopy = num1 / num2Copy; //2.5 (one of the variables is a double) - - int A = 5; - int B = 2; - - cout << (A++ - B) << endl;// 3 (but A becomes 6) - A = 5;//let's make it 5 again - cout << (++A - B) << endl;//4 (A becomes 6) - - // Comparison operators - - int N1 = 5; - int N2 = 6; - - cout << (N1 > N2)<<endl; // 0(false); - //or we can do this: - bool cond = N1 > N2; - cout << cond; - - - //Other comparison operators : ==, !=, >, <, >=,<= - - - - //Logical operators - - bool var1 = false; - bool var2 = true; - - bool t1 = var1 && var2; //false; - bool t2 = var1 || var2; //true - bool t3 = var1 ^ var2; //true - - - //Type casting - - int a1 = 97; - double b1 = a1; - char c1 = a1; - bool d1 = a1; - - cout << a1 << endl; //97 - cout << b1 << endl; //97.0 - cout << c1 << endl; //a - cout << d1 << endl; //1 - - - double b2 = 65.5; - int a2 = b2; - char c2 = b2; - bool d2 = b2; - - cout << b2 << endl; //65.5 - cout << a2 << endl; //65 - cout << c2 << endl; //A - cout << d2 << endl; //1 - - - char c3 = 'a'; - double b3 = c3; - int a3 = c3; - bool d3 = c3; - - cout << c3 << endl; //a - cout << b3 << endl; //97 - cout << a3 << endl; //97 - cout << d3 << endl; //1 - - bool d4 = true; - int a4 = d4; - double b4 = d4; - char c4 = d4; - - cout << c4 << endl; // ?? - cout << b4 << endl; // 1 - cout << a4 << endl; // 1 - cout << d4 << endl; // 1 - - int grade = 5; - - bool isValid = grade >= 2 && grade <= 6; - bool isValid2 = grade == 2 || grade == 3 || grade == 4 || grade == 5||grade == 6; - - bool isNotValid = !isValid; - bool isNotValid2 = grade < 2 || grade>6; - -} diff --git a/Sem. 02/Even_Odd.cpp b/Sem. 02/Even_Odd.cpp deleted file mode 100644 index 89c2ecd..0000000 --- a/Sem. 02/Even_Odd.cpp +++ /dev/null @@ -1,17 +0,0 @@ -#include <iostream> -using namespace std; - -int main() -{ - int number; - cin >> number; - - if (number % 2 == 0) - { - std::cout << "Even" << endl; - } - else - { - std::cout << "Odd" << endl; - } -}
\ No newline at end of file diff --git a/Sem. 02/Grades.cpp b/Sem. 02/Grades.cpp deleted file mode 100644 index 18e1538..0000000 --- a/Sem. 02/Grades.cpp +++ /dev/null @@ -1,63 +0,0 @@ - -#include <iostream> -using namespace std; - -int main() -{ - int grade; - cin >> grade; - - //Bad - if (grade == 2) - { - cout << "Poor" << endl; - } - if (grade == 3) - { - cout << "Average" << endl; - } - if (grade == 4) - { - cout << "Good" << endl; - } - if (grade == 5) - { - cout << "Very good" << endl; - } - if (grade == 6) - { - cout << "Excellent" << endl; - } - if (grade < 2 || grade > 6) - { - cout << "Invalid" << endl; - } - //This works! But when we find a match, we continue checking, even though we don't need to. - - //Better - if (grade == 2) - { - cout << "Poor" << endl; - } - else if (grade == 3) - { - cout << "Average" << endl; - } - else if (grade == 4) - { - cout << "Good" << endl; - } - else if (grade == 5) - { - cout << "Very good" << endl; - } - else if (grade == 6) - { - cout << "Excellent" << endl; - } - else - { - cout << "Invalid" << endl; - } - -}
\ No newline at end of file diff --git a/Sem. 02/Operators_priority.png b/Sem. 02/Operators_priority.png Binary files differdeleted file mode 100644 index 07d2565..0000000 --- a/Sem. 02/Operators_priority.png +++ /dev/null diff --git a/Sem. 02/dayOfWeek.cpp b/Sem. 02/dayOfWeek.cpp deleted file mode 100644 index b9640c3..0000000 --- a/Sem. 02/dayOfWeek.cpp +++ /dev/null @@ -1,22 +0,0 @@ -#include <iostream> -using namespace std; - -int main() -{ - int num; - cin >> num; - - switch (num) - { - case 1:cout << "Monday" << endl; break; - case 2:cout << "Tuesday" << endl; break; - case 3:cout << "Wednesday" << endl; break; - case 4:cout << "Thursday" << endl; break; - case 5:cout << "Friday" << endl; break; - case 6:cout << "Saturday" << endl; break; - case 7:cout << "Sunday" << endl; break; - - default: cout << "The number is not a valid day of the week" << endl; - } - -}
\ No newline at end of file diff --git a/Sem. 02/isPrime_between[1,9].cpp b/Sem. 02/isPrime_between[1,9].cpp deleted file mode 100644 index 08d8445..0000000 --- a/Sem. 02/isPrime_between[1,9].cpp +++ /dev/null @@ -1,26 +0,0 @@ - -#include <iostream> -using namespace std; - -int main() -{ - int num; - cin >> num; - - switch (num) - { - case 2: - case 3: - case 5: - case 7:cout << "Prime" << endl; break; - - case 1: - case 4: - case 6: - case 8: - case 9:cout << "Not a prime" << endl; break; - - default: cout << "The number is not between 1 and 10" << endl; break; - } - -}
\ No newline at end of file diff --git a/Sem. 03/Contains5.cpp b/Sem. 03/Contains5.cpp deleted file mode 100644 index 78d13f0..0000000 --- a/Sem. 03/Contains5.cpp +++ /dev/null @@ -1,32 +0,0 @@ -#include <iostream> - -using namespace std; - -int main() -{ - int n; - cin >> n; - - bool foundFive = false; - while (n != 0) - { - int lastDigit = n % 10; - if (lastDigit == 5) - { - foundFive = true; - break; - } - n /= 10; - } - - if (foundFive) - { - cout << "yes"; - } - else - { - cout << "no"; - } - - -}
\ No newline at end of file diff --git a/Sem. 03/GCD_solution1.cpp b/Sem. 03/GCD_solution1.cpp deleted file mode 100644 index 58ea35b..0000000 --- a/Sem. 03/GCD_solution1.cpp +++ /dev/null @@ -1,32 +0,0 @@ -#include <iostream> - -using namespace std; - -int main() -{ - int n, k; - - cin >> n >> k; - - if (n < k) //swap - { - int temp = n; - n = k; - k = temp; - } - - int devider = 1; - int result; - while (devider <= k) - { - if (n % devider == 0 && k % devider == 0) - { - result = devider; - } - devider++; - } - - cout << result; - - -}
\ No newline at end of file diff --git a/Sem. 03/GCD_solution2.cpp b/Sem. 03/GCD_solution2.cpp deleted file mode 100644 index ba06c89..0000000 --- a/Sem. 03/GCD_solution2.cpp +++ /dev/null @@ -1,35 +0,0 @@ -#include <iostream> - -using namespace std; - -int main() -{ - int n, k; - - cin >> n >> k; - - if (n < k) //swap - { - int temp = n; - n = k; - k = temp; - - } - int devider = k; - bool foundSolution = false; - - - while (!foundSolution) - { - if (n % devider == 0 && k % devider == 0) - foundSolution = true; - else - devider--; - - - } - cout << devider; - - - -}
\ No newline at end of file diff --git a/Sem. 03/GCD_solution3_Eucid.cpp b/Sem. 03/GCD_solution3_Eucid.cpp deleted file mode 100644 index f190a90..0000000 --- a/Sem. 03/GCD_solution3_Eucid.cpp +++ /dev/null @@ -1,25 +0,0 @@ -#include <iostream> - -using namespace std; - -int main() -{ - int n, k; - - cin >> n >> k; - - if (n < k) //swap - { - int temp = n; - n = k; - k = temp; - } - - while (k != 0) - { - int div = n % k; - n = k; - k = div; - } - cout << n << endl; -}
\ No newline at end of file diff --git a/Sem. 03/PrintEvenNumbers.cpp b/Sem. 03/PrintEvenNumbers.cpp deleted file mode 100644 index e9a2231..0000000 --- a/Sem. 03/PrintEvenNumbers.cpp +++ /dev/null @@ -1,27 +0,0 @@ -#include <iostream> - -using namespace std; - -int main() -{ - int n; - cin >> n; - - int j = 0; - while (j <= n) - { - cout << j << endl; - j += 2; - } - - //Here the variable j is reachable! - - - for (int i = 0; i <=n; i++) - { - cout << i << endl; - } - // Here the variable i is NOT reachable. - - -}
\ No newline at end of file diff --git a/Sem. 03/README.md b/Sem. 03/README.md deleted file mode 100644 index 5d510c5..0000000 --- a/Sem. 03/README.md +++ /dev/null @@ -1,109 +0,0 @@ -# Цикли -### Цикъл for - -```c++ - -for( <Инициализация(i)>; <Булево условие>; <Актуализация(i)> ) -{ - <Тяло на цикъла(i)> -} - - ``` - Изпълнението работи така: -1. Изпълнява се инициализацията -2. Проверява се булевото условие; - - 2.1 ако има стойност **лъжа**, цикълът приключва - - 2.2 ако има стойност **истина**, се изпълнава 3. - -3. Изпълнява се тялото на цикъла. -4. Изпълнява се инкрементацията. Отиваме на точка 2. -### Цикъл while -```c++ -while ( <Булево условие> ) -{ - <Тяло на цикъла> -} - ``` -Изпълнението работи така: -1. Проверява се булевото условие; - - 1.1 ако има стойност **лъжа**, цикълът приключва - - 1.2 ако има стойност **истина**, се изпълнава 2. - -2. Изпълнява се тялото на цикъла. Отиваме на 1. - -### Цикъл do- while -```c++ -do -{ - <Тяло на цикъла> - -}while ( <Булево условие> ); - ``` - Изпълнението работи така: -1. Изпълнява се тялото на цикъла. -2. Проверява се булевото условие - - 2.1 ако има стойност **лъжа**, цикълът приключва - - 2.2 ако има стойност **истина**, отиваме на точка 1. - -# Конвертиране на цикли. - - - -### От for към while. -```c++ -// for loop -for(int i = 0; i < 10; i++) -{ - <Тяло на цикъла> -} - -// for loop converted to while loop -int i = 0; //Инициализация -while(i < 10) -{ - <Тяло на цикъла> - i++; // Актуализация -} - ``` -### От while към for. - -```c++ - -// while loop -while(*str != '\0') -{ - <Тяло на цикъла> - ++str; -} - - -// while loop converted to for loop -for(; *str != '\0'; ++str) -{ - <Тяло на цикъла> -} - ``` - ### От do-while към while. -```c++ -// do-while loop -do -{ - <Тяло на цикъла> - -} while ( <Условие> ); - - -// do-while loop converted to while loop -<Тяло на цикъла> -while( <Условие> ) -{ - <Тяло на цикъла> -} - ``` -Забележка! Предложените начини за преобразуване между цикли са с демонстрационна цел! Спрямо конкретната цитуация може да се постигне такова преобразуване и по много по-прост начин. diff --git a/Sem. 03/SimpleDevidersCount_PrimalityCheck.cpp b/Sem. 03/SimpleDevidersCount_PrimalityCheck.cpp deleted file mode 100644 index db39c9c..0000000 --- a/Sem. 03/SimpleDevidersCount_PrimalityCheck.cpp +++ /dev/null @@ -1,30 +0,0 @@ -#include <iostream> - -using namespace std; - -int main() -{ - unsigned int n; //allways positive int - cin >> n; - - int divCount = 0; - - for (int i = 1; i <= n; i++) - { - if (n%i == 0) - divCount++; - } - //Can we reduce the number of steps? - - if (divCount == 2) - { - cout << "Prime" << endl; - } - else - { - cout << "Not a prime" << endl; - } - - - -} diff --git a/Sem. 03/SumOfDigits.cpp b/Sem. 03/SumOfDigits.cpp deleted file mode 100644 index 6777a42..0000000 --- a/Sem. 03/SumOfDigits.cpp +++ /dev/null @@ -1,22 +0,0 @@ -#include <iostream> - -using namespace std; - -int main() -{ - int n; - cin >> n; - - int digitSum = 0; - - while (n != 0) - { - int lastDigit = n % 10; //extracts last digit - digitSum += lastDigit; //adds it to the sum - n /= 10; //removes last digit - } - - cout << digitSum; - - -}
\ No newline at end of file diff --git a/Sem. 03/Tasks and Solutions/01. Between100and200.cpp b/Sem. 03/Tasks and Solutions/01. Between100and200.cpp deleted file mode 100644 index 0817bcc..0000000 --- a/Sem. 03/Tasks and Solutions/01. Between100and200.cpp +++ /dev/null @@ -1,15 +0,0 @@ -#include <iostream> -using namespace std; - -int main() -{ - unsigned int n; - cin >> n; - - if (n < 100) - cout << "Less than 100" << endl; - else if (n <= 200) - cout << "Between 100 and 200" << endl; - else - cout << "More than 200" << endl; -}
\ No newline at end of file diff --git a/Sem. 03/Tasks and Solutions/02. Speed check.cpp b/Sem. 03/Tasks and Solutions/02. Speed check.cpp deleted file mode 100644 index 4660382..0000000 --- a/Sem. 03/Tasks and Solutions/02. Speed check.cpp +++ /dev/null @@ -1,19 +0,0 @@ -#include <iostream> -using namespace std; - -int main() -{ - double speed; - cin >> speed; - - if (speed <= 10) - cout << "Slow" << endl; - else if (speed < 50) - cout << "Average" << endl; - else if (speed < 150) - cout << "Fast" << endl; - else if (speed < 1000) - cout << "Ultra fast" << endl; - else - cout << "Extremely fast" << endl; -}
\ No newline at end of file diff --git a/Sem. 03/Tasks and Solutions/03. Figures.cpp b/Sem. 03/Tasks and Solutions/03. Figures.cpp deleted file mode 100644 index 170c403..0000000 --- a/Sem. 03/Tasks and Solutions/03. Figures.cpp +++ /dev/null @@ -1,28 +0,0 @@ -#include <iostream> -using namespace std; - -const double PI = 3.14; -int main() -{ - char figure; - cin >> figure; - - if (figure == 's') - { - double side; - cin >> side; - cout << side * side << endl; - } - else if (figure == 'r') - { - double sideA, sideB; - cin >> sideA >> sideB; - cout << sideA * sideB << endl; - } - else if (figure == 'c') - { - double R; - cin >> R; - cout << PI * R * R << endl; - } -}
\ No newline at end of file diff --git a/Sem. 03/Tasks and Solutions/04. Time + 15.cpp b/Sem. 03/Tasks and Solutions/04. Time + 15.cpp deleted file mode 100644 index aee3118..0000000 --- a/Sem. 03/Tasks and Solutions/04. Time + 15.cpp +++ /dev/null @@ -1,21 +0,0 @@ -#include <iostream> -using namespace std; - -const double PI = 3.14; -int main() -{ - int hours, mins; - cin >> hours >> mins; - - (mins += 15) %= 60; - - if (mins < 15) - (hours+=1)%=24; - - if (hours <= 9) - cout << 0; - cout << hours << ":"; - if (mins <= 9) - cout << 0; - cout << mins << endl; -}
\ No newline at end of file diff --git a/Sem. 03/Tasks and Solutions/05. Chainsaw.cpp b/Sem. 03/Tasks and Solutions/05. Chainsaw.cpp deleted file mode 100644 index 68940e0..0000000 --- a/Sem. 03/Tasks and Solutions/05. Chainsaw.cpp +++ /dev/null @@ -1,16 +0,0 @@ -#include <iostream> -using namespace std; - -int main() -{ - int a, b, c, d, e; - cin >> a >> b >> c >> d >> e; - - if ((a <= b && b >= c && c <= d && d >= e) - || (a >= b && b <= c && c >= d && d <= e)) - { - cout << "Yes"; - } - else - cout << "No"; -}
\ No newline at end of file diff --git a/Sem. 03/Tasks and Solutions/06. DivBy3.cpp b/Sem. 03/Tasks and Solutions/06. DivBy3.cpp deleted file mode 100644 index 044aee9..0000000 --- a/Sem. 03/Tasks and Solutions/06. DivBy3.cpp +++ /dev/null @@ -1,11 +0,0 @@ -#include <iostream> -using namespace std; - -int main() -{ - int n; - cin >> n; - - for (int i = 3; i <= n; i+=3) - cout << i << endl; -}
\ No newline at end of file diff --git a/Sem. 03/Tasks and Solutions/07. ContainsDigit.cpp b/Sem. 03/Tasks and Solutions/07. ContainsDigit.cpp deleted file mode 100644 index 4ae1131..0000000 --- a/Sem. 03/Tasks and Solutions/07. ContainsDigit.cpp +++ /dev/null @@ -1,20 +0,0 @@ -#include <iostream> -using namespace std; - -int main() -{ - int n, searchedDigit; - cin >> n >> searchedDigit; - - bool found = false; - while (n != 0) - { - int lastDigit = n % 10; - if (searchedDigit == lastDigit) - { - found = true; - break; - } - n /= 10; - } -}
\ No newline at end of file diff --git a/Sem. 03/Tasks and Solutions/08. DuplicateDigits.cpp b/Sem. 03/Tasks and Solutions/08. DuplicateDigits.cpp deleted file mode 100644 index 0fa5946..0000000 --- a/Sem. 03/Tasks and Solutions/08. DuplicateDigits.cpp +++ /dev/null @@ -1,93 +0,0 @@ -#include <iostream> -using namespace std; - -int main() -{ - bool found0, found1, found2, found3, found4, found5, found6, found7, found8, found9; - found0 = found1 = found2 = found3 = found4 = found5 = found6 = found7 = found8 = found9 = false; - - int n; - cin >> n; - - bool foundDuplicate = false; - while (!foundDuplicate && n != 0) - { - int lastDigit = n % 10; - switch (lastDigit) - { - case 0: - if (found0) - { - foundDuplicate = true; - - } - found0 = true; - break; - case 1: - if (found1) - { - foundDuplicate = true; - } - found1 = true; - break; - case 2: - if (found2) - { - foundDuplicate = true; - } - found2 = true; - break; - case 3: - if (found3) - { - foundDuplicate = true; - } - found3 = true; - break; - case 4: - if (found4) - { - foundDuplicate = true; - } - found4 = true; - break; - case 5: - if (found5) - { - foundDuplicate = true; - } - found5 = true; - break; - case 6: - if (found6) - { - foundDuplicate = true; - } - found6 = true; - break; - case 7: - if (found7) - { - foundDuplicate = true; - } - found7 = true; - break; - case 8: - if (found8) - { - foundDuplicate = true; - } - found8 = true; - case 9: - if (found9) - { - foundDuplicate = true; - } - found9 = true; - break; - } - n /= 10; - } - - cout << foundDuplicate; -}
\ No newline at end of file diff --git a/Sem. 03/Tasks and Solutions/09. SumFromKtoN.cpp b/Sem. 03/Tasks and Solutions/09. SumFromKtoN.cpp deleted file mode 100644 index aea318a..0000000 --- a/Sem. 03/Tasks and Solutions/09. SumFromKtoN.cpp +++ /dev/null @@ -1,18 +0,0 @@ -#include <iostream> -using namespace std; - -int main() -{ - int n, k; - cin >> k >> n; - - int sum = 0; - for (int i = k; i <= n; i++) - sum += i; - - cout << sum << endl; - - //or use the formula - - cout << (n*(n + 1)) / 2 - ((k - 1)*k) / 2 << endl; -}
\ No newline at end of file diff --git a/Sem. 03/Tasks and Solutions/10. Pyramid.cpp b/Sem. 03/Tasks and Solutions/10. Pyramid.cpp deleted file mode 100644 index 5d9e2a9..0000000 --- a/Sem. 03/Tasks and Solutions/10. Pyramid.cpp +++ /dev/null @@ -1,14 +0,0 @@ -#include <iostream> -using namespace std; - -int main() -{ - int n; - cin >> n; - for (int i = 1; i <= n; i++) - { - for (int j = 1; j <= i; j++) - cout << "$"; - cout << endl; - } -}
\ No newline at end of file diff --git a/Sem. 03/Tasks and Solutions/11. Clock.cpp b/Sem. 03/Tasks and Solutions/11. Clock.cpp deleted file mode 100644 index 6386ca0..0000000 --- a/Sem. 03/Tasks and Solutions/11. Clock.cpp +++ /dev/null @@ -1,18 +0,0 @@ -#include <iostream> -using namespace std; - -int main() -{ - for (int hour = 0; hour <= 23; hour++) - { - for (int min = 0; min <= 59; min++) - { - if (hour < 10) - cout << 0; - cout << hour << ":"; - if (min < 10) - cout << 0; - cout << min << endl; - } - } -}
\ No newline at end of file diff --git a/Sem. 03/Tasks and Solutions/12. ClockWithStart.cpp b/Sem. 03/Tasks and Solutions/12. ClockWithStart.cpp deleted file mode 100644 index 1b996e1..0000000 --- a/Sem. 03/Tasks and Solutions/12. ClockWithStart.cpp +++ /dev/null @@ -1,31 +0,0 @@ -#include <iostream> -using namespace std; - -int main() -{ - int h, m; - cin >> h >> m; - - for (int min = m + 1; min <= 59; min++) - { - if (h < 10) - cout << 0; - cout << h << ":"; - if (min < 10) - cout << 0; - cout << min << endl; - } - - for (int hour = h+1; hour <= 23; hour++) - { - for (int min = 0; min <= 59; min++) - { - if (hour < 10) - cout << 0; - cout << hour << ":"; - if (min < 10) - cout << 0; - cout << min << endl; - } - } -}
\ No newline at end of file diff --git a/Sem. 03/Tasks and Solutions/13. ClockWithStartAndEnd.cpp b/Sem. 03/Tasks and Solutions/13. ClockWithStartAndEnd.cpp deleted file mode 100644 index af39745..0000000 --- a/Sem. 03/Tasks and Solutions/13. ClockWithStartAndEnd.cpp +++ /dev/null @@ -1,41 +0,0 @@ -#include <iostream> -using namespace std; - -int main() -{ - int hStart, mStart, hEnd, mEnd; - cin >> hStart >> mStart >> hEnd >> mEnd; - - for (int min = mStart + 1; min <= 59; min++) - { - if (hStart < 10) - cout << 0; - cout << hStart << ":"; - if (min < 10) - cout << 0; - cout << min << endl; - } - - for (int hour = hStart+1; hour <= hEnd-1; hour++) - { - for (int min = 0; min <= 59; min++) - { - if (hour < 10) - cout << 0; - cout << hour << ":"; - if (min < 10) - cout << 0; - cout << min << endl; - } - } - - for (int min = 0; min < mEnd; min++) - { - if (hEnd < 10) - cout << 0; - cout << hEnd << ":"; - if (min < 10) - cout << 0; - cout << min << endl; - } -}
\ No newline at end of file diff --git a/Sem. 03/Tasks and Solutions/14. Frame.cpp b/Sem. 03/Tasks and Solutions/14. Frame.cpp deleted file mode 100644 index 92de3ca..0000000 --- a/Sem. 03/Tasks and Solutions/14. Frame.cpp +++ /dev/null @@ -1,30 +0,0 @@ -#include <iostream> -using namespace std; - -int main() -{ - int n; - cin >> n; - - //Ãîðíà ðàìêà - cout << '+'; - for (int i = 0; i < n - 2; i++) - cout << '-'; - cout << '+' << endl; - - - //Ñðåäà - for (int j = 0; j < n - 2; j++) - { - cout << '|'; - for (int i = 0; i < n - 2; i++) - cout << '-'; - cout << '|' << endl; - } - - //Äîëíà ðàìêà - cout << '+'; - for (int i = 0; i < n - 2; i++) - cout << '-'; - cout << '+' << endl; -}
\ No newline at end of file diff --git a/Sem. 03/Tasks and Solutions/tasks.pdf b/Sem. 03/Tasks and Solutions/tasks.pdf Binary files differdeleted file mode 100644 index 6c2ad50..0000000 --- a/Sem. 03/Tasks and Solutions/tasks.pdf +++ /dev/null diff --git a/Sem. 04/README.md b/Sem. 04/README.md deleted file mode 100644 index 9ce9f75..0000000 --- a/Sem. 04/README.md +++ /dev/null @@ -1,129 +0,0 @@ -**Десетична бройна система.** - -1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 , 12 - -Защото използваме 10 символа: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 - -Най-малката бройна система: **Единична бройна система (Unary)** - -Символи: 1 - -1 = 1 - -2 = 11 - -3 = 111 - -4 = 1111 - -5 = 11111 - -6 = 111111 - - -**Двоична бройна система (binary)** - -Символи: 0,1 - -0 - 00000 - -1 - 00001 - -2 - 00010 - -3 - 00011 - -4 - 00100 - -5 - 00101 - -6 - 00110 - -**Троична бройна система** - -Символи: 0, 1, 2 - -0 - 00 - -1 - 01 - -2 - 02 - -3 - 10 - -4 - 11 - -5 - 12 - -6 - 20 - - -Пребобрзвуане между бройни системи. - -**1. Десетична бройна система -> k-ична(k = 2(двоична), k = 3(троична), k = 10(десетична)) бройна система.** - -**Пример 1**: Преобразуване на числото 36 от десетична бройна система в двоична бройна система. - -Т.е k = 2. - -| | | %k | -|----|--------|----| -| | n = 36 | 0 | -| /k | 18 | 0 | -| /k | 9 | 1 | -| /k | 4 | 0 | -| /k | 2 | 0 | -| /k | 1 | 1 | -| /k | 0 | | - - -**Гледаме от долу нагоре - 100100** - -**Пример 2**: Преобразуване на числото 38 от десетична бройна система в троична бройна система. - -Т.е k = 3. - -| | | %k | -|----|--------|----| -| | n = 38 | 2 | -| /k | 12 | 0 | -| /k | 4 | 1 | -| /k | 1 | 1 | -| /k | 0 | | - -**Гледаме от долу нагоре - 1102** - -**1. k-ична бройна система -> десетична бройна система.** - -**Пример 3**: Преобразуване на числото 100100 от двоична бройна система в десетична бройна система. - -0*2^0 + 0*2^1 + 1*2^2 + 0*2^3 + 0*2^4 + 1*2^5 = 4 + 32 = 36 - -**Пример 4**: Преобразуване на числото 1102 от троична бройна система в десетична бройна система - -2*3^0 + 0*3^1 + 1*3^2 + 1*3^3 = 2 + 9 + 27 = 38. - - -Всяка една променлива има **фиксиран** размер - памет, която заема. - -int - 32 бита. бит - 0 или 1 - -sizeof(int) - > 4 размер в байтове. Байт = 8 бита. - -Първият бит в int-а определя знака. - -Минимална стойност на променлива от тип int: -2^31. - -Максимална стоиност на променлива от тип int: 2^31 - 1 - -Побитови операции: Виж **bitwise_examples.cpp** - -Побитови операции(задачи): - -**Задача 1**: Да се провери дали дадено число е четно или нечетно. - -**Задача 2**: Въвежда се числa n и k и да се определи стойността на k-тия бит.(Вход: 10, 2 (000..001010) Изход: 0) - -**Задача 3**: Въвежда се число n. Да се пресметне 2^n. - -**Задача 4**: Въвежда се число n. Да се пресметне числото закодирано в предпоследните 3 бита. diff --git a/Sem. 04/Task1.cpp b/Sem. 04/Task1.cpp deleted file mode 100644 index 78ea86d..0000000 --- a/Sem. 04/Task1.cpp +++ /dev/null @@ -1,14 +0,0 @@ -#include <iostream> -using namespace std; - -int main() -{ - int n; - cin >> n; - - if (n & 1 == 1) - cout << "Odd"; - else - cout << "Even"; - -}
\ No newline at end of file diff --git a/Sem. 04/Task2.cpp b/Sem. 04/Task2.cpp deleted file mode 100644 index a45a2e6..0000000 --- a/Sem. 04/Task2.cpp +++ /dev/null @@ -1,17 +0,0 @@ -#include <iostream> -using namespace std; - -int main() -{ - int n, k; - cin >> n >> k; - - int temp = 1; - temp = temp << k; - - if ((n & temp) == 0) - cout << "0"; - else - cout << "1"; - -}
\ No newline at end of file diff --git a/Sem. 04/Task3.cpp b/Sem. 04/Task3.cpp deleted file mode 100644 index 6e71c31..0000000 --- a/Sem. 04/Task3.cpp +++ /dev/null @@ -1,10 +0,0 @@ -#include <iostream> -using namespace std; - -int main() -{ - int n; - cin >> n; - - cout << (1 << n); -}
\ No newline at end of file diff --git a/Sem. 04/Task4.cpp b/Sem. 04/Task4.cpp deleted file mode 100644 index b0f5c04..0000000 --- a/Sem. 04/Task4.cpp +++ /dev/null @@ -1,10 +0,0 @@ -#include <iostream> -using namespace std; - -int main() -{ - int n; - cin >> n; - // 14 = 000...001110 - òàêà ñ "ïîáèòîâî è" ùå âçåìåì ñàìî òåçè 3 áèòà, à îñòàíàëèòå ùå áúäàò 0. Ïîñëå ãè ïðåìåñòâàìå äî íà÷àëîòî (èçïîëçâàéêè >>). - cout << ((n & 14) >> 1); -}
\ No newline at end of file diff --git a/Sem. 04/bitwise_examples.cpp b/Sem. 04/bitwise_examples.cpp deleted file mode 100644 index 5dd5684..0000000 --- a/Sem. 04/bitwise_examples.cpp +++ /dev/null @@ -1,20 +0,0 @@ -#include <iostream> -using namespace std; - -int main() -{ - int a = 13; // 000...01101 - int b = 20; // 000...10100 - - int r1 = a & b; // 000...00100(4) - int r2 = a | b; // 000...11101(29) - int r3 = a ^ b; // 000...11001(25) - int r4 = a >> 1;// 000...00110(6) - int r5 = b << 1;// 000..101000(40) - - std::cout << r1 << endl; - std::cout << r2 << endl; - std::cout << r3 << endl; - std::cout << r4 << endl; - std::cout << r5 << endl; -} diff --git a/Sem. 05/README.md b/Sem. 05/README.md deleted file mode 100644 index b65599b..0000000 --- a/Sem. 05/README.md +++ /dev/null @@ -1,18 +0,0 @@ -**Задача 1:** Въвежда се неотрицателно число n. Да се провери дали n е просто. - -**Задача 2:** Въвежда се неотрицателно число n. Да се отпечата неговото разбиване на прости множители. - -*Вход: 288, Изход: 2^5 * 3^2* - -**Задача 3:** Въвежда се неотрицателно число n. Пресметнете n + 1, използвайки само цикли и побитови операции. - -**Задача 4:** Въвеждат се неотрицателни числа n и k. Пресметнете n + k, използвайки само цикли и побитови операции. - -**Задача 5:** Въвеждат се неотрицателни числа n и k. Пресметнете n * k, използвайки само цикли и побитови операции. - -**Задача 6:** Всяко естествено число се представя по единствен начин като сума на **различни**(не се повтарят) степени на двойката. -Въвежда се естествено число n. Отпечатайте това разбиване на n. - -*Вход: 26, Изход: 2^1 + 2^3 + 2^4* - -*Вход: 15, Изход: 2^0 + 2^1 + 2^2 + 2^3* diff --git a/Sem. 05/Task 1.cpp b/Sem. 05/Task 1.cpp deleted file mode 100644 index 20ca708..0000000 --- a/Sem. 05/Task 1.cpp +++ /dev/null @@ -1,58 +0,0 @@ -#include <iostream> -using namespace std; - -int main() -{ - unsigned int n; - cin >> n; - - //Ðåøåíèå 1: - bool isPrime1 = true; - for (int i = 2; i <= n - 1; i++) - { - if (n % i == 0) - isPrime1 = false; - } - cout << isPrime1 << endl; - // Ðåøåíèåòî ðàáîòè. Íî ïðàâè èçëèøíè ïðîâåðêè. Íå å íåîáõîäèìî äà òúðñèì äåëèòåë ÷àê äî n-1. - // Àêî íå íàìåðèì äåëèòåë îò êîðåí(n), òî íÿìà äà íàìåðèì è ñëåä êîðåíà. - - //Ðåøåíèå 2: - bool isPrime2 = true; - for (int i = 2; i <= sqrt(n); i++) - { - if (n % i == 0) - isPrime2 = false; - } - cout << isPrime2 << endl; - - // Ðåøåíèåòî ïàê ðàáîòè. Íî íà âñÿêà ïðîâåðêà i <= sqrt(n) ïðåñìÿòàìå êîðåí(n), êîåòî å î÷åâèäíî, ÷å å èçëèøíî. - // Ìîæå äà ãî ñìåòíåì âåäíúæ è ïîñëå äà ãî ïîëçâàìå. - - //Ðåøåíèå 3: - bool isPrime3 = true; - double temp = sqrt(n); - for (int i = 2; i <= temp; i++) - { - if (n % i == 0) - isPrime3 = false; - } - cout << isPrime3 << endl; - - // È òîâà ðåøåíèå äàâà âåðåí ðåçóëòàò. Íî îòíîâî å âúçìîæíî äà ïðàâè èçëèøíè ïðîâåðêè. - // Ïðè âúâåæäàíå íà ÷èñëîòî 2000000, î÷åâèäíî áè áèëî, ÷å ÷èñëîòî ÍÅ å ïðîñòî, ïîíåæå ñå äåëè íà 2. - // Íî íàøåòî ðåøåíèå ùå ïðîäúëæè äà òúðñè äåëèòåëè, äîðè ñëåä êàòî å âèäÿëî, ÷å èìà òàêúâ (â ñëó÷àÿ ÷èñëîòî 2). - - //Ôèíàëíî ðåøåíèå: - bool isPrime4 = true; - double temp2 = sqrt(n); - for (int i = 2; i <= temp2; i++) - { - if (n % i == 0) - { - isPrime4 = false; - break; - } - } - cout << isPrime4 << endl; -}
\ No newline at end of file diff --git a/Sem. 05/Task 2.cpp b/Sem. 05/Task 2.cpp deleted file mode 100644 index 0f4408d..0000000 --- a/Sem. 05/Task 2.cpp +++ /dev/null @@ -1,39 +0,0 @@ -#include <iostream> -using namespace std; - -int main() -{ - unsigned int n; - cin >> n; - - for (int i = 2; n != 1; i++) //Âñè÷êè âúçìîæíè äåëèòåëè (ìíîæèòåëè) íà n 2,3,4,5,..., - { - // Ïðîâåðÿâàìå äàëè ÷èñëîòî å ïðîñòî (ïîíåæå íè èíòåðåñóâàò ñàìî ïðîñòè ìíîæèòåëè) - bool isPrime = true; - double temp = sqrt(i); - for (int j = 2; j <= temp; j++) - { - if (i % j == 0) - { - isPrime = false; - break; - } - } - - if (!isPrime) - continue; //Àêî íå å ïðîñòî - íå íè èíòåðåñóâà òîâà ÷èñëî. Ïðåìèíàâàìå êúì ñëåäâàùîòî. - - // Ùîì ñìå ñòèãíàëè òóê, ñìå óáåäåíè, ÷å i å ïðîñòî ÷èñëî. - // Èñêàìå äà âèäèì êîëêî ïúòè i äåëè n. - - int pow = 0; - while (n % i == 0) - { - n /= i; - pow++; - } - - if (pow != 0) //Àêî ïîíå âåäíúæ ãî å ðàçäåëèëî - çíà÷è ó÷àñòâà â ðàçáèâàíåòî íà ïðîñòè ìíîæèòåëè. - cout << i << "^" << pow << " "; - } -}
\ No newline at end of file diff --git a/Sem. 05/Task 3.cpp b/Sem. 05/Task 3.cpp deleted file mode 100644 index 6723ee2..0000000 --- a/Sem. 05/Task 3.cpp +++ /dev/null @@ -1,27 +0,0 @@ -#include <iostream> -using namespace std; - - -//Àëãîðèòúìúò çà ñúáèðàíå ñ 1 â äâîè÷åí çàïèñ: -//Îò äÿñíî íà ëÿâî - ïðàâèì âñè÷êè 1-öè íà 0, äîêàòî íå ñðåùíåì ïúðâàòà 0. -//Ïúðâàòà 0 ÿ ïðàâèì íà 1. - -// 101001111 + 1 -// 101010000 -int main() -{ - unsigned int n; - cin >> n; - - int mask = 1; //Íàé-äåñíèÿò áèò íà ìàñêàòà å 1-öà. Âñè÷êè äðóãè ñà 0-ëè. - - - while ((n & mask) > 0) //Ïðîâåðÿâàìå äàëè òåêóùèÿ áèò å 1-öà. (ïðè ïúðâîòî âëèçàíå, ïðîâåðÿâàìå íàé-äåñíèÿ) - { - n ^= mask; // Ïðàâèì ãî íà 0 ( n = n ^ mask) - mask <<= 1; // Îòìåñòâàìå ìàñêàòà, çà äà ïðîâåðèì áèò-à â ëÿâî. (mask = mask << 1) - } - - //Îòêðèëè ñìå ïúðâàòà 0. 1-öàòà å íà òî÷íàòà ïîçèöèÿ â ìàñêàòà. - n |= mask; // Ïðàâèì íà 1-öa (n = n | mask) -}
\ No newline at end of file diff --git a/Sem. 05/Task 4.cpp b/Sem. 05/Task 4.cpp deleted file mode 100644 index 6d57f92..0000000 --- a/Sem. 05/Task 4.cpp +++ /dev/null @@ -1,23 +0,0 @@ -#include <iostream> -using namespace std; - -int main() -{ - unsigned int n, k; - cin >> n >> k; - - - //Изпълняваме k пъти събирането на n с 1 - for (int i = 0; i < k; i++) - { - //Събираме n с 1-ца (кодът от миналата задача) - int mask = 1; - while ((n & mask) > 0) - { - n ^= mask; - mask <<= 1; - } - n |= mask; - } - cout << n << endl; -} diff --git a/Sem. 05/Task 5.cpp b/Sem. 05/Task 5.cpp deleted file mode 100644 index 6f3d0dd..0000000 --- a/Sem. 05/Task 5.cpp +++ /dev/null @@ -1,33 +0,0 @@ -#include <iostream> -using namespace std; - -int main() -{ - unsigned int n, k; - cin >> n >> k; - - //Ñìÿòàìå n*k. n+n+n...+n (k ïúòè). - //Ïðèëàãàìå êîäà îò ïðåäèøíàòà çàäà÷à k ïúòè - - - int result = 0; - - //Събирането с n го правим k пъти. Т.е става точно n*k - for (int t = 0; t < k; t++) - { - - //Събирането с 1 го правим пъти. Т.е става +n - for (int i = 0; i < n; i++) - { - //Събираме n с 1. - int mask = 1; - while ((result & mask) > 0) - { - result ^= mask; - mask <<= 1; - } - result |= mask; - } - } - cout << result << endl; -} diff --git a/Sem. 05/Task 6.cpp b/Sem. 05/Task 6.cpp deleted file mode 100644 index 415cae4..0000000 --- a/Sem. 05/Task 6.cpp +++ /dev/null @@ -1,19 +0,0 @@ -#include <iostream> -using namespace std; - -int main() -{ - unsigned int n; - cin >> n; - - int currentPosition = 0; - while (n != 0) - { - if (n % 2 == 1) //Проверяваме последния бит дали е 1. - { - cout << "2^" << currentPosition << " "; - } - currentPosition++; - n >>= 1; // Премахваме последния бит и предпоследния става последен (n /=2); - } -} diff --git a/Sem. 06/README.md b/Sem. 06/README.md deleted file mode 100644 index caea304..0000000 --- a/Sem. 06/README.md +++ /dev/null @@ -1,37 +0,0 @@ -**Задача 1:** Въвежда се неотрицателно число n. Да се отпечатат всички двойки прости числа, които са във вида 6k-1 и 6k+1. - -**Задача 2:** Напишете функция, която приема неотрицателно число n и връща числото обърнато - -*Вход: 288, Изход: 822* - -**Задача 3:** Напишете функция, която приема неотрицателно число и връща дали числото е палиндром. - -*Вход: 2882 Изход: true* - -**Задача 4:** Напишете функция, която приема неотрицателни числа n и k и връща дали k е суфикс на n. - -*Вход: 288, 88, Изход: true* - -**Задача 5:** Напишете функция, която приема неотрицателни числа n и k и връща дали k е префикс на n. - -*Вход: 288, 28, Изход: true* - -**Задача 6:** Напишете функция, която приема неотрицателни числа n и k и връща дали k се съдържа в n. - -*Вход: 2831, 83, Изход: true* - -**Задача 7:** Напишете функция, която приема неотрицателно число n и проверява дали има 4 последователни еднакви цифри. - -*Вход: 28777731 Изход: true* - -**Задача 8:** Напишете функция, която приема неотрицателно число и връща дали цифрите му са сортирани във възходящ ред. - -*Вход: 122239, Изход: true* - -**Задача 9:** Напишете функция, която приема неотрицателно число и връща дали цифрите му са сортирани в низходящ ред. - -*Вход: 99943, Изход: true* - -**Задача 10:** Напишете функция, която приема неотрицателно число и връща дали цифрите му са еднакви. - -*Вход: 111111, Изход: true* diff --git a/Sem. 06/Task_1(with functions).cpp b/Sem. 06/Task_1(with functions).cpp deleted file mode 100644 index db68d0d..0000000 --- a/Sem. 06/Task_1(with functions).cpp +++ /dev/null @@ -1,26 +0,0 @@ -#include <iostream> -using namespace std; - -bool isPrime(int number) -{ - double temp = sqrt(number); - for (int i = 2; i <= temp; i++) - { - if (number % i == 0) - return false; //Ñïèðà ôóíêöèÿòà è âðúùà îòãîâîð - ëúæà - } - return true; -} - -int main() -{ - int n; - cin >> n; - - for (int i = 6; i <= n; i += 6) - { - if (isPrime(i - 1) && isPrime(i + 1)) - cout << i - 1 << " " << i + 1 << endl; - } - -}
\ No newline at end of file diff --git a/Sem. 06/Task_1(without functions).cpp b/Sem. 06/Task_1(without functions).cpp deleted file mode 100644 index 9e5bcdb..0000000 --- a/Sem. 06/Task_1(without functions).cpp +++ /dev/null @@ -1,40 +0,0 @@ -#include <iostream> -using namespace std; - -int main() -{ - int n; - cin >> n; - - for (int i = 6; i <= n; i+=6) - { - int firstNumToCheck = i - 1, secondNumToCheck = i + 1; - - double temp = sqrt(firstNumToCheck); - bool isFirstNumPrime = true; - for (int j = 2; j <= temp; j++) - { - if (firstNumToCheck % j == 0) - { - isFirstNumPrime = false; - break; - } - } - - if (!isFirstNumPrime) - continue; - double temp2 = sqrt(secondNumToCheck); - bool isSecondNumPrime = true; - for (int j = 2; j <= temp2; j++) - { - if (secondNumToCheck % j == 0) - { - isSecondNumPrime = false; - break; - } - } - if (isSecondNumPrime) - cout << firstNumToCheck << " " << secondNumToCheck << endl; - } - -}
\ No newline at end of file diff --git a/Sem. 06/Tasks_2,3,4,5,6,7,8,9,10.cpp b/Sem. 06/Tasks_2,3,4,5,6,7,8,9,10.cpp deleted file mode 100644 index 1d9666d..0000000 --- a/Sem. 06/Tasks_2,3,4,5,6,7,8,9,10.cpp +++ /dev/null @@ -1,108 +0,0 @@ -#include <iostream> -using namespace std; - - -//Task 2 -unsigned int reverse(unsigned int number) -{ - int result = 0; - - while (number != 0) - { - int lastDigit = number % 10; - (result *= 10) += lastDigit; - number /= 10; - } - - return result; -} - -//Task 3 -bool isPalindrome(unsigned int n) -{ - return n == reverse(n); -} - -//Task 4 -bool isSuffix(unsigned int n, unsigned int k) -{ - if (n < k) - return false; - while (k != 0) - { - int lastDigitFromN = n % 10; - int lastDigitFromK = k % 10; - if (lastDigitFromN != lastDigitFromK) - return false; - n /= 10; - k /= 10; - } - return true; -} - -// Task 5 -bool isPrefix(unsigned int n, unsigned int k) -{ - return isSuffix(reverse(n), reverse(k)); -} - -// Task 6 -bool isInfix(unsigned int n, unsigned int k) -{ - if (k > n) - return false; - while (n >= k) - { - if (isSuffix(n, k)) - return true; - n /= 10; - } - return false; -} - -// Task 7 -bool hasConsecutiveFourDigits(unsigned int n) -{ - for (int i = 1111; i <= 9999; i+=1111) - { - if (isInfix(n, i)) - return true; - } - for (int i = 10000; i <= 90000; i += 10000) - { - if (isInfix(n, i)) - return true; - } - return false; -} - -// Task 8 -bool areDigitsSortedIncreasing(unsigned int n) -{ - while (n >= 10) - { - int lastDigit = n % 10; - int lastLastDigit = (n / 10) % 10; - - if (lastLastDigit > lastDigit) - return false; - n /= 10; // - } - return true; -} - -// Task 9 -bool areDigitsSortedDecreasing(unsigned int n) -{ - return areDigitsSortedIncreasing(reverse(n)); -} - -// Task 10 -bool areAllDigitsTheSame(unsigned int n) -{ - return areDigitsSortedIncreasing(n) && areDigitsSortedDecreasing(n); -} -int main() -{ - cout << areAllDigitsTheSame(777); -} diff --git a/Sem. 07/BullsAndColls.cpp b/Sem. 07/BullsAndColls.cpp deleted file mode 100644 index 2eb5d3c..0000000 --- a/Sem. 07/BullsAndColls.cpp +++ /dev/null @@ -1,96 +0,0 @@ -#include <iostream> -#include <stdlib.h> -using namespace std; - - -//Бикове и крави. -//Число: 1234 -//Предположение: 4253 - 2 крави (4 и 3) и 1 бик (2). - -bool hasDuplicateDigits(int n) ///1343 -{ - const int DIGITCOUNT = 10; - bool found[DIGITCOUNT]; - for (int i = 0; i < DIGITCOUNT; i++) - found[i] = false; - while (n != 0) - { - int lastDigit = n % 10; - if (found[lastDigit] == true) - return true; - else - found[lastDigit] = true; - n /= 10; - } - return false; -} - -void convertNumberToArr(int n, int arr[]) -{ - - for (int i = 3; i >= 0; i--) - { - arr[i] = n % 10; - n /= 10; - } - -} -int countBulls(int myNumber[], int compNumber[]) -{ - int bullsCount = 0; - for (int i = 0; i <= 3; i++) - { - if (myNumber[i] == compNumber[i]) - bullsCount++; - } - return bullsCount; -} -int countCows(int myNumber[], int compNumber[]) -{ - int cowsCount = 0; - - for (int i = 0; i <= 3; i++) - { - int myDigit = myNumber[i]; - for (int j = 0; j <= 3; j++) - { - if (j == i) // çà äà íå áðîèì áèêîâåòå - continue; - if (myDigit == compNumber[j]) - cowsCount++; - } - } - return cowsCount; -} -int main() -{ - int numberToGuess; - do - { - numberToGuess = 1000 + rand() % 9000; // [1000..9999] - } - while (hasDuplicateDigits(numberToGuess)); - - cout << "Computer has picked a number! Try to guess it!" <<endl; - int numberToGuessArr[4]; - - convertNumberToArr(numberToGuess, numberToGuessArr); - - int bullsCount = 0, cowsCount = 0; - do - { - int myNumber; - cin >> myNumber; - int myNumberArr[4]; - convertNumberToArr(myNumber, myNumberArr); - - bullsCount = countBulls(myNumberArr, numberToGuessArr); - cowsCount = countCows(myNumberArr, numberToGuessArr); - - cout << "Bulls: " << bullsCount << " Cows:" << cowsCount << endl; - - - } while (bullsCount != 4); - - cout << "Success!" << endl; -} diff --git a/Sem. 07/README.md b/Sem. 07/README.md deleted file mode 100644 index bae79b6..0000000 --- a/Sem. 07/README.md +++ /dev/null @@ -1,60 +0,0 @@ - - **Задача 1 (малък проект) :** Реализирайте играта **"Бикове и крави"**. Програмата ще генерира число и потребителят ще трябва да позне числото. - -# Масиви - -**Масивът** е наредена последователност от елементи от един тип. Отделен елемент на масива се достъпва посредством името на масива, последвано от поредния номер (индекс) на елемента в квадратни скоби - - - -## Инициализация на масиви - - ```c++ - int arr[6]; // Създава масив от 6 елемента, всеки от които е цяло число. - int arr2[] = {0, 1, 2, 3, 4, 5}; // Създава масив от 6 елемента. - int arr3[6] = {1,2,3}; //Останалите елементи се запълват с defaut-на стойност. - // Задължително големината на масива трябва да е константа, чиято стойност е ясна преди да - // се компилира програмата -``` - -## Достъп на елемент - - ```c++ - arr[3] = 44; //Присвоява на елементът на индекс 3 стойността 44. - cout << arr[2]; //Отпечатва на стандартния изход елементът на индекс 2 - //Индексацията на масивите в с++ започва от 0! -``` - - -## Извличане на размер на масив - - ```c++ - const int SIZE = 5; - int arr[SIZE]; - cout << sizeof(arr) / sizeof(int); - //Големината на масива я разделяме на големината на една променлива от този тип. -``` - - -## Подаване на масиви във функции - ```c++ - #include <iostream> - using namespace std; - void print(int arr[], int len) - { - for(int i = 0; i < len; i++) - { - cout << arr[i] << " "; - } - } - int main() - { - const int SIZE = 5; - int arr[SIZE] {1,2,3,4}; - - print(arr,SIZE); - - return 0; - } -``` - Масивите се подават във функциите по адрес! Т.е промените, които се правят върху масива във функцията, ще се отразят върху подадения като параметър масив! - diff --git a/Sem. 08/README.md b/Sem. 08/README.md deleted file mode 100644 index 367f048..0000000 --- a/Sem. 08/README.md +++ /dev/null @@ -1,7 +0,0 @@ -**Задача 1:** Да се реализира функция, която приема булев масив и връща числото, което е репрезентирано в него(в двоична бройна система). - -**Задача 2:** Да се реализира функция, която приема масив, в който всеки елемент се среща 2 пъти, с изключение на един елемент, който се среща точно веднъж. -Функцията да връща кой е този елемент. - - -**Задача 3:** Напишете функция, която приема масив връща дължината на най-дългият подмасив, който е палиндром. diff --git a/Sem. 08/task1.cpp b/Sem. 08/task1.cpp deleted file mode 100644 index b8c5943..0000000 --- a/Sem. 08/task1.cpp +++ /dev/null @@ -1,17 +0,0 @@ -#include <iostream> -using namespace std; - -const int SIZE = 32; - -int convert(bool arr[SIZE]) -{ - int result = 0; - for (int i = 31; i >= 0; i--) - result += arr[i] * (1 << 31-i); - return result; -} -int main() -{ - bool arr[SIZE] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1 }; - cout << convert(arr); -} diff --git a/Sem. 08/task2.cpp b/Sem. 08/task2.cpp deleted file mode 100644 index ecc9d74..0000000 --- a/Sem. 08/task2.cpp +++ /dev/null @@ -1,43 +0,0 @@ -#include <iostream> -using namespace std; - -const int SIZE = 30; -int countOccurrences(int arr[SIZE], int n, int el) -{ - int count = 0; - for (int i = 0; i < n; i++) - { - if (arr[i] == el) - count++; - } - return count; -} - -int getLonlyNumber(int arr[SIZE], int n) -{ - for (int i = 0; i < n; i++) - { - if (countOccurrences(arr, n, arr[i]) == 1) - return arr[i]; - } - return -1; - -} - -int getLonlyNumberBetter(int arr[SIZE], int n) -{ - int res = 0; - for (int i = 0; i < n; i++) - res ^= arr[i]; - return res; -} - -int main() -{ - int arr[SIZE]; - int n; - cin >> n; - for (int i = 0; i < n; i++) - cin >> arr[i]; - cout << getLonlyNumberBetter(arr, n); -} diff --git a/Sem. 08/task3.cpp b/Sem. 08/task3.cpp deleted file mode 100644 index a6b0ca9..0000000 --- a/Sem. 08/task3.cpp +++ /dev/null @@ -1,49 +0,0 @@ -#include <iostream> -using namespace std; - -const int SIZE = 30; -bool isSubarrayPalindrome(int arr[SIZE], int startIndex, int endIndex) -{ - while (startIndex < endIndex) - { - if (arr[startIndex] != arr[endIndex]) - return false; - startIndex++; - endIndex--; - } - return true; -} -void print(int arr[SIZE]) -{ - for (int i = 0; i < SIZE; i++) - cout << arr[i]; - cout << endl; -} - -int longestPalindromicSubarray(int arr[SIZE], int n) -{ - int currentSize = n; - - int startIndex = 0; - int endIndex = startIndex + currentSize-1; - while (true) - { - if (isSubarrayPalindrome(arr, startIndex, endIndex)) - return endIndex - startIndex + 1; - startIndex++; - endIndex++; - if (endIndex == n)//last iteration - { - currentSize--; - startIndex = 0; - endIndex = startIndex + currentSize - 1; - } - } -} -int main() -{ - - int arr[SIZE] = {1,4,3,2,3}; - cout << longestPalindromicSubarray(arr, 5); - -} diff --git a/Sem. 09/README.md b/Sem. 09/README.md deleted file mode 100644 index 51a6913..0000000 --- a/Sem. 09/README.md +++ /dev/null @@ -1,35 +0,0 @@ -- **Задача 1 (малък проект) :** Реализирайте играта **"Морски шах" (tic-tac-toe)**. Реализирайте програмата, така че да може смяната на големината на полето да става чрез промяната на стойността само на една константа. - -# Многомерни масиви - -Представляват масиви от масиви. - - - -## Инициализация на многомерни масиви - - ```c++ - int m1[2][3]; // Създава матрица с 2 реда и 3 колони. - int m2[2][3] = {{1, 2 ,3} , {4 ,5 , 6}}; //изреждаме редовете (те са елементите на масива) - int m3[2][3] = {1, 2, 3, 4, 5, 6}; //изреждаме елементите - - int arr[][3] = { 0, 0, 0, 4, 5, 6 }; // Пресмята колко реда трябва да е. - - int arr[3][0] = { 0, 0, 0, 4, 5, 6 }; // Грешка! - - int cube[3][3][3]; // Създава тримерен масив. -``` - -## Достъп на елемент - - ```c++ - m1[2][0] = 44; //Присвоява на елементът на ред с индекс 2 и колона с индекс 0 числото 44 - cout << m1[0][0]; //Отпечатва на стандартния изход елементът на индекси 0 0 -``` - -## Как се осъществява достъпът: - - ```c++ - m1[i][j] = 44;// адресът на m1 + i* sizeof(int)*rows_count + j* sizeof(int) -``` - diff --git a/Sem. 09/free_space_in_room.cpp b/Sem. 09/free_space_in_room.cpp deleted file mode 100644 index 532a5e1..0000000 --- a/Sem. 09/free_space_in_room.cpp +++ /dev/null @@ -1,72 +0,0 @@ -#include <iostream> -using namespace std; - -//Задача 2: - - -//Подадена е булева матрица. (Стая) -// 1- заета клетка -// 0- свободна клетка. -// 11111111 -// 11000001 -// 11000001 -// 11111111 - -// Подават ни обект(мебел) с размери n и k. -// Трябва да отпечатаме дали има място, където да поставим обекта - - -// Пример: -// В горния пример има къде да поставим обек 2x2, но няма къде да поставим обект 3x3 - - - -const int ROOM_SIZE_X = 4; -const int ROOM_SIZE_Y = 8; - -//Проверява дали има подматрица само със свободни клетки(само с 0-ли) с големина objXDim, objYDim -//където горният ляв ъгъл е на коодриднати upperLeftX и upperLeftY/ -bool hasFreeSpaceFromThisLeftUpCorner(bool room[ROOM_SIZE_X][ROOM_SIZE_Y], int objXDim, int objYDim, int upperLeftX, int upperLeftY) -{ - for (int i = 0; i < objXDim; i++) - { - for (int j = 0; j < objYDim; j++) - { - if (room[upperLeftX + i][upperLeftY + j] != 0) - return false; - } - } - return true; -} -bool hasSpace(bool room[ROOM_SIZE_X][ROOM_SIZE_Y], int objXDim, int objYDim) -//дали има подматрица само от 0-ли с размери objXDim x objYDim -{ - for (int i = 0; i < ROOM_SIZE_X - objXDim + 1; i++) - { - for (int j = 0; j < ROOM_SIZE_Y - objYDim + 1; j++) - { - //i,j - кандидат за горен ляв ъгъл на потенциално свободното пространство - if (hasFreeSpaceFromThisLeftUpCorner(room, objXDim, objYDim, i, j)) - { - //i,j са горен ляв ъгъл на достатъчно голямо свободно място за обект с рамери objXDim objYDim - - cout << "Free space found!" <<endl; - cout << "Corners:" << endl; - cout << i << " " << j<<endl; - cout << i + objXDim - 1 << " " << j << endl; - cout << i + objXDim-1 << " " << j + objYDim-1<<endl; - cout << i << " " << j + objYDim - 1 << endl; - return true; - } - } - } - return false; -} -int main() -{ - bool room[ROOM_SIZE_X][ROOM_SIZE_Y] = { { 1, 1, 1, 1, 1, 1, 1, 1 }, - { 1, 1, 0, 0, 0, 0, 0, 1 }, - { 1, 1, 0, 0, 0, 0, 0, 1 }, - { 1, 1, 1, 1, 1, 1, 1, 1 } }; - hasSpace(room, 2, 4); //Има ли къде да разположим мебел с размер 2x4 -} diff --git a/Sem. 09/tic-tac-toe.cpp b/Sem. 09/tic-tac-toe.cpp deleted file mode 100644 index d0e2aaf..0000000 --- a/Sem. 09/tic-tac-toe.cpp +++ /dev/null @@ -1,130 +0,0 @@ -#include <iostream> -using namespace std; - -//Зад1: Да се реализира играта tic-tac-toe -// Матрицата ще ни бъде от цели числа. Ще пазим следните стойности: -// [] = 0 (празна клетка) -// [x] = 1 -// [o] = -1 -const int TABLE_SIZE = 5; - -//Прави матрицата само от 0-ли (от празни клетки) -void init(int table[TABLE_SIZE][TABLE_SIZE]) -{ - for (int i = 0; i < TABLE_SIZE; i++) - { - for (int j = 0; j < TABLE_SIZE; j++) - { - table[i][j] = 0; - } - } -} - -//Дали не сме извън рамките на масива -bool areValidCoordinates(int x, int y) -{ - return x >= 1 && x <= TABLE_SIZE && y >= 1 && y <= TABLE_SIZE; -} - -//Дали клетката е свободна. Тук вече допускаме, че x и y са валидни координати. -bool isCellFree(int table[TABLE_SIZE][TABLE_SIZE], int x, int y) -{ - return table[x][y] == 0; -} - -//Проверяваме дали няма вече победител. -//el - кой проверяваме дали е победител (el = 1, значи проверяваме дали имаме последователност от TABLE_SIZE 1-ци.) -bool isWinner(int table[TABLE_SIZE][TABLE_SIZE], int el) -{ - for (int i = 0; i < TABLE_SIZE; i++) - { - //Проверка за редовете - bool isWinner = true; - for (int j = 0; j < TABLE_SIZE; j++) - { - if (table[i][j] != el) - isWinner = false; - } - if (isWinner) - return true; - - //Проверка за колоните - isWinner = true; - for (int j = 0; j < TABLE_SIZE; j++) - { - if (table[i][j] != el) - isWinner = false; - } - if (isWinner) - return true; - } - - //Проверка за главния диагонал - bool isWinner = true; - for (int i = 0; i < TABLE_SIZE; i++) - { - if (table[i][i] != el) - isWinner = false; - } - if (isWinner) - return true; - - //Проверка за второстепенния диагонал - isWinner = true; - for (int i = 0; i < TABLE_SIZE; i++) - { - if (table[i][TABLE_SIZE - 1 - i] != el) - isWinner = false; - } - return isWinner; -} -void print(int table[TABLE_SIZE][TABLE_SIZE]) -{ - for (int i = 0; i < TABLE_SIZE; i++) - { - for (int j = 0; j < TABLE_SIZE; j++) - { - cout << "["; - if (table[i][j] == -1) - cout << "o"; - else if (table[i][j] == 0) - cout << " "; - else - cout << "x"; - cout << "]"; - } - cout << endl; - } - cout << endl; -} -int main() -{ - int table[TABLE_SIZE][TABLE_SIZE]; - init(table); - - bool isFirstPlayersTurn = true; - print(table); - while (true) - { - cout << "It's player " << (isFirstPlayersTurn ? 1 : 2) << "\'s turn!"<<endl; - int x, y; - do - { - cin >> x >> y; - } while (!areValidCoordinates(x, y) || !isCellFree(table, x-1,y-1)); - // Първо проверяваме дали x и y са валидни индекси и САМО АКО СА, проверяваме дали клетката е свободна. - // Възползваме се, че при A || B, ако A е истина, не проверява стойността на B. - - int currentSymbol = isFirstPlayersTurn ? 1 : -1; - table[x - 1][y - 1] = currentSymbol; - - system("CLS"); //Изчиства всичко от конзолата. Работи само на Visual Studio. - print(table); - if (isWinner(table,currentSymbol)) - { - cout << "End game!"; - break; - } - isFirstPlayersTurn = !isFirstPlayersTurn; - } -} diff --git a/Sem. 10/pointers_basics.cpp b/Sem. 10/pointers_basics.cpp deleted file mode 100644 index e3c537a..0000000 --- a/Sem. 10/pointers_basics.cpp +++ /dev/null @@ -1,26 +0,0 @@ -#include <iostream> -using namespace std; - -const int SIZE = 5; -int main() -{ - int arr[SIZE] = {9,8,7,6,5}; //arr е променлива от тип const int* - int* ptr = arr; - - cout << arr << endl; // адресът на първата клетка в масива. - cout << ptr << endl; // същият адрес - - cout << *ptr <<endl; // Изкарва стойността на клетката, към която сочи указателят. (Тук това е 9) - cout << ptr[0] <<endl; // Отпечатва елементът на 0 отстъпа вдясно (тук пак това е 9) - cout << ptr[1] <<endl; // Отпечатва елементът на 1 отстъп вдясно (тук това е 8) - - ptr+=2; // "Премества" указателят 2 клетки надясно. - - cout << *ptr <<endl; // Изкарва стойността на клетката, към която сочи указателят. (Тук това е 7) - cout << ptr[0] <<endl; // Отпечатва елементът на 0 отстъпа вдясно (тук пак това е 7) - cout << ptr[1] <<endl; // Отпечатва елементът на 1 отстъп вдясно (тук това е 6) - - - - cout << *ptr <<endl; -} diff --git a/Sem. 10/strings.cpp b/Sem. 10/strings.cpp deleted file mode 100644 index bf0559f..0000000 --- a/Sem. 10/strings.cpp +++ /dev/null @@ -1,94 +0,0 @@ -#include <iostream> -using namespace std; - -// Низове (символни низове) стрингове - -// за да запазим текст с дължина k, ще ми трябват k+1 клетки -// k за текста и една клетка за \0; - - - -// Функцията ще променя ли масива? -// Ако не, винаги слагаме const! - -int stringLength(const char* str) -{ - int len = 0; - while (*str != '\0') - { - len++; - str++; - } - return len; -} - -int convertCharToDigit(char ch) -{ - return ch - '0'; -} - -//Фунцкия, която приема низ и го конверира в число, ако е възможно -// "345" ->345 -// "3456" -> 3456 -int convertFromString(const char* str) -{ - int len = stringLength(str); - int multiPl = 1; - - int result = 0; - for (int i = len - 1; i >= 0; i--) - { - result += multiPl * convertCharToDigit(str[i]); - multiPl *= 10; - } - return result; -} - -int min(int a, int b) -{ - return a < b ? a : b; -} -// Функция, която сравнява лексикографски 2 низа: -// - ако str1<str2 -// 0 ако str1 = str2 -// + ако str1>str2 -int stringCompare(const char* str1,const char* str2) -{ - int len1 = stringLength(str1); - int len2 = stringLength(str2); - int minLen = min(len1, len2); - - for (int i = 0; i < minLen; i++) - { - int diff = str1[i] - str2[i]; - if (diff != 0) - return diff; //Двата символа са различни. Връщаме кой е "по-малък". - } - //Ако е свършил цикълът, никъде няма разлика в символите. - if (len1 != len2) - return len1 - len2; - //Няма разлика в символите и няма разлика в дължините. - return 0; -} - -// Конкатенация на два низа. -void stringConcat(char* dest, const char* source) -{ - int destLength = stringLength(dest); - int sourceLength = stringLength(source); - - for (int i = 0; i <= sourceLength; i++) // Тук използваме <= за да вземем и терминиращата нула от source. - dest[destLength + i] = source[i]; -} - -const int LEN = 300; -int main() -{ - - char str[LEN] = "Test1"; - char str2[LEN] = "Test2"; - - stringConcat(str, str2); - cout << str2 << endl; - -} diff --git a/Sem. 11/README.md b/Sem. 11/README.md deleted file mode 100644 index b82c95e..0000000 --- a/Sem. 11/README.md +++ /dev/null @@ -1,35 +0,0 @@ -# Домашна работа - Мinesweeper - -Да се реализира в **конзолна** играта **Мinesweeper**. -Целта на играта е да се разкрият всички квадратчета, които не съдържат мини , без да щракнем върху мина преди това. Разположението на мините може да се разбере логически, с помощта на цифрички, стоящи се на местата на квадратчетата след щракане върху тях. Цифрите показват колко квадратчета, в които има мини, има в съседство. Ако се щракне върху квадратче, което няма мини (стои числото 0) в съседство, то разкрива съседните, ако някое от тези разкрити също няма мини в съседство, то също разкрива съседните квадратчета и тн... - -Пример: - - - -[Онлайн версия на играта](http://minesweeperonline.com/#) - - -**Забележка: От вас не се изисква създаването на графичен интерфейс. Играта трябва да бъде конзолна апликация.** - -В конзолата трябва да изпълнявате команди от вида: - -> [command] [x coordinate] [y coordinate] - -Където [command] е **open**, **mark** или **unmark**, а след него стоят координатите на квадратчето. - - - **open** - отваря квадратчето. Ако там седи мина - край на играта! - - **mark** - маркира квадратчето като "мина". Ако всички мини са маркирани - и всички други квардратчета са отворени, играта прилкючва с успех! - - **unmark** - отмаркира квадрачето като "мина". Ако квадратчето не е било - маркирано, то се извежда подходящо съобщение за грешка. - -При започването на играта, потребителят трябва да може да избере на каква размерност да играе (3 <= N <= 10). След това трябва да избере колко мини да бъдат "скрити". -Броят трябва да е в интервала [1, 3N]. Ако някои от стойностите не са въведат правилно от потребителя, то трябва да се изведе подходящо съобщение и да бъде "приканен" да въведе отново. - -Краен срок: **09.01.2021** - -**П.С.:** Това беше моя курсова работа в първи курс. Кодът съм го загубил, но съм ви качил конзолното приложение **(homework_example/MineSweeper.zip)**. -Можете да го свалите и да го ползвате като ориентир. В моята програма има и един бъг (ако я разцъкате, ще го забележите), който не мога да оправя (понеже нямам кода вече). - - diff --git a/Sem. 11/array_algorithms.cpp b/Sem. 11/array_algorithms.cpp deleted file mode 100644 index ed8d664..0000000 --- a/Sem. 11/array_algorithms.cpp +++ /dev/null @@ -1,134 +0,0 @@ -#include <iostream> -using namespace std; -// Алгоритми върху масиви. -// Пример за алгормитъм. -// Функция, която търси елемент в масив. -// Search arr, el -> -// -1 ako go nqma, + ako go ima -> indeksa - - -int linearSearch(const int* arr, int len, int searched) -{ - for (int i = 0; i < len; i++) - { - if (arr[i] == searched) - return i;//връщаме индекса. - } - return -1;//елементът го няма -} -// Анализ - кога тези алгоритми са "бързи" и кога са "бавни". -// Сложност на алгоритъм - колко стъпки ще направи алгоритъма. -// Приемаме, че масивът е с n елемента. -// best-case: 1 стъпка O(1) -// average-case: n/2 стъпки. O(n) -// worst-case: n стъпки. O(n) - -// зад 2) Търсене в масив. Масивът е сортиран. - -// Двоично търсене (binary search). -// -int binarySearch(const int* arr, int len, int searched) -{ - int leftIndex = 0; - int rightIndex = len - 1; - while (leftIndex <= rightIndex) - { - int midIndex = (leftIndex + rightIndex) / 2; - if (arr[midIndex] == searched) - return midIndex; - if (arr[midIndex] > searched) - rightIndex = midIndex - 1; - else - leftIndex = midIndex + 1; - } - return -1; - -} -// best-case: 1 стъпка O(1) -// average-case: O(log(n)) -// worst-case: O(log(n)) -// Сортиран масив с 70000 елемента -> линейно търсене (70000 стъпки) -// -> двоично търсене (16 стъпки) - - - - -//Сортиране на масив. -// Пример: 9 6 3 7 -> 3 6 7 9 - -// Bubble sort (Сортиране по метода на мехурчето) - -// "Разходка по масива" -// -void swap(int* arr, int i, int j) -{ - int temp = arr[i]; - arr[i] = arr[j]; - arr[j] = temp; -} - -//След една разходка най-големият елемент ще отиде на мястото си. -// след разходка 2-> 2-та най-големи елемента ще са на мясотот си -// след разходка 3-> 3-те ... -//Ако след една разходка, не направим нито един swap, то следва че масивът вече е сортиран. -void bubbleSort(int* arr, int len) -{ - for (int j = 0; j < len - 1; j++) - { - bool isSwapped = false; - for (int i = 0; i < len - 1 - j; i++) - { - if (arr[i] > arr[i + 1]) - { - swap(arr, i, i + 1); - isSwapped = true; - } - } - if (!isSwapped) - return; - } -} - -//Сложност: -// best-case: O(n) -// average-case: O(n^2) -// worst-case: n*(n-1) /2 = (n^2 + n )/2 O(n^2) - -// Стабилност: (следващият път) - - - -// Selection sort (сортиране чрез пряка селекция). -// 5 8 1 4 9 - -void selectionSort(int* arr, int len) -{ - for (int pos = 0; pos < len - 1; pos++) - { - int minIndex = pos; - for (int i = pos; i < len; i++) - { - if (arr[i] < arr[minIndex]) - minIndex = i; - } - if (pos != minIndex) - swap(arr, pos, minIndex); - } -} - -// Сложност: -// best-case: O(n^2) -// average-case: O(n^2) -// worst-case: О(n^2) - -// Selection sort прави минимален брой swap-ове. - - -int main() -{ - int arr[] = {5,3,2,6,1,4}; - selectionSort(arr, 6); - for (int i = 0; i < 6; i++) - cout << arr[i] << " "; - //cout << binarySearch(arr, 10, 500); -} diff --git a/Sem. 11/homework_example/MineSweeper.zip b/Sem. 11/homework_example/MineSweeper.zip Binary files differdeleted file mode 100644 index 7649e37..0000000 --- a/Sem. 11/homework_example/MineSweeper.zip +++ /dev/null diff --git a/Sem. 12/README.md b/Sem. 12/README.md deleted file mode 100644 index 1246379..0000000 --- a/Sem. 12/README.md +++ /dev/null @@ -1,29 +0,0 @@ -**Задача 1:** Напишете функция, която приема стринг и връща нов стринг, в който са премахнати всички цифри от първия стринг. -Новият стринг да е с точна дължина. - -**Пример:** - -**Вход:** "ivan454sdd" - -**Изход:** "ivanssd" - -**Задача 2:** Да се реализира функция, която приема масив, в който всеки елемент се среща 2 пъти, с изключение на един елемент, който се среща точно веднъж. -Функцията да връща кой е този елемент. - -**Пример:** - -**Вход:** [3, 5, 6, 5, 3, 7, 8, 8, 7] - -**Изход:** 6 - -**Задача 3:** Напишете функция, която примема стринг A, стринг X и приема и стринг Y и замества всяко срещане на X в А с Y. -Новият стринг да е с точна дължина. - -**Пример:** -A = "hello friends! You are my best friend. I have no other friends!" - -X = "friend" - -Y = "enemy" - -**Резултат:** "hello enemys! You are my best enemy. I have no other enemys!" diff --git a/Sem. 12/dynamic_memory.cpp b/Sem. 12/dynamic_memory.cpp deleted file mode 100644 index 6d45a1d..0000000 --- a/Sem. 12/dynamic_memory.cpp +++ /dev/null @@ -1,27 +0,0 @@ -#include <iostream> -using namespace std; - -int main() -{ - int arr[3]; //големината на тези масиви трябва да е ясна ПРЕДИ да се компилира програмата - //паметта за стека трябва да се задели преди да тръгне програмата - if (true) - { - int num = 10; - num++; - } - //num++; //стекът сам си "чисти" паметта. Променливата num не съществува. - - int n; - cin >> n; - int* arr = new int[n];// Тук n е променлива - стойността и НЕ е ясна преди да тръгне програмата! - - /*if (true) - { - arr = new int[2*n] // Отечка на памет (memory leak).Не е изтрита паметта, към която сочи arr. - }*/ - delete[] arr; - //За всяко едно new трябва да имаме едно delete. - //Уговаряме се, че ЩЕ БЪДЕ В СЪЩАТА ФУНЦКИЯ. - //Т.е няма да заделяме памет в една функция и да я освобождаваме в друга! -} diff --git a/Sem. 12/references.cpp b/Sem. 12/references.cpp deleted file mode 100644 index 5922d33..0000000 --- a/Sem. 12/references.cpp +++ /dev/null @@ -1,22 +0,0 @@ -#include <iostream> -using namespace std; - -void f(int a) -{ - a += 5; - -} -void f2(int& a) -{ - a += 5; -} - -int main() -{ - int x = 10; - f(x); - cout << x << endl; //10 - - f2(x); - cout << x << endl; //15 -} diff --git a/Sem. 12/task1.cpp b/Sem. 12/task1.cpp deleted file mode 100644 index 1698c33..0000000 --- a/Sem. 12/task1.cpp +++ /dev/null @@ -1,54 +0,0 @@ -#include <iostream> -using namespace std; - -bool isDigit(char ch) -{ - return ch >= '0' && ch <= '9'; -} -int countDigits(const char* str) -{ - //int len = strlen(str); - //int count = 0; - //for (int i = 0; i < len; i++) - //{ - // if (isDigit(str[i])) - // count++; - //} - - int count = 0; - while (*str != '\0') - { - if (isDigit(*str)) - count++; - str++; - } - return count; -} - -void removeDigits(const char* str, char* resultStr) -{ - while (*str != '\0') - { - if (!isDigit(*str)) - { - *resultStr = *str; - resultStr++; - } - str++; - } - *resultStr = '\0'; -} -int main() -{ - const char* str = "hello friends 123 , how are you? 343. Fine!"; - - int len = strlen(str) - countDigits(str); - - char* resultStr = new char[len + 1]; - - removeDigits(str, resultStr); - - cout << resultStr << endl; - - delete[] resultStr; -}
\ No newline at end of file diff --git a/Sem. 12/task3.cpp b/Sem. 12/task3.cpp deleted file mode 100644 index ba0ba1b..0000000 --- a/Sem. 12/task3.cpp +++ /dev/null @@ -1,89 +0,0 @@ -#include <iostream> -using namespace std; - -int search(const char* string, const char* searched); - -void replace(const char* string, const char* x, const char* y, char* result) -{ - int yLen = strlen(y); - int xLen = strlen(x); - while (true) - { - int indX = search(string, x); //14 - if (indX == -1) - break; - - - for (int i = 0; i < indX; i++) - result[i] = string[i]; - result += indX; - string += indX + xLen; - - for (int i = 0; i < yLen; i++) - result[i] = y[i]; - result += yLen; - } - - //the rest symbols - while (*string != '\0') - { - *result = *string; - result++; - string++; - } - *result = '\0'; - -} - -//return the first index of searched in str. -int search(const char* str, const char* searched) -{ - int len1 = strlen(str); - int len2 = strlen(searched); - for (int i = 0; i < len1 - len2+1; i++) - { - bool found = true; - for (int j = 0; j < len2; j++) - { - if (searched[j] != str[i + j]) - { - found = false; - break; - } - } - if (found) - return i; - } - return -1; -} -int countOccurrences(const char* str, const char* searched) -{ - int count = 0; - - int searchLen = strlen(searched); - int ind = search(str, searched); - while (ind != -1) - { - count++; - str += (ind + searchLen); - ind = search(str, searched); - } - return count; -} -int main() -{ - const char* str = "hello friends! You are my best friends. I have no other friends"; - const char* x = "friend"; - const char* y = "enemy"; - - int len = strlen(str); - int xOccurrences = countOccurrences(str, x); - - char* result = new char[len - xOccurrences*strlen(x) + xOccurrences*strlen(y) + 1]; - - replace(str, x, y, result); - - cout << result << endl; - - delete[] result; -}
\ No newline at end of file diff --git a/Sem. 12/tesk2.cpp b/Sem. 12/tesk2.cpp deleted file mode 100644 index e41c069..0000000 --- a/Sem. 12/tesk2.cpp +++ /dev/null @@ -1,56 +0,0 @@ -#include <iostream> -using namespace std; - -bool isSymbol(char ch) -{ - return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z'); -} -bool isVowel(char ch) -{ - switch (ch) - { - case 'A': - case 'O': - case 'I': - case 'U': - case 'E': - case 'a': - case 'o': - case 'i': - case 'u': - case 'e':return true; - } - return false; -} -void countVowelAndCons(const char* str, int& vowelCount, int& consCount) -{ - while (*str != '\0') - { - if (isSymbol(*str)) - { - if (isVowel(*str)) - vowelCount++; - else - consCount++; - } - str++; - } -} - -bool isBalanced(const char* str) -{ - int vowelCount = 0, consCount = 0; - - countVowelAndCons(str, vowelCount, consCount); - - return vowelCount == consCount; -} - -int main() -{ - const char* str = "TestMeau"; - - cout << isBalanced(str) << endl; - - -} diff --git a/Sem. 13/README.md b/Sem. 13/README.md deleted file mode 100644 index be7432c..0000000 --- a/Sem. 13/README.md +++ /dev/null @@ -1,15 +0,0 @@ -**Çàäà÷à 1:** Äà ñå ðåàëèçèðà ðåêóðñèâíà ôóíêöèÿ, êîÿòî ïðåñìÿòà n! - -**Çàäà÷à 2:** Äà ñå ðåàëèçèðà ðåêóðñèâíà ôóíêöèÿ, êîÿòî ïðåñìÿòà n-òîòî ÷èñëî íà ôèáîíà÷è. - -**Çàäà÷à 3:** Äà ñå ðåàëèçèðà ðåêóðñèâíà ôóíêöèÿ, êîÿòî âäèãà ÷èñëî íà äàäåíà ñòåïåí. - -**Çàäà÷à 4:** Äà ñå ðåàëèçèðà ðåêóðñèâíà ôóíêöèÿ, êîÿòî ïðèåìà ìàñèâ îò öåëè ÷èñëà è âðúùà ñóìàòà íà åëåìåíòèòå â íåãî. - -**Çàäà÷à 5:** Äà ñå ðåàëèçèðà ðåêóðñèâíà ôóíêöèÿ, êîÿòî ïðèåìà **ïðîèçâîëåí** ìàñèâ è ÷èñëî è âðúùà äàëè ÷èñëîòî ñå ñúäúðæà â ìàñèâà. (Ëèíåéíî òúðñåíå). - -**Çàäà÷à 6:** Äà ñå ðåàëèçèðà ðåêóðñèâíà ôóíêöèÿ, êîÿòî ïðèåìà **ñîðòèðàí** ìàñèâ è ÷èñëî è âðúùà äàëè ÷èñëîòî ñå ñúäúðæà â ìàñèâà. (Äâîè÷íî òúðñåíå). - -**Çàäà÷à 7:** Äà ñå ðåàëèçèðà ðåêóðñèâíà ôóíêöèÿ, êîÿòî ïðèåìà ñòðèíã è âðúùà äàëè ñòðèíãúò å ïàëèíäðîì. - -**Çàäà÷à 8:** Äà ñå ðåàëèçèðà ðåêóðñèâíà ôóíêöèÿ, êîÿòî ïðèåìà ìàñèâ îò öåëè ÷èñëà è âðúùà íàé-ãîëåìèÿò åëåìåíò â ìàñèâà. diff --git a/Sem. 13/task1.cpp b/Sem. 13/task1.cpp deleted file mode 100644 index bd2ce93..0000000 --- a/Sem. 13/task1.cpp +++ /dev/null @@ -1,15 +0,0 @@ -#include <iostream> -using namespace std; - -unsigned fact(unsigned n) -{ - if (n == 0) - return 1; - - return n * fact(n - 1); -} - -int main() -{ - cout << fact(5); -}
\ No newline at end of file diff --git a/Sem. 13/task2.cpp b/Sem. 13/task2.cpp deleted file mode 100644 index 39f69ad..0000000 --- a/Sem. 13/task2.cpp +++ /dev/null @@ -1,14 +0,0 @@ -#include <iostream> -using namespace std; - -unsigned fibb(unsigned n) -{ - if (n == 0 || n == 1) - return 1; - return fibb(n - 1) + fibb(n - 2); -} - -int main() -{ - cout << fibb(5); -}
\ No newline at end of file diff --git a/Sem. 13/task3.cpp b/Sem. 13/task3.cpp deleted file mode 100644 index a17bdb0..0000000 --- a/Sem. 13/task3.cpp +++ /dev/null @@ -1,14 +0,0 @@ -#include <iostream> -using namespace std; - -unsigned power(unsigned n, unsigned k) -{ - if (k == 0) - return 1; - return n * power(n, k - 1); -} - -int main() -{ - cout << power(2,7); -}
\ No newline at end of file diff --git a/Sem. 13/task4.cpp b/Sem. 13/task4.cpp deleted file mode 100644 index e69de29..0000000 --- a/Sem. 13/task4.cpp +++ /dev/null diff --git a/Sem. 13/task5.cpp b/Sem. 13/task5.cpp deleted file mode 100644 index 5e38f28..0000000 --- a/Sem. 13/task5.cpp +++ /dev/null @@ -1,16 +0,0 @@ -#include <iostream> -using namespace std; - -int sum(const int* arr, int len) -{ - if (len == 0) - return 0; - - return arr[0] + sum(arr+1, len - 1); -} - -int main() -{ - int arr[] = { 1, 2, 2, 6 }; - cout << sum(arr,4); -}
\ No newline at end of file diff --git a/Sem. 13/task6.cpp b/Sem. 13/task6.cpp deleted file mode 100644 index 121cc9b..0000000 --- a/Sem. 13/task6.cpp +++ /dev/null @@ -1,15 +0,0 @@ -#include <iostream> -using namespace std; - -bool LinearSearch(const int* arr, int len, int searched) -{ - if (len == 0) - return false; - return arr[0] == searched || LinearSearch(arr + 1, len - 1, searched); -} - -int main() -{ - int arr[] = { 17, 1, 2, 2, 6 }; - cout << LinearSearch(arr, 5, 17); -}
\ No newline at end of file diff --git a/Sem. 13/task7.cpp b/Sem. 13/task7.cpp deleted file mode 100644 index c90cf32..0000000 --- a/Sem. 13/task7.cpp +++ /dev/null @@ -1,23 +0,0 @@ -#include <iostream> -using namespace std; - -bool BinarySearch(const int* arr, int len, int searched) -{ - if (len == 0) - return false; - - int midIndex = len / 2; - - if (arr[midIndex] == searched) - return true; - if (arr[midIndex] < searched) - return BinarySearch(arr + midIndex + 1, len - midIndex - 1, searched); - else - return BinarySearch(arr, midIndex, searched); -} - -int main() -{ - int arr[] = { 1, 2, 2, 6, 19, 55 }; - cout << BinarySearch(arr, 6, 19); -}
\ No newline at end of file diff --git a/Sem. 13/task8.cpp b/Sem. 13/task8.cpp deleted file mode 100644 index a22d3b7..0000000 --- a/Sem. 13/task8.cpp +++ /dev/null @@ -1,20 +0,0 @@ -#include <iostream> -using namespace std; - -int max(int a, int b) -{ - return a > b ? a : b; -} - -int max(const int* arr, int len) -{ - if (len == 1) - return arr[0]; - return max(arr[0], max(arr + 1, len - 1)); -} - -int main() -{ - int arr[] = { 1, 2, 2,-4,-6 }; - cout << max(arr, 5); -}
\ No newline at end of file diff --git a/Sem. 14/README.md b/Sem. 14/README.md deleted file mode 100644 index 3288722..0000000 --- a/Sem. 14/README.md +++ /dev/null @@ -1,16 +0,0 @@ -**Задача 1:** Да се реализира рекурсивна функция, която пресмята биномен коефициент. - -**Задача 2:** Да се напише рекурсивна функция, която пресмята броя единиците и броя на нулите на дадено число. - -**Задача 3:** Дадено е поле под формата масив от цели числа. Стойнстта на всяка клетка означава колко голям "скок" можем да направим от тази клетка в друга -наляво или надясно. Напишете функция, която връща дали може да стигнем от началото до края на масива. - -**Задача 4:** Дадено ни е число n и n елемента на масив (от естествени числа). Напишете рекурсивна функция, която провеява дали в масива се съдържат първите n четни числа (точно веднъж). - -**Задача 5:** Въвеждат се две изречения (с макс дължина 1024). Да се напише функция, която проверява дали изреченията са от еднакви думи (между думите може да има произволен брой интервали). - -**Задача 6:** Даден е правоъгълник с размери NxM. Да се напише функция, която връща дали правоъгълникът може да бъде покрит с плочки 1x2 и 3x1. - -**Задача 7:** Дадено е изречение. Да се реализира функция, която обръща реда на думите в изречението. - - Пример: **Вход**: "How are you friends. I am fine!", **Изход**: "fine! am I friends. you are How" diff --git a/Sem. 14/task1.cpp b/Sem. 14/task1.cpp deleted file mode 100644 index 01d4eb9..0000000 --- a/Sem. 14/task1.cpp +++ /dev/null @@ -1,16 +0,0 @@ -#include <iostream> -using namespace std; - -unsigned binom(unsigned n, unsigned k) -{ - if (n < k) - return 0; - if (n == k || k == 0) - return 1; - return binom(n - 1, k) + binom(n - 1, k - 1); -} - -int main() -{ - -}
\ No newline at end of file diff --git a/Sem. 14/task2.cpp b/Sem. 14/task2.cpp deleted file mode 100644 index f22e9ae..0000000 --- a/Sem. 14/task2.cpp +++ /dev/null @@ -1,25 +0,0 @@ -#include <iostream> -using namespace std; - -void countBinaryElements(unsigned n, unsigned& zeros, unsigned& ones) -{ - if (n == 0) - return; - - int lastBit = n % 2; - if (lastBit == 1) - ones++; - else if (lastBit == 0) - zeros++; - countBinaryElements(n >> 1, zeros, ones); - -} -int main() -{ - int n; - cin >> n; - - unsigned ones = 0, zeros = 0; - countBinaryElements(n, ones, zeros); - cout << ones << " " << zeros; -}
\ No newline at end of file diff --git a/Sem. 14/task3.cpp b/Sem. 14/task3.cpp deleted file mode 100644 index 5df4d01..0000000 --- a/Sem. 14/task3.cpp +++ /dev/null @@ -1,35 +0,0 @@ -#include <iostream> -using namespace std; - -bool checkIfPathExists(const int* field, bool* visited, int len, int pos) -{ - if (pos < 0 || pos >= len || visited[pos]) //out of bounds - return false; - if (pos == len - 1) - return true; - - visited[pos] = true; - - int value = field[pos]; - - return checkIfPathExists(field, visited, len, pos - value) || checkIfPathExists(field, visited, len, pos + value); - -} - -int main() -{ - int n; - cin >> n; //ãîëåìèíàòà íà ìàñèâà. - int* field = new int[n]; - bool* visited = new bool[n]; - - for (int i = 0; i < n; i++) - { - cin >> field[i]; - visited[i] = false; - } - - cout << checkIfPathExists(field, visited, n, 0); - - delete[] field, visited; -} diff --git a/Sem. 14/task4.cpp b/Sem. 14/task4.cpp deleted file mode 100644 index b48b521..0000000 --- a/Sem. 14/task4.cpp +++ /dev/null @@ -1,32 +0,0 @@ -#include <iostream> -using namespace std; - -bool checkIfContainsFirstNEvenNumbers(const unsigned* arr, bool* visited, int len, int n) -{ - if (len == 0) - return true; //all values in visited should be true - - int currentNumber = arr[0]; - if (currentNumber % 2 != 0 || currentNumber > 2 * n - 2 || visited[currentNumber / 2]) - return false; - - visited[currentNumber / 2] = true; - - return checkIfContainsFirstNEvenNumbers(arr + 1, visited, len - 1, n); - -} -int main() -{ - int n; - cin >> n; - unsigned* arr = new unsigned[n]; - bool* visited = new bool[n]; - for (int i = 0; i < n; i++) - { - cin >> arr[i]; - visited[i] = false; - } - - cout << checkIfContainsFirstNEvenNumbers(arr, visited, n, n); - delete[] arr, visited; -}
\ No newline at end of file diff --git a/Sem. 14/task5.cpp b/Sem. 14/task5.cpp deleted file mode 100644 index 4301cee..0000000 --- a/Sem. 14/task5.cpp +++ /dev/null @@ -1,110 +0,0 @@ -#include <iostream> -using namespace std; - - -const int MAX_LEN = 1024; - -//returns -1 if searched is not found in str. returns the index otherwise. -int contains(const char* str, const char* searched) -{ - int len1 = strlen(str); - int len2 = strlen(searched); - for (int i = 0; i < len1 - len2 + 1; i++) - { - bool found = true; - for (int j = 0; j < len2; j++) - { - if (searched[j] != str[i + j]) - { - found = false; - break; - } - } - if (found) - return i; - } - return -1; -} -bool containsOnlyWhiteSpaces(const char* str) -{ - while (*str != '\0') - { - if (*str != ' ') - return false; - str++; - } - return true; -} -void makeSpaces(char* str, int startIndex, int spacesCount) -{ - for (int i = startIndex; i < startIndex + spacesCount; i++) - str[i] = ' '; -} -bool hasSameWords(const char* sentence1, const char* sentence2) -{ - int len1 = strlen(sentence1); - int len2 = strlen(sentence2); - - char* s1 = new char[len1 + 1]; - char* s2 = new char[len2 + 1]; - - char* s1Original = s1;// we change s1. So we could delete the whole array - - strcpy(s1, sentence1); - strcpy(s2, sentence2); - - - for (int i = 0; i <= len1; i++) - { - if (s1[i] != ' ' &&s1[i] != '\0' ) - continue; - //we are here if we found a space (or a \0 which means it's the last word). - - - //if the space is at the begining, there is not a word before it. So we just remove it. - if (i == 0) - { - s1 += 1; - len1--; - i = -1; // so it could become 0 for the next iteration - continue; - } - - char* currentWord = new char[i + 1]; - - s1[i] = '\0'; - strcpy(currentWord, s1); - - if (i != len1) //if it's not the last word (because after the last word there is an '\0'). - s1[i] = ' '; - - int res = contains(s2, currentWord); - if (res == -1) - return false; - - //we make the matched word as whitespaces. - makeSpaces(s1, 0, i); - makeSpaces(s2, res, i); - - //we move the pointer to continue with the sentense. - s1 += i; - len1 -= i; - - i = -1; // so it could become 0 for the next iteration - delete[] currentWord; - } - - bool res = containsOnlyWhiteSpaces(s1Original) && containsOnlyWhiteSpaces(s2); - delete[] s1Original, s2; - return res; -} -int main() -{ - char sentence1[MAX_LEN]; - char sentence2[MAX_LEN]; - - //cin.getline(sentence1, MAX_LEN); - //cin.getline(sentence2, MAX_LEN); - - cout << hasSameWords("hello friends bye enemy", "bye friends hello enemy"); -} diff --git a/Sem. 14/task6.cpp b/Sem. 14/task6.cpp deleted file mode 100644 index 9d0de4b..0000000 --- a/Sem. 14/task6.cpp +++ /dev/null @@ -1,37 +0,0 @@ -#include <iostream> -using namespace std; - -bool canBeCovered(int n, int m) -{ - if ((n == 0 && m >= 0) || (n>=0 && m==0)) //empty rectangle can be covered - return true; - - if (n < 0 || m < 0) //out of range - return false; - - if ((n == 1 && m == 2) || (n == 3 && m == 1)) //exactly one 1x2 or 3x1 - return true; - - if ((n == 1 && m == 1) || (n == 2 && m == 1)) // to swall for our plates - return false; - - - - //if the plate 1x2 stands in the top left corner - bool case1 = (m >=2 && canBeCovered(n - 1, 2) && canBeCovered(n, m - 2)) //try cut vertically - || (n>=1 && canBeCovered(n-1, m) && canBeCovered(1, m-2)); //try cut horizontaly - - if (case1) - return true; - - //if the plate 3x1 stands in the top left corner - bool case2 = (m >= 1 && canBeCovered(n - 3, 1) && canBeCovered(n, m - 1)) //try cut vertically - || (n>=3 && canBeCovered(3, m - 1) && canBeCovered(n - 3, m)); //try cut horizontaly - - return case2; -} -int main() -{ - int n, m; - cout << canBeCovered(4, 3); -} diff --git a/Sem. 14/task7.cpp b/Sem. 14/task7.cpp deleted file mode 100644 index 726a0f2..0000000 --- a/Sem. 14/task7.cpp +++ /dev/null @@ -1,65 +0,0 @@ -#include <iostream> -#include <cstring> -using namespace std; - -const int MAXLEN = 1024; - -//creates a matrix of the words in the sentence. -int fillWords(const char* str, char words[MAXLEN][MAXLEN]) -{ - int len = strlen(str); - - int currentWordCursorInMatrix = 0; - int count = 0 ; //also the index of the row in the matrix. - - for(int i = 0; i < len; i++) - { - if(str[i] == ' ') // the current word ends here. - { - if(currentWordCursorInMatrix != 0) // check if we have writen at least one symbol in the current word. - { - words[count][currentWordCursorInMatrix] = '\0'; - count++; - currentWordCursorInMatrix = 0; - } - } - else - { - words[count][currentWordCursorInMatrix] = str[i]; // we write the symbol in the current word. - currentWordCursorInMatrix++; - } - } - if(str[len-1] != ' ') - count++; //the last word; - return count; - -} - -void createReversedSentence(char words[MAXLEN][MAXLEN], int wordsCount, char* newSentence) -{ - - for (int j = wordsCount - 1; j >= 0 ; j--) - { - strcat(newSentence, words[j]); - if(j != 0) - strcat(newSentence, " "); //the space between the words - } -} -int main() -{ - const char* str = "How are you friends. I am fine!"; - - char words[MAXLEN][MAXLEN]; - - int wordsCount = fillWords(str, words); - - char* newSentense = new char[strlen(str)]; - - createReversedSentence(words, wordsCount, newSentense); - - cout << newSentense << endl; - - delete[] newSentense; - - return 0; -} diff --git a/Sem. 15/README.md b/Sem. 15/README.md deleted file mode 100644 index d3b3895..0000000 --- a/Sem. 15/README.md +++ /dev/null @@ -1,23 +0,0 @@ -**Задача 1:** Да се реализира функция, която приема символен низ (стринг) и връща думите му сортирани лексикографски. - -**Вход:** "hello friends! how are you?" - -**Изход:** are friends! hello how you? - -**Задача 2:** Да се реализира функция, която приема символен низ (стринг) и проверява дали има повтарящи се думи. - -**Задача 3:** Да се реализира функция, която приема два сортирани масива и връща трети сортиран масив с елементите от първите два. - -**Вход:** - -4 - -1 4 6 7 - -6 - -0 5 9 10 14 15 - - **Изход:** - -0 1 4 5 6 7 9 10 14 15 diff --git a/Sem. 15/task1.cpp b/Sem. 15/task1.cpp deleted file mode 100644 index d44663e..0000000 --- a/Sem. 15/task1.cpp +++ /dev/null @@ -1,121 +0,0 @@ -#include <iostream> - -using namespace std; - -int countWords(const char* text) -{ - bool wasLastCharSpace = true; - int wordCount = 0; - int len = strlen(text); - - for (int i = 0; i < len; i++) - { - if (wasLastCharSpace && text[i] != ' ' ) - { - wordCount++; - wasLastCharSpace = false; - } - else if (text[i] == ' ') - wasLastCharSpace = true; - } - return wordCount; - -} -int getWordLength(const char* text, int start) -{ - int len = 0; - int index = start; - - while (text[index] != ' ' && text[index] != '\0') - { - index++; - len++; - } - return len; -} - -void copyChars(char* dest, const char* text, int start, int len) -{ - - for (int i = start, index = 0; index < len; i++, index++) - dest[index] = text[i]; - - dest[len] = '\0'; -} -void fillWords(char** words, const char* text) -{ - int len = strlen(text); - int currentWordIndex = 0; - - for (int i = 0; i < len; i++) - { - if (text[i] == ' ') - continue; - - int currentWordLen = getWordLength(text, i); - - words[currentWordIndex] = new char[currentWordLen + 1]; //(**) - - copyChars(words[currentWordIndex], text, i, currentWordLen); - - currentWordIndex++; - i += currentWordLen; - } -} - -void swap(char** arr, int i, int j) -{ - char* wordPtr = arr[i]; - arr[i] = arr[j]; - arr[j] = wordPtr; -} -void selectionSort(char** arr, int len) -{ - for (int pos = 0; pos < len - 1; pos++) - { - int minIndex = pos; - for (int i = pos; i < len; i++) - { - if (strcmp(arr[i], arr[minIndex]) < 0) - minIndex = i; - } - if (pos != minIndex) - swap(arr, pos, minIndex); - } -} - -void free(char** words, int wordsCount) -{ - for (int i = 0; i < wordsCount; i++) - delete[] words[i]; // (**) - delete[] words; // (*) -} -void task1(const char* text) -{ - - int wordsCount = countWords(text); - - char** words = new char*[wordsCount]; // (*) - - fillWords(words, text); - - cout << "Before sort:" << endl; - for (int i = 0; i < wordsCount; i++) - cout << words[i] << endl; - - selectionSort(words, wordsCount); - - cout << "After sort:" << endl; - for (int i = 0; i < wordsCount; i++) - cout << words[i] << endl; - - free(words); -} - -int main() -{ - const char* text = " hello friends. how are you friends. "; - - task1(text); - -} diff --git a/Sem. 15/task2.cpp b/Sem. 15/task2.cpp deleted file mode 100644 index cc59a94..0000000 --- a/Sem. 15/task2.cpp +++ /dev/null @@ -1,119 +0,0 @@ -#include <iostream> -using namespace std; - -int countWords(const char* text) -{ - bool wasLastCharSpace = true; - int wordCount = 0; - int len = strlen(text); - - for (int i = 0; i < len; i++) - { - if (wasLastCharSpace && text[i] != ' ' ) - { - wordCount++; - wasLastCharSpace = false; - } - else if (text[i] == ' ') - wasLastCharSpace = true; - } - return wordCount; - -} -int getWordLength(const char* text, int start) -{ - int len = 0; - int index = start; - - while (text[index] != ' ' && text[index] != '\0') - { - index++; - len++; - } - return len; -} - -void copyChars(char* dest, const char* text, int start, int len) -{ - - for (int i = start, index = 0; index < len; i++, index++) - dest[index] = text[i]; - - dest[len] = '\0'; -} -void fillWords(char** words, const char* text) -{ - int len = strlen(text); - int currentWordIndex = 0; - - for (int i = 0; i < len; i++) - { - if (text[i] == ' ') - continue; - - int currentWordLen = getWordLength(text, i); - - words[currentWordIndex] = new char[currentWordLen + 1]; //(**) - - copyChars(words[currentWordIndex], text, i, currentWordLen); - - currentWordIndex++; - i += currentWordLen; - } -} - -void swap(char** arr, int i, int j) -{ - char* wordPtr = arr[i]; - arr[i] = arr[j]; - arr[j] = wordPtr; -} -void selectionSort(char** arr, int len) -{ - for (int pos = 0; pos < len - 1; pos++) - { - int minIndex = pos; - for (int i = pos; i < len; i++) - { - if (strcmp(arr[i], arr[minIndex]) < 0) - minIndex = i; - } - if (pos != minIndex) - swap(arr, pos, minIndex); - } -} - -void free(char** words, int wordsCount) -{ - for (int i = 0; i < wordsCount; i++) - delete[] words[i]; // (**) - delete[] words; // (*) -} - - -bool hasDuplicatesWords(const char* text) -{ - int wordsCount = countWords(text); - char** words = new char*[wordsCount]; // (*) - fillWords(words, text); - - selectionSort(words, wordsCount); - - for (int i = 0; i < wordsCount - 1; i++) - { - if (strcmp(words[i], words[i + 1]) == 0) - return true; - } - - return false; - - free(words, wordCount); - -} -int main() -{ - const char* text = " hello friends. how are you frienYds. "; - - cout << hasDuplicatesWords(text); - -} diff --git a/Sem. 15/task3.cpp b/Sem. 15/task3.cpp deleted file mode 100644 index b03b844..0000000 --- a/Sem. 15/task3.cpp +++ /dev/null @@ -1,53 +0,0 @@ -#include <iostream> -using namespace std; - - -//1-ви начин - конкатенираме двата масива и прилагаме сортировка. -//Губим предимството, че двата масива са били сортирани! - -//2-ри начин - с функцията merge. -void merge(const int* arr1, int len1, const int* arr2, int len2, int* result) -{ - int ind1 = 0, ind2 = 0, resultIndex; - - while (ind1 < len1 && ind2 < len2) - { - if (arr1[ind1] <= arr2[ind2]) - result[resultIndex++] = arr1[ind1++]; - else - result[resultIndex++] = arr2[ind2++]; - } - - while (ind1 < len1)//Ако е приключил първо вторият масив - result[resultIndex++] = arr1[ind1++]; - - while (ind2 < len2)//Ако е приключил първо първият масив - result[resultIndex++] = arr1[ind2++]; - -} -int main() -{ - int len1, len2; - cin >> len1 >> len2; - - int* arr1 = new int[len1]; // (*) - int* arr2 = new int[len2]; // (**) - cout << "Enter SORTED array 1:" << endl; - - for (int i = 0; i < len1; i++) - cin >> arr1[i]; - - cout << "Enter SORTED array 2:" << endl; - - for (int i = 0; i < len2; i++) - cin >> arr2[i]; - - int* result = new int[len1 + len2]; // (***) - - merge(arr1, len1, arr2, len2, result); - - for (int i = 0; i < len1 + len2; i++) - cout << result[i] << " "; - - delete[] arr1, arr2, result; // (*) (**) (***) -} |
