diff options
45 files changed, 1188 insertions, 145 deletions
@@ -4,6 +4,10 @@ - **Тема 2:** Условни конструкции - if, switch и тернарен оператор. - **Тема 3:** Цикли. Оператори break и continue. - **Тема 4:** Функции. Оператор return. + - **Тема 5:** Референции. Подаване на параметри по референция. Function overloading(*). + - **Тема 6:** Масиви. Масиви с предварително известна големина + - **Тема 7:** Бройни системи и побитови операции + ### Практикум: diff --git a/Sem. 03/README.md b/Sem. 03/README.md index 35624d4..e9c09f2 100644 --- a/Sem. 03/README.md +++ b/Sem. 03/README.md @@ -163,4 +163,13 @@ do **Задача 15:** Да се напише програма, която приема цяло положително число n и отпечатва следната папионка:  +**Задача 16:** Да се напише програма, която приема цяло положително число n и отпечатва следния килим: + +**Задача 17:** Да се напише програма, която приема цяло положително число n (n>=2) и след това n цели числа. +Да се отпечатат най-голямато и второто по големина. + + +*Вход: 10 9 1 4 5 10 99 34 0 44 1, Изход: 99 44* + +*Вход: 4 1 3 3 1, Изход: 3 3* diff --git a/Sem. 03/drawing_examples.txt b/Sem. 03/drawing_examples.txt index 73e3130..ee68672 100644 --- a/Sem. 03/drawing_examples.txt +++ b/Sem. 03/drawing_examples.txt @@ -188,3 +188,48 @@ $ $ $ $ 1 1
+
+задача 16:
+
+вход: 3
+
+#####
+#123#
+#231#
+#312#
+# X #
+#312#
+#231#
+#123#
+#####
+
+вход: 4
+
+######
+#1234#
+#2341#
+#3412#
+#4123#
+# XX #
+#4123#
+#3412#
+#2341#
+#1234#
+######
+
+вход: 5
+
+#######
+#12345#
+#23451#
+#34512#
+#45123#
+#51234#
+# X #
+#51234#
+#45123#
+#34512#
+#23451#
+#12345#
+#######
+
diff --git a/Sem. 04/example01_with_functions.cpp b/Sem. 04/example01_with_functions.cpp index f33b6b9..64d4367 100644 --- a/Sem. 04/example01_with_functions.cpp +++ b/Sem. 04/example01_with_functions.cpp @@ -1,8 +1,11 @@ #include <iostream>
using namespace std;
-bool isPrime(int n)
+bool isPrime(unsigned n)
{
+ if(n <= 1)
+ return false;
+
double temp = sqrt(n);
for (int i = 2; i <= temp; i++)
@@ -24,4 +27,4 @@ int main() if (isPrime(i - 1) && isPrime(i + 1))
cout << i - 1 << " " << i + 1 << endl;
}
-}
\ No newline at end of file +}
diff --git a/Sem. 05_kn/BAndC.cpp b/Sem. 05/BullsAndColls.cpp index 30f8a3d..706278b 100644 --- a/Sem. 05_kn/BAndC.cpp +++ b/Sem. 05/BullsAndColls.cpp @@ -1,36 +1,47 @@ -#include <iostream> +#include <iostream> using namespace std; +// Задача: +// Играта бикове и крави. +// Въвежда се число от потребителя. (скриваме го) +// Приемаме заявки от вида : +// Вход: x +// Изход: 2 бика и 2 крави. const int DIGITS_COUNT = 4; -int getNumLen(int n) +int getNumberLength(int n) { int count = 0; + + if (n == 0) + return 1; + while (n != 0) { - count++; n /= 10; + count++; } return count; } -bool containsDigit(int n, int digit) +bool containsDigit(int n, int searchedDigit) { while (n != 0) { int lastDigit = n % 10; - if (digit == lastDigit) + if (lastDigit == searchedDigit) return true; n /= 10; } return false; } -bool containsDiffrentDigits(int n) + +bool onlyDiffrentDigits(int n) { - while (n >= 10) + while (n != 0) { int lastDigit = n % 10; n /= 10; @@ -38,66 +49,70 @@ bool containsDiffrentDigits(int n) if (containsDigit(n, lastDigit)) return false; } + return true; } bool isValid(int n) { - return getNumLen(n) == DIGITS_COUNT && containsDiffrentDigits(n); + return getNumberLength(n) == DIGITS_COUNT && onlyDiffrentDigits(n); } -void userInput(int& toGuess) +void userInput(int& input) { do { - cin >> toGuess; - } while (!isValid(toGuess)); + cin >> input; + } while (!isValid(input)); } int getBulls(int toGuess, int myGuess) { - int bulls = 0; + int count = 0; + while (toGuess != 0) { int toGuessLastDigit = toGuess % 10; int myGuessLastDigit = myGuess % 10; if (toGuessLastDigit == myGuessLastDigit) - bulls++; - + count++; + toGuess /= 10; myGuess /= 10; } - return bulls; + return count; } -int getCows(int toGuess, int myGuess, int bulls) +int getSumOfBullsAndCows(int toGuess, int myGuess) { - int cows = 0; + int count = 0; while (myGuess != 0) { int lastDigit = myGuess % 10; if (containsDigit(toGuess, lastDigit)) - cows++; + count++; myGuess /= 10; } - return cows - bulls; + + return count; } void getBullsAndCows(int toGuess, int myGuess, int& bulls, int& cows) { bulls = getBulls(toGuess, myGuess); - cows = getCows(toGuess, myGuess, bulls); + cows = getSumOfBullsAndCows(toGuess, myGuess) - bulls; } + int main() { int toGuess; userInput(toGuess); - cout << "Try to guess:" << endl; + cout << "Success! Try to guess the number:" << endl; int bulls = 0; int cows = 0; @@ -108,8 +123,9 @@ int main() userInput(myGuess); getBullsAndCows(toGuess, myGuess, bulls, cows); - cout << "Bulls: " << bulls << " " << ", Cows: " << cows << endl; + cout << "Bulls: " << bulls << " " << "Cows: " << cows << endl; } - cout << "Success!" << endl; -} + +} + diff --git a/Sem. 05/references.cpp b/Sem. 05/references.cpp new file mode 100644 index 0000000..cf4f37e --- /dev/null +++ b/Sem. 05/references.cpp @@ -0,0 +1,56 @@ +#include <iostream> +using namespace std; + +// lvalue ("променлива") +// rvalue ("стойност/константа") + +//Референция - друго име за някоя променлива + +//Пример: +//Напишете функция, която приема цяло число и връща най-голямата и най-малката цифра. + +void getMaxAndMinDigit(int n, int& maxDigit, int& minDigit) +{ + int max = 0; + int min = 9; + + while (n != 0) + { + int lastDigit = n % 10; + + if (lastDigit > max) + max = lastDigit; + + if (lastDigit < min) + min = lastDigit; + + n /= 10; + } + maxDigit = max; + minDigit = min; + +} + + +int f1(int& n) //-връщат константа (rvalue) +{ + n++; + return n; +} +int& f2(int& n) //--връщат променлива (lvalue). +{ + n++; + return n; +} + +///!!!!!!!!!!! error +int& f3() +{ + int a = 10; + return a; +} + +int main() +{ + //cout << ++f(); +} diff --git a/Sem. 05_kn/draw b/Sem. 05/task15_sem3.cpp index 652a201..652a201 100644 --- a/Sem. 05_kn/draw +++ b/Sem. 05/task15_sem3.cpp diff --git a/Sem. 05/task16_sem3.cpp b/Sem. 05/task16_sem3.cpp new file mode 100644 index 0000000..bed9616 --- /dev/null +++ b/Sem. 05/task16_sem3.cpp @@ -0,0 +1,68 @@ +#include <iostream> +using namespace std; + + +int main() +{ + int n; + cin >> n; + + + //up + for (int i = 0; i < n + 2; i++) + cout << '#'; + cout << endl; + + + for (int i = 0; i < n; i++) + { + cout << '#'; + + for (int j = i + 1; j <= n + i; j++) + { + if (j > n) + cout << j % n; + else + cout << j; + + } + cout << '#' << endl; + } + //mid + + cout << "#"; + + for (int i = 0; i < n; i++) + { + if (n % 2 == 1 && n / 2 == i) + cout << "x"; + else if (n % 2 == 0 && ((n / 2 == i) || (n / 2 - 1 == i))) + cout << "x"; + else + cout << ' '; + } + + cout << '#' << endl; + + + //down + for (int i = n - 1; i >= 0; i--) + { + cout << '#'; + + for (int j = i + 1; j <= n + i; j++) + { + if (j > n) + cout << j % n; + else + cout << j; + + } + cout << '#' << endl; + } + + for (int i = 0; i < n + 2; i++) + cout << '#'; + cout << endl; +} + diff --git a/Sem. 05_kn/refferences.cpp b/Sem. 05_kn/refferences.cpp deleted file mode 100644 index 47e4fba..0000000 --- a/Sem. 05_kn/refferences.cpp +++ /dev/null @@ -1,119 +0,0 @@ -#include <iostream> -using namespace std; - - -int f(int n) -{ - n++; - return n; -} - -// lvalue ("връщане на променлива") -// rvalue ("връщане на константа") - -//Референция - друго име за някоя променлива - -// Пример: -// Напишете функция, която приема цяло число и връща най-голямата и най-малката цифра. - -void getMaxAndMinDigit(int n, int& maxDigit, int& minDigit) -{ - int max = 0; - int min = 9; - - while (n != 0) - { - int lastDigit = n % 10; - - if (lastDigit > max) - max = lastDigit; - - if (lastDigit < min) - min = lastDigit; - - n /= 10; - } - maxDigit = max; - minDigit = min; - -} - -//! - -int& f(int& n) //--няма да върне копие. -{ - n++; - return n; -} - -int main() -{ - int n; - cin >> n; - - int max, min; - - getMaxAndMinDigit(n, max, min); - cout << "Min digit " << min << " " << "max digit " << max << endl; -} - - - - - -#include <iostream> -using namespace std; - -// lvalue ("връщане на променлива") -// rvalue ("връщане на константа") - -//Референция - друго име за някоя променлива - -//Пример: -// Напишете функция, която приема цяло число и връща най-голямата и най-малката цифра. - -void getMaxAndMinDigit(int n, int& maxDigit, int& minDigit) -{ - int max = 0; - int min = 9; - - while (n != 0) - { - int lastDigit = n % 10; - - if (lastDigit > max) - max = lastDigit; - - if (lastDigit < min) - min = lastDigit; - - n /= 10; - } - maxDigit = max; - minDigit = min; - -} - - -int f1(int& n) //-връщат константа (rvalue) -{ - n++; - return n; -} -int& f2(int& n) //--връщат променлива (lvalue). -{ - n++; - return n; -} -///!!!!!!!!!!! error -int& f3() -{ - int a = 10; - return a; -} -int main() -{ - cout << ++f(); - - -} diff --git a/Sem. 06/README.md b/Sem. 06/README.md new file mode 100644 index 0000000..5da8c18 --- /dev/null +++ b/Sem. 06/README.md @@ -0,0 +1,139 @@ + +# Масиви (с фиксирана дължина) + +**Масивът** е наредена последователност от елементи от един тип. Отделен елемент на масива се достъпва посредством името на масива, последвано от поредния номер (индекс) на елемента в квадратни скоби + + + +## Инициализация на масиви + + ```c++ + int arr[6]; // Създава масив от 6 елемента, всеки от които е цяло число. + int arr2[] = {0, 1, 2, 3, 4, 5}; // Създава масив от 6 елемента. + int arr3[6] = {1,2,3}; //Останалите елементи се запълват с defaut-на стойност. + int arr[]; //грешка + int arr[4] = {1, 2, 3, 4, 5} // грешка +``` + + Задължително големината на масива трябва да е константа, чиято стойност е ясна преди да се компилира програмата + + ```c++ + int n; + cin >> n; + int arr[n]; //грешка! +``` + + ```c++ + const int SIZE = 4; + int arr[SIZE]; //ok! +``` + +## Достъп на елемент + В масивите имаме константен достъп до всеки един елемент. +Достъпът става посредством индекси. Индексацията започва от 0. (защо?) + + ```c++ + int arr[] = {1, 2, 400, 4, 5} + arr[3] = 44; //Присвоява на елементът на индекс 3 стойността 44. + // [1, 2, 400, 44, 5] + cout << arr[2]; //Отпечатва на стандартния изход елементът на индекс 2 (400) + +``` +arr не е самият масив, а указател към първия елемент. + ```c++ + int arr[] = {1, 2, 400, 4, 5} + cout << arr; //ще се отпечата АДРЕСА на масива, но не и самия масив. +``` + +Достъпът до елемент става, чрез смятането адреса му: + +Адресът на arr[i] е: arr + i * sizeof(type of array) + +i е брой "отмествания" надясно. + + + + + +## Подаване на масиви във функции + ```c++ + #include <iostream> + using namespace std; + void print(const int arr[], int len) + { + for(int i = 0; i < len; i++) + { + cout << arr[i] << " "; + } + } + void increment(int[] arr, unsigned size) + { + for(unsigned i = 0; i < size; i++) + arr[i]++; + } + int main() + { + const int SIZE = 4; + int arr[SIZE] {1,2,3,4}; + + increment(arr, SIZE); + print(arr,SIZE); + + return 0; + } +``` + Масивите се подават във функциите по адрес! + Т.е промените, които се правят върху масива във функцията, ще се отразят върху подадения като параметър масив! +## Примери + + - Отпечатване на масив + - Линейно търсене в масив + - Решето на Ератостен + - Двоично търсене + - Обръщане на масив + +<h3>Задачи</h3> + +**Задача 1:** Да се напише функция, която приема масив и връща дали е палиндром. + +*Вход: [1 2 3 2 1], Изход: true* + +**Задача 2** Да се напише функция, която приема масив и връща най-малкото общо кратно на числата в масива. + +*Вход: [9 18 6 12], Изход: 36* + + +**Задача 3** Да се напише функция, която приема масив и връща най-големият общ делител на числата в масива. + +*Вход: [9 18 6 12], Изход: 3* + +**Задача 4 :** Да се напише функция, която приема масив и връща дали е конкатенация на два масива, които са палиндроми. + +*Вход: [1 2 3 2 1 4 5 5 4], Изход: true* + +*Вход: [1 2 3 4 5], Изход: false* + +*Вход: [1 2 3 2 1], Изход: true* + + +**Задача 5 :** Въвежда се число N (N <= 1000) и N цели числа (елементи на масив). +Да се отпечатат броя на инверсиите в масива. + +Инверсия ще наричаме двойка индекси (i,j), където i < j и arr[i] > arr[j] + +*Вход: 6 5 4 3 2 10 Изход: 15* //в масива [5 4 3 2 1 0] има 15 инверсии. + +*Вход: 5 10 11 12 13 14 15, Изход: 0* + + +**Задача 6:** +От даден масив от сортирани последнователни числа са премахнати някои числа. +Напишете фунцкия, която приема такъв масив и връща най-малкото премахнато число. + +Решението ви трябва да работи с **логартмична сложност** ( а не с лиейно минаване през масива). + +*Вход: [5 6 7 9 10 12 13], Изход: 8* //премахнатите числа са 8 и 11. + +*Вход: [10 12 13 14 16], Изход: 11* //премахнатите числа са 11 и 16. + +Модифицирайте функцията, за да отпечатване и най-голямото премахнато число diff --git a/Sem. 06/binarySearch.cpp b/Sem. 06/binarySearch.cpp new file mode 100644 index 0000000..c4132c9 --- /dev/null +++ b/Sem. 06/binarySearch.cpp @@ -0,0 +1,33 @@ +#include <iostream>
+using namespace std;
+
+bool binarySearch(const int arr[], unsigned size, int searched)
+{
+ unsigned fromIndex = 0;
+ unsigned toIndex = size - 1;
+
+ while (fromIndex <= toIndex)
+ {
+ unsigned midIndex = fromIndex + (toIndex - fromIndex) / 2;
+
+ if (arr[midIndex] == searched)
+ return true;
+
+ if (arr[midIndex] < searched)
+ fromIndex = midIndex + 1;
+ else
+ toIndex = midIndex - 1;
+ }
+
+ return false;
+}
+
+
+int main()
+{
+
+ int arr[] { 1, 2, 3, 4,5,6,7,8};
+ cout << binarySearch(arr, 8);
+
+}
+
diff --git a/Sem. 06/linearSearch.cpp b/Sem. 06/linearSearch.cpp new file mode 100644 index 0000000..d5d2ff1 --- /dev/null +++ b/Sem. 06/linearSearch.cpp @@ -0,0 +1,45 @@ +#include <iostream>
+#include <vector>
+using namespace std;
+
+
+bool linearSearch(const int arr[], unsigned size, int el)
+{
+ for (unsigned i = 0; i < size; i++)
+ {
+ if (arr[i] == el)
+ return true;
+ }
+ return false;
+}
+
+bool binarySearch(const int arr[], unsigned size, int searched)
+{
+ unsigned fromIndex = 0;
+ unsigned toIndex = size - 1;
+
+ while (fromIndex <= toIndex)
+ {
+ unsigned midIndex = fromIndex + (toIndex - fromIndex) / 2;
+
+ if (arr[midIndex] == searched)
+ return true;
+
+ if (arr[midIndex] < searched)
+ fromIndex = midIndex + 1;
+ else
+ toIndex = midIndex - 1;
+ }
+
+ return false;
+}
+
+
+
+int main()
+{
+ const unsigned SIZE = 8;
+ int arr[] { 1, 12, 33, 14,35,4,17,38};
+ cout << linearSearch(arr, SIZE, 14);
+}
+
diff --git a/Sem. 06/printArray.cpp b/Sem. 06/printArray.cpp new file mode 100644 index 0000000..af69b41 --- /dev/null +++ b/Sem. 06/printArray.cpp @@ -0,0 +1,18 @@ +#include <iostream>
+using namespace std;
+
+
+void print(const int arr[], unsigned int len)
+{
+ cout << "[ ";
+ for (int i = 0; i < len; i++)
+ cout << arr[i] << " ";
+ cout << "]" << endl;
+}
+
+int main()
+{
+ int arr[] { 1, 2, 3, 4, 5, 6, 7, 8};
+ print(arr, 8);
+}
+
diff --git a/Sem. 06/reverse.cpp b/Sem. 06/reverse.cpp new file mode 100644 index 0000000..e239289 --- /dev/null +++ b/Sem. 06/reverse.cpp @@ -0,0 +1,23 @@ +#include <iostream>
+using namespace std;
+
+void swap(int& x, int& y)
+{
+ int temp = x;
+ x = y;
+ y = temp;
+}
+
+void reverse(int arr[], unsigned size)
+{
+ for (unsigned i = 0; i < size / 2; i++)
+ swap(arr[i], arr[size - 1 - i]);
+}
+
+int main()
+{
+ int arr[] { 1, 2, 3, 4,5,6,7,8};
+ reverse(arr, 8);
+ print(arr, 8);
+}
+
diff --git a/Sem. 06/sieveOfEratosthenes.cpp b/Sem. 06/sieveOfEratosthenes.cpp new file mode 100644 index 0000000..2505ad9 --- /dev/null +++ b/Sem. 06/sieveOfEratosthenes.cpp @@ -0,0 +1,48 @@ +#include <iostream>
+using namespace std;
+
+void init(bool arr[], unsigned size, bool value)
+{
+ for (unsigned i = 0; i < size; i++)
+ arr[i] = value;
+}
+
+void sieveEratosthenes(bool arr[], unsigned size)
+{
+ arr[0] = arr[1] = false;
+
+ for (unsigned i = 2; i < size; i++)
+ {
+ if (!arr[i]) //ако числото е задраскано
+ continue;
+
+ for (unsigned iter = i + i; iter < size; iter += i)
+ arr[iter] = false; //задраскваме
+ }
+}
+
+void printSieve(const bool arr[], unsigned size)
+{
+ for (unsigned i = 0; i < size; i++)
+ {
+ if (arr[i])
+ {
+ cout << i << " ";
+ }
+ }
+}
+
+
+int main()
+{
+ const unsigned MAX_SIZE = 1000;
+ bool arr[MAX_SIZE];
+
+ int n;
+ cin >> n;
+
+ init(arr, n, true);
+ sieveEratosthenes(arr, n);
+ printSieve(arr, n);
+}
+
diff --git a/Sem. 07/README.md b/Sem. 07/README.md new file mode 100644 index 0000000..92ed2ea --- /dev/null +++ b/Sem. 07/README.md @@ -0,0 +1,91 @@ + +# Бройни системи и побитови операции + +| Десетична (decimal) | Двоична (binary) | осмична (octal) | Шестнайсетична (hexadecimal) | Унарна (unary) | +|---------------------|------------------|-----------------|------------------------------|-------| +| 00 | 00000 | 00 | 00 | 00001 | +| 01 | 00001 | 01 | 01 | 00011 | +| 02 | 00010 | 02 | 02 | 00111 | +| 03 | 00011 | 03 | 03 | 01111 | +| 04 | 00100 | 04 | 04 | ... | +| 05 | 00101 | 05 | 05 | | +| 06 | 00110 | 06 | 06 | | +| 07 | 00111 | 07 | 07 | | +| 08 | 01000 | 10 | 08 | | +| 09 | 01001 | 11 | 09 | | +| 10 | 01010 | 12 | 0A | | +| 11 | 01011 | 13 | 0B | | +| 12 | 01100 | 14 | 0C | | +| 13 | 01101 | 15 | 0D | | + +#### Преобразуване между бройни системи + +Примери: + + - Алгоритъм за преобразуване от произволна бройна система в дестична бройна система + - Алгоритъм за преобразуване от десетчина бройна система в произволна бройна система + +#### Представяния на отрицателни числа + + - One's complement (5) [101] -(flip)-> [010] (-5) + - Two's complement (5) [101] -(flip)-> [010] + [001] = [011] (-5) + +#### Побитови операции +прилагат върху един бит или набор от повече отделни битове на двоични числа + + - Побитово И (**&**) + - Побитово ИЛИ (**|**) + - Побитово ИЗКЛЮЧВАЩО ИЛИ (**^**) + - Побитово отместване (**<<** ) ( **>>**) + +| | | +|--------|-----------| +| a | 101010100 | +| b | 100101110 | +| a&b | 100000100 | +| a \| b | 101111110 | +| a^b | 000000100 | +| a << 2 | 101010000 | +| a >> 2 | 001010101 | + +Примери: + + - Функция, която с побитови операции проверява дали число е четно + - Функция, която с побитови операции повдига 2 на степен k. + +<h3>Задачи</h3> + +**Задача 1:** Напишете функция, която приема число от в произволна бройна система и преобразува **директно** (без да минава през десетична) числото в друга произволна бройна система. + +**Задача 2** Да се напише функция, която приема масив, в който всяко число се среща 2 пъти с изключение на едно число, което се среща веднъж. +Напишете функция, която приема такъв масив и връща кое е това число. +(Подсказка: използвайте побитови операции, за да постигнете линейно решение) + +*Вход: [9 18 9 12 18 15 12], Изход: 15* + + +**Задача 3** Напишете функция, която приема цяло число и връща броя на 1-ците в двоичния му запис. + +*Вход: 189, Изход: 6* + +**Задача 4 :** Напишете функция, която приема цяло число и обръща най-десният бит в него, който е единица. + +*Вход: 12, Изход: 8* + +*Вход: 15, Изход: 14* + +**Задача 5:** Напишете функция, която по подадено цяло число n и цяло число k и връща числото, което е "закодирано" в последните k бита на n. + +*Вход: 15 2, Изход: 3* + +*Вход: 189 3, Изход: 5* + +*Вход: 189 4, Изход: 13* + +**Задача 6:** Напишете функция, която приема цяло число n и цяло число k и връща дали k в двоичен запис (разглеждайки го без водещите 0-ли) е част от двоичния запис на n. + +*Вход: 15 3, Изход: true* + +*Вход: 13 5 Изход: true* + +*Вход: 13 7, Изход: false* diff --git a/Sem. 07/bitwiseSimpleExamples.cpp b/Sem. 07/bitwiseSimpleExamples.cpp new file mode 100644 index 0000000..c550a0f --- /dev/null +++ b/Sem. 07/bitwiseSimpleExamples.cpp @@ -0,0 +1,16 @@ +#include <iostream> +using namespace std; + +bool isEven(unsigned n) // какво ще трябва се промени ако искаме да е signed? +{ + return !(n & 1); +} + +unsigned powerOfTwo(unsigned n) +{ + return (1 << n); +} +int main() +{ + cout << powerOfTwo(8); // 2^8 +} diff --git a/Sem. 07/numerialSystemsExample.cpp b/Sem. 07/numerialSystemsExample.cpp new file mode 100644 index 0000000..620804c --- /dev/null +++ b/Sem. 07/numerialSystemsExample.cpp @@ -0,0 +1,98 @@ +#include <iostream> +using namespace std; + +const unsigned MAX_SIZE = 32; + +char getCharByNumber(unsigned number) +{ + if (number <= 9) + return '0' + number; + if (10 <= number && number <= 35) + return 'A' + (number - 10); + else + return 'a' + (number - 36); +} + +unsigned getNumberByChar(char ch) +{ + if ('0' <= ch && ch <= '9') + return ch - '0'; + if ('A' <= ch && ch <= 'Z') + return 10 + ch - 'A'; + if ('a' <= ch && ch <= 'z') + return 32 + ch - 'a'; +} + +void swap(int& a, int& b) +{ + int temp = a; + a = b; + b = temp; +} +void convertFromDecimal(unsigned number, char result[], unsigned k) +{ + unsigned resultInd = 0; + while (number != 0) + { + int symbolIndex = number % k; + result[resultInd++] = getCharByNumber(symbolIndex); + number /= k; + } + + for (unsigned i = 0; i < resultInd / 2; i++) + swap(result[i], result[resultInd - 1 - i]); + +} + +unsigned convertToDecimal(const char number[], unsigned size, unsigned k) +{ + unsigned mult = 1; + + unsigned result = 0; + for (int i = size - 1; i >= 0; i--) + { + result += getNumberByChar(number[i]) * mult; + mult *= k; + } + + return result; +} + +//fill with spaces from start +void init(char buff[], unsigned start) +{ + for (unsigned i = start; i < MAX_SIZE; i++) + buff[i] = ' '; +} + +void print(const char buff[]) +{ + for (unsigned i = 0; i < MAX_SIZE; i++) + cout << buff[i]; + cout << endl; +} + +int main() +{ + { + unsigned n = 12345; + char buff[MAX_SIZE]; + init(buff, 0); + + convertFromDecimal(123456, buff, 16); + + cout << n << " to hex: "; + print(buff); + } + + { + unsigned n = 12345; + char buff[MAX_SIZE] = { 'A', '1', '2', 'B' }; + init(buff, 5); + + unsigned result = convertToDecimal(buff, 4, 16); + + cout << buff << " to decimal: " << result << endl; + } +} + diff --git a/pract_KN/pract. 05/задачи пета седмица.pdf b/pract_KN/pract. 05/задачи пета седмица.pdf Binary files differnew file mode 100644 index 0000000..0ee9d36 --- /dev/null +++ b/pract_KN/pract. 05/задачи пета седмица.pdf diff --git a/pract_KN/pract. 06/задачи пета седмица.pdf b/pract_KN/pract. 06/задачи пета седмица.pdf Binary files differnew file mode 100644 index 0000000..a3a4162 --- /dev/null +++ b/pract_KN/pract. 06/задачи пета седмица.pdf diff --git a/pract_SI/Pract. 04/Solutions/task3 - isNegative().cpp b/pract_SI/Pract. 04/Solutions/task3 - isNegative().cpp new file mode 100644 index 0000000..6ca43c5 --- /dev/null +++ b/pract_SI/Pract. 04/Solutions/task3 - isNegative().cpp @@ -0,0 +1,4 @@ +bool isNegative(int num) +{ + return num < 0; +}
\ No newline at end of file diff --git a/pract_SI/Pract. 04/Solutions/task3.cpp b/pract_SI/Pract. 04/Solutions/task3 - isPositive().cpp index 937b833..937b833 100644 --- a/pract_SI/Pract. 04/Solutions/task3.cpp +++ b/pract_SI/Pract. 04/Solutions/task3 - isPositive().cpp diff --git a/pract_SI/Pract. 04/Solutions/task4 - abs.cpp b/pract_SI/Pract. 04/Solutions/task4 - abs.cpp new file mode 100644 index 0000000..771550b --- /dev/null +++ b/pract_SI/Pract. 04/Solutions/task4 - abs.cpp @@ -0,0 +1,4 @@ +int abs(int num1, int num2) +{ + return ((num1 - num2) >= 0 ? (num1 - num2) : (num2 - num1)); +}
\ No newline at end of file diff --git a/pract_SI/Pract. 04/Solutions/task4 - fabs.cpp b/pract_SI/Pract. 04/Solutions/task4 - fabs.cpp new file mode 100644 index 0000000..bb2f15b --- /dev/null +++ b/pract_SI/Pract. 04/Solutions/task4 - fabs.cpp @@ -0,0 +1,4 @@ +double fabs(double &num) +{ + return num > 0.0 ? num : -num; +}
\ No newline at end of file diff --git a/pract_SI/Pract. 04/Solutions/task6.cpp b/pract_SI/Pract. 04/Solutions/task6.cpp new file mode 100644 index 0000000..cbca3de --- /dev/null +++ b/pract_SI/Pract. 04/Solutions/task6.cpp @@ -0,0 +1,4 @@ +bool isCapitalLetter(char S) +{ + return (S >= 'A' && S <= 'Z'); +}
\ No newline at end of file diff --git a/pract_SI/Pract. 04/Solutions/task7 - a).cpp b/pract_SI/Pract. 04/Solutions/task7 - a).cpp new file mode 100644 index 0000000..8a590b4 --- /dev/null +++ b/pract_SI/Pract. 04/Solutions/task7 - a).cpp @@ -0,0 +1,3 @@ +bool isInInterval(int num) { + return num >= 100 && num <= 10000; +} diff --git a/pract_SI/Pract. 04/Solutions/task7 - b).cpp b/pract_SI/Pract. 04/Solutions/task7 - b).cpp new file mode 100644 index 0000000..4dde747 --- /dev/null +++ b/pract_SI/Pract. 04/Solutions/task7 - b).cpp @@ -0,0 +1,3 @@ +bool isNumberInInterval(long longnum, long long interval_lower_bound, long long interval_upper_bound,) { + return num >= interval_lower_bound && num <= interval_upper_bound; +}
\ No newline at end of file diff --git a/pract_SI/Pract. 04/Solutions/task8.cpp b/pract_SI/Pract. 04/Solutions/task8.cpp new file mode 100644 index 0000000..9d91c6a --- /dev/null +++ b/pract_SI/Pract. 04/Solutions/task8.cpp @@ -0,0 +1,9 @@ +long long pow(int num, unsigned N) +{ + long long result = 1; + + for (size_t i = 0; i < N; i++) + result *= num; + + return result; +}
\ No newline at end of file diff --git a/pract_SI/Pract. 04/Solutions/task9.cpp b/pract_SI/Pract. 04/Solutions/task9.cpp new file mode 100644 index 0000000..0356de8 --- /dev/null +++ b/pract_SI/Pract. 04/Solutions/task9.cpp @@ -0,0 +1,17 @@ +int calculate(int a, int b, char action = '+') +{ + switch (action) + { + case '+': return a + b; + + case '-': return a - b; + + case '*': return a * b; + + case '/': return a / b; + + case '%': return a % b; + + default: return -1; + } +}
\ No newline at end of file diff --git a/pract_SI/Pract. 04/Solutions_10-14/task10.cpp b/pract_SI/Pract. 04/Solutions_10-14/task10.cpp new file mode 100644 index 0000000..e9e83b9 --- /dev/null +++ b/pract_SI/Pract. 04/Solutions_10-14/task10.cpp @@ -0,0 +1,9 @@ +int askUser(int from, int to) +{ + int number; + while (std::cin >> number) + { + if (number >= from && number <= to) + return number; + } +}
\ No newline at end of file diff --git a/pract_SI/Pract. 04/Solutions_10-14/task11.cpp b/pract_SI/Pract. 04/Solutions_10-14/task11.cpp new file mode 100644 index 0000000..77d76e5 --- /dev/null +++ b/pract_SI/Pract. 04/Solutions_10-14/task11.cpp @@ -0,0 +1,25 @@ +void convertIfNegative(int &number) +{ + if (number < 0) + number *= -1; +} + +unsigned long long toBinary(int number) +{ + convertIfNegative(number); + + unsigned long long toBinary = 0; + short digits = 0; + while (number > 0) + { + unsigned long long temp = 1; + for (size_t i = 0; i < digits; i++) + temp *= 10; + + toBinary += (number % 2) * temp; + digits++; + number /= 2; + } + + return toBinary; +}
\ No newline at end of file diff --git a/pract_SI/Pract. 04/Solutions_10-14/task11_recursive.cpp b/pract_SI/Pract. 04/Solutions_10-14/task11_recursive.cpp new file mode 100644 index 0000000..1b9a3e3 --- /dev/null +++ b/pract_SI/Pract. 04/Solutions_10-14/task11_recursive.cpp @@ -0,0 +1,12 @@ +/* +NOTE! +Current Solution uses recursion, which we still have NOT taken/discussed. +*/ + +void toBinary(unsigned int num) +{ + if (num > 1) { + toBinary(num / 2); + } + std::cout << num % 2; +}
\ No newline at end of file diff --git a/pract_SI/Pract. 04/Solutions_10-14/task12.cpp b/pract_SI/Pract. 04/Solutions_10-14/task12.cpp new file mode 100644 index 0000000..464b17b --- /dev/null +++ b/pract_SI/Pract. 04/Solutions_10-14/task12.cpp @@ -0,0 +1,35 @@ +#include <iostream> +using namespace std; + +int gcd(int x, int y) +{ + while (x != y) + if (x > y) + x -= y; + else + y -= x; + return x; +} + +int main() +{ + int a, b, c, d; + + cout << "a, b, c, d= "; + cin >> a >> b >> c >> d; + if (!cin || a < 1 || b < 1 || c < 1 || d < 1) + { + cout << "Error! \n"; + return 1; + } + + int r = gcd(a, b); + cout << "gcd{" << a << ", " << b << "}= " << r << "\n"; + + int s = gcd(c, d); + cout << "gcd{" << c << ", " << d << "}= " << s << "\n"; + + cout << "gcd{" << a << ", " << b << ", " << c << ", " << d << "}= " << gcd(r, s) << "\n"; + + return 0; +} diff --git a/pract_SI/Pract. 04/Solutions_10-14/task13.cpp b/pract_SI/Pract. 04/Solutions_10-14/task13.cpp new file mode 100644 index 0000000..8acb1c9 --- /dev/null +++ b/pract_SI/Pract. 04/Solutions_10-14/task13.cpp @@ -0,0 +1,43 @@ +#include<iostream> +using namespace std; + +int input() +{ + int number; + do + { + cout << "Enter a valid number: "; + cin >> number; + } while (!cin || number < 100 || number > 100000); + return number; +} + +int dist(int number1, int number2) +{ + int diff = number1 - number2; + return diff >= 0 ? diff : -diff; +} + +int closestLargerPowerOf2(int number) +{ + int power = 1; + while (power < number) + { + power <<= 1; + } + return power; +} + +int main() +{ + int number = input(); + int larger = closestLargerPowerOf2(number); + int smaller = larger >> 1; + + int distToSmaller = dist(number, smaller); + int distToLarger = dist(number, larger); + + cout << "Closest power of two to " << number << ": " << ((distToSmaller < distToLarger) ? smaller : larger) << endl; + + return 0; +}
\ No newline at end of file diff --git a/pract_SI/Pract. 04/Solutions_10-14/task14.cpp b/pract_SI/Pract. 04/Solutions_10-14/task14.cpp new file mode 100644 index 0000000..405bcf7 --- /dev/null +++ b/pract_SI/Pract. 04/Solutions_10-14/task14.cpp @@ -0,0 +1,92 @@ +#include <iostream> +#include <cmath> + +using namespace std; + +//Function to check whether a number is prime +bool isPrime(int number) +{ + int size = sqrt(number); + + for (int i = 2; i <= size; i++) + { + if (number % i == 0) + return false; + } + + return true; +} + +//Print all prime numbers that are smaller than N +void printAllPrimeToNumber(int number) //Interval [1 ; N] +{ + std::cout << "1" << ", 2"; + + for (int i = 3; i <= number; i += 2) + { + if (isPrime(i)) + std::cout << ", " << i; + } + + std::cout << "." << std::endl; +} + +//PrimeFactorization +void PrimeFactor(int number) +{ + for (int i = 2; i <= number; i++) + { + if (isPrime(i) && number % i == 0) + { + if (i == number) //last step, no space + std::cout << i; + else + std::cout << i << " "; + + number /= i; + i--; + } + } + std::cout << std::endl; +} + +//Function whether the number N can be expressed as a sum of two prime numbers +bool checkSumOfTwoPrimes(int number,int &primeOfNumber) +{ + int size = number / 2; //36 = 7 + 29, 16 = 3 + 13 , 36 = 5 + 31 + for (int i = 2;i <= size; i++) + { + //16 = 3 + x , x = 16 - 3 , x = 13 PRIME + if (isPrime(i) && isPrime(number - i)) + { + primeOfNumber = i; + return true; + } + } + return false; +} + +int main() +{ + int number; + std::cin >> number; + + if (isPrime(number)) + std::cout << number << " is prime!" << std::endl; + else + std::cout << number << " is composite number!" << std::endl; + + std::cout << std::endl << "Prime numbers up to " << number << " are: "; + printAllPrimeToNumber(number); + + std::cout << "Factoring of: " << number << " is: "; + PrimeFactor(number); + + int primeOfNumber; + if (checkSumOfTwoPrimes(number, primeOfNumber)) + std::cout << primeOfNumber << " + " << number - primeOfNumber << std::endl; + else + std::cout << "Error!" << std::endl; + + return 0; +} diff --git a/pract_SI/Pract. 04/Tasks4.txt b/pract_SI/Pract. 04/Tasks4.txt index 4daf06c..5470b9a 100644 --- a/pract_SI/Pract. 04/Tasks4.txt +++ b/pract_SI/Pract. 04/Tasks4.txt @@ -29,4 +29,17 @@ Входа да се валидира като при грешен ход да се дава възможност за нов опит. Изкарайте отделните функционалности във функции. +14. a)Напишете функция, която проверява дали дадено число е просто. +14. b)Напишете функция, която извежда на екрана всички прости числа до дадено число. +14. c)Напишете програма, която приема число и отпечатва неговата *факторизация. +*Декомпозиция на числото на произведението на други прости числа(множители), които след това умножение дават оригинала* + +Вход: 225 +Изход: 3.3.5.5 + +Вход: 31668 +Изход: 2.2.3.7.13.29 + +14. d)Напишете функция, която проверява дали дадено число може да бъде представено като сбор на 2 прости числа. + diff --git a/pract_SI/Pract. 05/Solutions/task1.cpp b/pract_SI/Pract. 05/Solutions/task1.cpp new file mode 100644 index 0000000..7832c63 --- /dev/null +++ b/pract_SI/Pract. 05/Solutions/task1.cpp @@ -0,0 +1,13 @@ +int firstDuplicateInArray(int *arr, int size) +{ + for (int i = 0; i < size - 1; i++) + { + for (int j = i + 1; j < size; j++) + { + if (arr[i] == arr[j]) + return arr[i]; + } + } + + return -1; +}
\ No newline at end of file diff --git a/pract_SI/Pract. 05/Solutions/task1_changedCondition.cpp b/pract_SI/Pract. 05/Solutions/task1_changedCondition.cpp new file mode 100644 index 0000000..35b0d8f --- /dev/null +++ b/pract_SI/Pract. 05/Solutions/task1_changedCondition.cpp @@ -0,0 +1,10 @@ +bool isNumberInArray(int *arr, int size,int number) +{ + for (int i = 0; i < size; i++) + { + if (arr[i] == number) + return true; + } + + return false; +}
\ No newline at end of file diff --git a/pract_SI/Pract. 05/Solutions/task3.cpp b/pract_SI/Pract. 05/Solutions/task3.cpp new file mode 100644 index 0000000..b8693d9 --- /dev/null +++ b/pract_SI/Pract. 05/Solutions/task3.cpp @@ -0,0 +1,50 @@ +long long toBinary(int number) +{ + if (number < 0) + number *= -1; + + int buffer[MAX_POWTWO_SIZE]; + int size = 0; + + while (number > 0) + { + buffer[size] = number % 2; + number /= 2; + size++; + } + + long long convertedToBinary = 0; + long long multiply = 1; + for (int i = 0; i < size; i++) + { + convertedToBinary += buffer[i] * multiply; + multiply *= 10; + } + + return convertedToBinary; +} + +void convertToBinary(long long &number) +{ + if (number < 0) + number *= -1; + + int buffer[MAX_POWTWO_SIZE]; + int size = 0; + + while (number > 0) + { + buffer[size] = number % 2; + number /= 2; + size++; + } + + long long multiply = 1; + for (int i = 0; i < size; i++) + { + if(buffer[i] == 1) + number += multiply; + + multiply *= 10; + } +}
\ No newline at end of file diff --git a/pract_SI/Pract. 05/Solutions/task4.cpp b/pract_SI/Pract. 05/Solutions/task4.cpp new file mode 100644 index 0000000..19c1f38 --- /dev/null +++ b/pract_SI/Pract. 05/Solutions/task4.cpp @@ -0,0 +1,23 @@ +bool isPalindrom(int *arr, int size) +{ + for (int i = 0; i < size / 2; i++) + { + if (arr[i] != arr[size - i - 1]) + return false; + } + return true; +} + +bool isPalindrom(int number) +{ + int buffer[MAX_SIZE]; + int size = 0; + while (number > 0) //1505 + { + buffer[size] = number % 10; //5 0 5 1 + number /= 10; + size++; + } + + return isPalindrom(buffer, size); +}
\ No newline at end of file diff --git a/pract_SI/Pract. 05/Solutions/task5.cpp b/pract_SI/Pract. 05/Solutions/task5.cpp new file mode 100644 index 0000000..0676987 --- /dev/null +++ b/pract_SI/Pract. 05/Solutions/task5.cpp @@ -0,0 +1,23 @@ +void swap(int &first,int &second) +{ + int temp = first; + first = second; + second = temp; +} + +void specificOrderArray(int *arr,int size) +{ + bool isBigger = true; + + for (int i=0; i < size - 1; i++) + { + if (isBigger) + if (arr[i] < arr[i+1]) + swap(arr[i], arr[i+1]); + else + if (arr[i] > arr[i+1]) + swap(arr[i], arr[i+1]); + + isBigger = !isBigger; + } +}
\ No newline at end of file diff --git a/pract_SI/Pract. 05/Solutions/task6.cpp b/pract_SI/Pract. 05/Solutions/task6.cpp new file mode 100644 index 0000000..a3804fc --- /dev/null +++ b/pract_SI/Pract. 05/Solutions/task6.cpp @@ -0,0 +1,26 @@ +/* +A iterative binary search function. +It returns location of x in given array arr[l..r] if present, +otherwise -1. +*/ + +//int l - left side index +//int r - right side index +//int m - middle index +//int x - number 'x' we are searching for + +int binarySearch1(int *arr, int l, int r, int x) +{ + while (l <= r) + { + int m = l + (r - l) / 2; + if (arr[m] == x)// Check if x is present at mid + return m; + if (arr[m] < x)// If x greater, ignore left half + l = m + 1; + else + r = m - 1; // If x is smaller, ignore right half + } + + return -1; // if we reach here, then the element was not present +}
\ No newline at end of file diff --git a/pract_SI/Pract. 05/Tasks5.txt b/pract_SI/Pract. 05/Tasks5.txt new file mode 100644 index 0000000..5ef0385 --- /dev/null +++ b/pract_SI/Pract. 05/Tasks5.txt @@ -0,0 +1,14 @@ +#Никола Светославов - task5 + +## Задачи + +1.Напишете програма, която намира първия повтарящ се елемент в редица от N числа. +2.Напишете програма, която подрежда елементите на редица от N числа, + като първите елементи са четните, вторите - нечетните. +3.Напишете програма, която превръща дадено естествено число в двоична бройна система. +4.Напишете програма, която извежда дали едно число е палиндром. +5.Напишете програма, която подрежда елементите на редица от N числа по следния начин: +а1 > а2 < а3 > а4 < (...) +6.Напишете функция, която сортира масив във възходящ ред. + Напишете функция binarySearch, приемаща като аргументи сортиран във възходящ ред масив от цели числа, + размер на масива и търсен елемент.Функцията трябва да връща индекса на търсения елемент или -1 ,ако той не присъства в масива. diff --git a/pract_SI/Pract. 05/input.cpp b/pract_SI/Pract. 05/input.cpp new file mode 100644 index 0000000..9b8c5da --- /dev/null +++ b/pract_SI/Pract. 05/input.cpp @@ -0,0 +1,7 @@ +#include <iostream> + +void input(int *arr,const int size) +{ + for (int i = 0; i < size; i++) + std::cin >> arr[i]; +} diff --git a/pract_SI/Pract. 05/output.cpp b/pract_SI/Pract. 05/output.cpp new file mode 100644 index 0000000..79829e0 --- /dev/null +++ b/pract_SI/Pract. 05/output.cpp @@ -0,0 +1,7 @@ +#include <iostream> + +void output(int *arr,const int size) +{ + for (int i = 0; i < size; i++) + std::cout << arr[i] << std::endl; +}
\ No newline at end of file |
