first commit

This commit is contained in:
NKTKLN 2024-09-24 02:22:33 +03:00
commit e94e758736
725 changed files with 38725 additions and 0 deletions

4
.gitignore vendored Executable file
View File

@ -0,0 +1,4 @@
.DS_Store
.vscode/
Test/

42
First term/Algorithms/1-2/1.py Executable file
View File

@ -0,0 +1,42 @@
def binary_search(arr: list, item: int) -> (int, bool):
is_found = False
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == item:
is_found = True
break
if arr[mid] > item:
high = mid - 1
continue
low = mid + 1
if arr[mid] < item:
mid += 1
return mid, is_found
def main() -> None:
# Config
arr = [1, 2, 3, 4, 5, 7, 8]
item = 6
# Main code
ans = binary_search(arr, item)
print("Index: ", ans[0])
print("Before:", arr)
if not ans[1]:
arr.insert(ans[0], item)
print("After: ", arr)
if __name__ == "__main__":
main()

62
First term/Algorithms/1-2/2.py Executable file
View File

@ -0,0 +1,62 @@
def binary_search(arr: list) -> int:
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if len(arr) - 1 == mid or mid == 0:
return mid
if arr[mid-1] < arr[mid] > arr[mid+1]:
return mid
if arr[mid] >= arr[mid+1]:
high = mid - 1
continue
low = mid + 1
return None
def checkIfPeakExist(arr: list) -> bool:
for index in range(len(arr)):
is_exist = True
for first in range(index-1):
if not arr[first] < arr[first+1]:
is_exist = False
for second in range(index, len(arr)-1):
if not arr[second] > arr[second+1]:
is_exist = False
if is_exist:
if index == 0 or index == len(arr)-1:
return 0
return arr[index]
return 0
def main() -> None:
# Config
arr = [2, 3, 7, 4, 3, 2, -1, -2, -3, -4, -5, -6, -8]
# arr = [-8, -6, -5, -4, -3, -2, -1, 2, 3, 4, 3, 2]
# arr = [1, 2, 3, 4, 5, 4, 3, 2, 1]
# Main code
if not checkIfPeakExist(arr):
print("Не является горным списком.")
return
ans = binary_search(arr)
print("Ответ:", arr[ans])
print("Индекс:", ans)
if __name__ == "__main__":
main()

44
First term/Algorithms/1-2/3.py Executable file
View File

@ -0,0 +1,44 @@
def binary_search(arr: list) -> int:
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == 0:
break
if arr[mid] > 0:
high = mid - 1
continue
low = mid + 1
return mid
def main() -> None:
# Config
arr = [-5, -4, -3, -2, 2, 3, 4]
# Main code
if len(arr) == 0:
print("Пустой список.")
return
index = binary_search(arr)
neg = index
pos = len(arr) - neg
if arr[index] < 0:
neg += 1
if arr[index] <= 0:
pos -= 1
print(neg, pos)
if __name__ == "__main__":
main()

41
First term/Algorithms/1-2/4.py Executable file
View File

@ -0,0 +1,41 @@
def binary_search(arr: list, item: int) -> int:
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == item:
break
if arr[mid] > item:
high = mid - 1
continue
low = mid + 1
if arr[mid] < item:
mid += 1
return mid
def main() -> None:
# Config
arr = [5, 2, 6, 1, 9, 4, 3, 2, 4, 5]
# Main code
sorted_arr = [arr[-1]]
ans = [0]
for num_index in range(len(arr)-2, -1, -1):
index = binary_search(sorted_arr, arr[num_index])
sorted_arr.insert(index, arr[num_index])
ans.append(index)
print(ans[::-1])
if __name__ == "__main__":
main()

12
First term/Algorithms/2-2/1.py Executable file
View File

@ -0,0 +1,12 @@
def main() -> None:
n = int(input())
index = 0
while 2 ** index < n:
index += 1
print(int(2 ** index == n))
if __name__ == "__main__":
main()

20
First term/Algorithms/2-2/2.py Executable file
View File

@ -0,0 +1,20 @@
def main() -> int:
a = int(input())
if a < 10:
return a
numbers = []
for divider in range(9, 1, -1):
while a % divider == 0:
a //= divider
numbers.append(divider)
if a >= 10:
return 0
return int("".join(map(str, sorted(numbers))))
if __name__ == "__main__":
print(main())

21
First term/Algorithms/2-2/3.py Executable file
View File

@ -0,0 +1,21 @@
def main() -> None:
n = int(input())
number = 1
numbers = []
while len(numbers) < n:
num = number
for divider in 2, 3, 5:
while num % divider == 0:
num //= divider
if num == 1:
numbers.append(number)
number += 1
print(numbers[n-1])
if __name__ == "__main__":
main()

24
First term/Algorithms/2-2/4.py Executable file
View File

@ -0,0 +1,24 @@
import heapq
def main() -> None:
# Config
arr = [1, 2, 3, 5]
k = 3
# Main code
heap = [(arr[0]/arr[j], 0, j) for j in range(1, len(arr))]
heapq.heapify(heap)
for _ in range(k):
val, i, j = heapq.heappop(heap)
if i < len(arr) - 1:
heapq.heappush(heap, (arr[i+1]/arr[j], i+1, j))
print([arr[i], arr[j]])
if __name__ == "__main__":
main()
# O(k * log(n)), где n - длина массива arr

21
First term/Algorithms/4/1.py Executable file
View File

@ -0,0 +1,21 @@
def main() -> None:
arr = [86, 90, 27, 29, 38, 30, 40]
my_dict = [None] * 7
for num in arr:
key = num % 7
d = 1
while my_dict[key] is not None:
key += d
if key >= len(arr)-1:
d = -1
key -= 1
my_dict[key] = num
print(my_dict)
if __name__ == "__main__":
main()

15
First term/Algorithms/4/2.py Executable file
View File

@ -0,0 +1,15 @@
def main(string: str) -> None:
some_dict = {}
for char in string:
if some_dict.get(char) is None:
some_dict[char] = 1
continue
some_dict[char] += 1
for key in some_dict.keys():
print(f"'{key}': {some_dict[key]}")
if __name__ == "__main__":
main("hello world")

19
First term/Algorithms/4/3.py Executable file
View File

@ -0,0 +1,19 @@
def main() -> None:
# Config
arr = [-1, 2, 3, 4, 7]
n = 5
# Main code
some_dict = {}
for index in range(len(arr)):
key = n - arr[index]
if some_dict.get(key) is not None:
print(some_dict[key], index)
break
if some_dict.get(arr[index]) is None:
some_dict[arr[index]] = index
if __name__ == "__main__":
main()

30
First term/Algorithms/4/4.py Executable file
View File

@ -0,0 +1,30 @@
def main() -> None:
# Config
first_arr = [1, 2, 3, 4, 5]
second_arr = [0, 2, 4, 6, 8]
# Main code
some_dict = {}
ans = set()
for index in range(max(len(first_arr), len(second_arr))):
if index < len(first_arr):
first_number = first_arr[index]
if some_dict.get(first_number) is None:
some_dict[first_number] = 1
elif some_dict[first_number] == 2:
ans.add(first_number)
if index < len(second_arr):
second_number = second_arr[index]
if some_dict.get(second_number) is None:
some_dict[second_number] = 2
elif some_dict[second_number] == 1:
ans.add(second_number)
print(list(ans))
if __name__ == "__main__":
main()

16
First term/Algorithms/4/5.py Executable file
View File

@ -0,0 +1,16 @@
def main() -> None:
# Config
arr = ["а", "b", "с", "d", "с", "е", "f"]
# Main code
some_dict = {}
for index in range(len(arr)):
if some_dict.get(arr[index]) is not None:
print(arr[index])
break
some_dict[arr[index]] = index
if __name__ == "__main__":
main()

23
First term/Algorithms/4/6.py Executable file
View File

@ -0,0 +1,23 @@
def main() -> None:
# Config
input_string = "minimum"
# Main code
some_dict = {}
for char in input_string:
if some_dict.get(char) is None:
some_dict[char] = 1
continue
some_dict[char] += 1
for char in input_string:
if some_dict[char] == 1:
print(char)
break
if __name__ == "__main__":
main()

17
First term/Algorithms/README.md Executable file
View File

@ -0,0 +1,17 @@
# Algorithms
[Таблица с баллами](https://docs.google.com/spreadsheets/d/135vbCsW6saNCQs6ftMX8vYrR1yVyBFGC8ENsjEpcQBc/edit#gid=0)
number | name | grade
:----: | --------------------------------------------------------------------- | :---:
1 | Метод половинного деления. Метод хорд | ✅
1.2 | Бинарный поиск | ✅
2 | Числовые алгоритмы | ✅
2.2 | Работа с делением -_- | ✅
3 | Алгоритмы длинной арифметики: сложение, вычитание, умножение, деление | ✅
4 | Рекурсия | ✅
5 | Алгоритмы сортировки массивов | ✅
6 | Структуры данных (часть 1) | ✅
extra | Структуры данных (часть 2) | ✅
[Back](/NKTKLN/mirea-projects)

View File

@ -0,0 +1,34 @@
#include <ctime>
#include <cmath>
#include <iostream>
using namespace std;
int main() {
// srand(time(0));
int n = rand() % 50;
int *arr = new int[n];
cout << "[ ";
for (int index = 0; index < n; ++index) {
arr[index] = rand() % 100;
cout << arr[index] << " ";
}
cout << "] (" << n << ")" << endl;
int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0;
for (int index = 0; index < n; ++index) {
if (arr[index] % 2 != 0) ++a;
if (int(sqrt(arr[index])) == sqrt(arr[index]) && int(sqrt(arr[index])) % 2 == 0) ++b;
if (arr[index] % 3 == 0 && arr[index] % 5 != 0) ++c;
if ((2 ^ index) < arr[index] && arr[index] < tgamma(index + 1)) ++d;
if (index + 1 < n && index - 1 >= 0 && arr[index] < (arr[index - 1] + arr[index + 1]) / 2) ++e;
if (index % 2 == 1 && arr[index] % 2 != 0) ++f;
}
cout << a << " " << b << " " << c << " " << d << " " << e << " " << f << endl;
delete[] arr;
return 0;
}

View File

@ -0,0 +1,46 @@
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
void printNumbersInOrder(const string &filename) {
ifstream inputFile(filename);
if (!inputFile.is_open()) {
cerr << "Unable to open the file: " << filename << endl;
return;
}
queue<int> singleDigitQueue;
queue<int> doubleDigitQueue;
int number;
while (inputFile >> number) {
if (number >= 10) {
doubleDigitQueue.push(number);
}
else {
singleDigitQueue.push(number);
}
}
while (!singleDigitQueue.empty()) {
cout << singleDigitQueue.front() << " ";
singleDigitQueue.pop();
}
while (!doubleDigitQueue.empty()) {
cout << doubleDigitQueue.front() << " ";
doubleDigitQueue.pop();
}
inputFile.close();
}
int main() {
string filename = "input.txt";
printNumbersInOrder(filename);
return 0;
}

View File

@ -0,0 +1,31 @@
#include <ctime>
#include <iostream>
using namespace std;
int main() {
// srand(time(0));
int arraySize = rand() % 50;
int *numbers = new int[arraySize];
cout << "[ ";
for (int index = 0; index < arraySize; ++index) {
numbers[index] = rand() % 100;
cout << numbers[index] << " ";
}
cout << "] (" << arraySize << ")" << endl;
int divisibleByFiveCount = 0;
int divisibleByFiveSum = 0;
for (int index = 0; index < arraySize; ++index) {
if (numbers[index] % 5 == 0 && numbers[index] % 7 != 0) {
divisibleByFiveSum += numbers[index];
++divisibleByFiveCount;
}
}
cout << divisibleByFiveCount << " " << divisibleByFiveSum << endl;
delete[] numbers;
return 0;
}

View File

@ -0,0 +1,43 @@
#include <ctime>
#include <iostream>
using namespace std;
int main() {
srand(time(0));
int arraySize = rand() % 50;
int *numbers = new int[arraySize];
cout << "[ ";
for (int index = 0; index < arraySize; ++index) {
numbers[index] = rand() % 3; // 100
cout << numbers[index] << " ";
}
cout << "] (" << arraySize << ")" << endl;
bool hasTwoConsecutiveZeros = false;
bool hasThreeConsecutiveZeros = false;
int consecutiveZerosCount = 0;
for (int index = 0; index < arraySize; ++index) {
if (numbers[index] != 0) {
consecutiveZerosCount = 0;
continue;
}
if (consecutiveZerosCount == 1) {
hasTwoConsecutiveZeros = true;
}
if (consecutiveZerosCount == 2) {
hasThreeConsecutiveZeros = true;
break;
}
++consecutiveZerosCount;
}
cout << hasTwoConsecutiveZeros << " " << hasThreeConsecutiveZeros << endl;
delete[] numbers;
return 0;
}

View File

@ -0,0 +1,55 @@
#include <ctime>
#include <iostream>
using namespace std;
struct Node {
int data;
Node *next;
Node(int value) : data(value), next(nullptr) {}
};
Node *createList(int size) {
if (size <= 0)
{
return nullptr;
}
Node *element = new Node(1);
Node *head = element;
for (int index = 0; index < size - 1; index++)
{
Node *new_node = new Node(index);
element->next = new_node;
element = new_node;
}
return head;
}
void printList(Node *head) {
Node *ptr = head;
while (ptr)
{
cout << ptr->data << " -> ";
ptr = ptr->next;
}
cout << "nullptr" << endl;
}
int sumOfListElements(Node *head) {
int sum = 0;
while (head != nullptr)
{
sum += head->data;
head = head->next;
}
return sum;
}
int main() {
srand(time(0));
Node *head = createList(10);
printList(head);
cout << sumOfListElements(head) << endl;
return 0;
}

View File

@ -0,0 +1,33 @@
#include <ctime>
#include <iostream>
using namespace std;
int main() {
srand(time(0));
int arraySize = rand() % 50;
int *numbers = new int[arraySize];
cout << "[ ";
for (int index = 0; index < arraySize; ++index) {
numbers[index] = rand() % 10;
cout << numbers[index] << " ";
}
cout << "] (" << arraySize << ")" << endl;
bool isDescending = true;
int previousNumber = numbers[0];
for (int index = 0; index < arraySize; ++index) {
if (numbers[index] >= previousNumber) {
isDescending = false;
break;
}
previousNumber = numbers[index];
}
cout << isDescending << endl;
delete[] numbers;
return 0;
}

134
First term/Algorithms/extra/6.cpp Executable file
View File

@ -0,0 +1,134 @@
#include <ctime>
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
Node(int value) : data(value), next(nullptr) {}
};
Node* constructList(int size) {
if (size <= 0) {
return nullptr;
}
Node* element = new Node(rand() % 100 + 1);
Node* head = element;
for (int i = 0; i < size - 1; i++) {
Node* new_node = new Node(rand() % 100 + 1);
element->next = new_node;
element = new_node;
}
return head;
}
bool isListEmpty(Node* head) {
return (head == nullptr);
}
int countOfListElements(Node* head) {
int count = 0;
while (head != nullptr) {
++count;
head = head->next;
}
return count;
}
void addElementToHead(Node*& head, int value) {
Node* element = new Node(value);
element->next = head;
head = element;
}
void addElementToLast(Node*& head, int value) {
Node* element = new Node(value);
Node* ptr = head;
while (ptr) {
if (ptr->next == nullptr) {
ptr->next = element;
break;
}
ptr = ptr->next;
}
}
void addElementToN(Node*& head, int value, int index) {
Node* element = new Node(value);
Node* ptr = head;
while (ptr) {
--index;
if (index < 0) {
element->next = head;
break;
}
if (index == 0) {
element->next = ptr->next;
ptr->next = element;
break;
}
ptr = ptr->next;
}
}
void printList(Node* head) {
Node* ptr = head;
while (ptr) {
cout << ptr->data << " -> ";
ptr = ptr->next;
}
cout << "nullptr" << endl;
}
Node* copyListExceptFirst(Node* head) {
if (head == nullptr || head->next == nullptr) {
return nullptr;
}
Node* newHead = new Node(head->next->data);
Node* current = newHead;
Node* original = head->next->next;
while (original) {
current->next = new Node(original->data);
current = current->next;
original = original->next;
}
return newHead;
}
int main() {
srand(time(0));
Node* numbers = nullptr;
cout << isListEmpty(numbers) << endl;
numbers = constructList(10);
printList(numbers);
addElementToHead(numbers, 1);
printList(numbers);
addElementToLast(numbers, 10);
printList(numbers);
addElementToN(numbers, 5, 5);
printList(numbers);
Node* newList = copyListExceptFirst(numbers);
printList(newList);
cout << countOfListElements(numbers) << endl;
return 0;
}

203
First term/Algorithms/extra/7.cpp Executable file
View File

@ -0,0 +1,203 @@
#include <map>
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
Node(int value) : data(value), next(nullptr) {}
};
Node* createList(int size) {
if (size <= 0) {
return nullptr;
}
Node* element = new Node(1);
Node* head = element;
for (int index = 0; index < size - 1; index++) {
Node* new_node = new Node(index);
element->next = new_node;
element = new_node;
}
return head;
}
void printList(Node* head) {
Node* ptr = head;
while (ptr) {
cout << ptr->data << " -> ";
ptr = ptr->next;
}
cout << "nullptr" << endl;
}
bool areListsEqual(Node* head1, Node* head2) {
Node* ptr1 = head1;
Node* ptr2 = head2;
while (ptr1 && ptr2) {
if (ptr1->data != ptr2->data) {
return false;
}
ptr1 = ptr1->next;
ptr2 = ptr2->next;
}
return ptr1 == ptr2;
}
bool doAllElementsExist(Node* head1, Node* head2) {
map<int, bool> m;
Node* ptr = head2;
while (ptr) {
m[ptr->data] = true;
ptr = ptr->next;
}
ptr = head1;
while (ptr) {
if (!m[ptr->data]) {
return false;
}
ptr = ptr->next;
}
return true;
}
bool hasDuplicateElements(Node* head) {
map<int, bool> m;
Node* ptr = head;
while (ptr) {
if (m[ptr->data]) {
return true;
}
m[ptr->data] = true;
ptr = ptr->next;
}
return false;
}
void moveToLast(Node*& head) {
Node* newHead = head->next;
Node* ptr = head;
while (ptr->next != nullptr) {
ptr = ptr->next;
}
head->next = nullptr;
ptr->next = head;
head = newHead;
}
void moveToFirst(Node*& head) {
Node* ptr = head;
while (ptr->next->next != nullptr) {
ptr = ptr->next;
}
Node* newHead = ptr->next;
ptr->next = nullptr;
newHead->next = head;
head = newHead;
}
void appendList(Node*& head1, Node* head2) {
Node* ptr = head1;
while (ptr->next != nullptr) {
ptr = ptr->next;
}
ptr->next = head2;
}
void reverseList(Node*& head) {
Node* newHead = nullptr;
Node* ptr = head;
while (ptr) {
Node* nextPtr = ptr->next;
ptr->next = newHead;
newHead = ptr;
ptr = nextPtr;
}
head = newHead;
}
void keepDistinctElements(Node*& head) {
map<int, bool> m;
Node* newHead = nullptr;
Node* ptr = head;
Node* prev = nullptr;
while (ptr) {
if (!m[ptr->data]) {
m[ptr->data] = true;
if (!newHead) {
newHead = ptr;
}
if (prev) {
prev->next = ptr;
}
prev = ptr;
}
ptr = ptr->next;
}
if (prev) {
prev->next = nullptr;
}
head = newHead;
}
int main() {
srand(time(0));
Node* list1 = createList(10);
Node* list2 = createList(10);
appendList(list2, new Node(10));
printList(list1);
printList(list2);
cout << areListsEqual(list1, list2) << endl;
cout << doAllElementsExist(list1, list2) << endl;
cout << hasDuplicateElements(list1) << endl;
moveToLast(list1);
printList(list1);
moveToFirst(list1);
printList(list1);
appendList(list1, list2);
printList(list1);
reverseList(list1);
printList(list1);
keepDistinctElements(list1);
printList(list1);
return 0;
}

View File

@ -0,0 +1,31 @@
#include <iostream>
using namespace std;
int main() {
int* arr;
int temp;
int size = 10;
int shift = 23;
arr = new int[size];
for (int index = 0; index < size; ++ index) {
arr[index] = index;
cout << arr[index] << " ";
}
cout << endl;
shift %= size;
for (int count = 0; count < shift; ++count) {
temp = arr[9];
for (int index = size-1; index > 0; --index)
arr[index] = arr[index-1];
arr[0] = temp;
}
for (int index = 0; index < size; ++index)
cout << arr[index] << " ";
cout << endl;
return 0;
}

View File

@ -0,0 +1,24 @@
#include <stack>
#include <fstream>
#include <iostream>
using namespace std;
int main() {
stack<char> stack;
ifstream inputFile("input.txt");
if (inputFile.is_open()) {
while (inputFile) {
stack.push(inputFile.get());
}
}
stack.pop();
while (!stack.empty()) {
cout << char(stack.top());
stack.pop();
}
return 0;
}

325
First term/Informatics/IT-1.md Executable file
View File

@ -0,0 +1,325 @@
# Рабочая тетрадь № 1
## Задачи № 1
### № 1
```math
4 mb = 4 * 1024 * 1024 * 8 bit = 33554432 bit
```
### № 2
```math
2 gb = 2 * 1024 * 1024 * 1024 byte = 2147483648 byte
```
### № 3
```math
6291456 byte = 6291456 / 1024 / 1024 mb = 6 mb
```
## Задачи № 2
### № 1
```math
log2(26) = 5 bit
```
### № 2
```math
log2(5) = 3 bit
```
### № 3
```math
log2(21) = 5 bit
```
## Задачи № 3
### № 1
```math
-0.5 * log2(0.5) = 0.5
-0.5 * log2(0.5) = 0.5
H = 0.5 + 0.5 = 1
```
### № 2
```math
-1/6 * log2(1/6) = 0.431
-1/6 * log2(1/6) = 0.431
-1/6 * log2(1/6) = 0.431
-1/6 * log2(1/6) = 0.431
-1/6 * log2(1/6) = 0.431
-1/6 * log2(1/6) = 0.431
H = 0.431 + 0.431 + 0.431 + 0.431 + 0.431 + 0.431 = 2586
```
### № 3
```math
-0.6 * log2(0.6) = 0.442
-0.4 * log2(0.4) = 0.529
H = 0.442 + 0.529 = 0.971
```
## Задачи № 4
### № 1
```math
77
```
### № 2
```math
u
```
### № 3
```math
73 74 75 64 65 6E 74
```
## Задачи № 5
### № 1
```math
110010010
```
### № 2
```math
101000011
```
### № 3
```math
Да
```
## Задачи № 6
### № 1
```math
00111011
000 000 111 111 111 000 111 111
```
### № 2
```math
001 011 010 110 011 010 001 111
01011001
```
### № 3
```math
CCz oYo mdm ppS uRu tpt wee Qrr __* Rss acc iBi eee nn% Fcc jee
Computer_science
```
## Задачи № 7
### № 1
```math
B 1010100
C 0011110
0110101
3
```
### № 2
```math
A 0101010
B 1010100
C 0011110
ρ(A,B)
A 0101010
B 1010100
0000001
6
ρ(A,C)
A 0101010
C 0011110
1001011
3
ρ(B,C)
B 1010100
C 0011110
0110101
3
ρ(A,B) ≤ ρ(A,C) + ρ(C,B) - Да
ρ(A,C) ≤ ρ(A,B) + ρ(B,C) - Да
ρ(B,C) ≤ ρ(B,A) + ρ(A,C) - Да
Да
```
### № 3
```math
d = min(6, 3, 3) = 3
3 >= 2n + 1
n = 1
```
## Тест
1. 1
2. 3
3. 2
4. 4
5. 4
6. 2
7. 3
8. 1
9. 3
10. 4
## Задачи № 8
### № 1
```python
print("Калинин Никита Викторович ЭФБО-09-23")
```
### № 2
```python
a = int(input())
b = int(input())
print(a + b)
```
### № 3
```python
a = float(input())
print(x ** 5 - 2 * x ** 3 + 1)
```
## Задачи № 9
### № 1
```python
strange = [[], 1]
print(type(strange))
```
### № 2
```python
for x in 0, 1:
for y in 0, 1:
if (x or y) and (not(x) or y) and not(x and y):
print(x, y)
```
### № 3
```python
some_list = []
for i in range(4):
some_list.append(i)
for i in some_list[::-1]:
print(i)
```
## Задачи № 10
### № 1
```python
from math import log, ceil
def hartly(n: int) -> float:
return ceil(log(n, 2))
print(hartly(int(input())))
```
### № 2
```python
from math import log
def entropy(p1, p2: float) -> float:
h1 = -1 * p1 * log(p1, 2)
h2 = -1 * p2 * log(p2, 2)
return h1 + h2
a = float(input())
b = float(input())
print(entropy(a, b))
```
### № 3
```python
from math import tan, cos, sin, e, log
def some_func(x: float) -> float:
return tan(cos(x) * sin(2 * x) / x * e**x) ** log(x, 7)
x = float(input())
print(some_func(x))
```
### № 4
```python
def parity_bit(string: str) -> str:
if string.count("1") % 2 == 0:
return string + "0"
return string + "1"
s = input()
print(parity_bit(s))
```

286
First term/Informatics/IT-2.md Executable file
View File

@ -0,0 +1,286 @@
# Рабочая тетрадь № 2
## Задачи № 1
### № 1
```math
101010 bin = 1 * 2 ^ 1 + 1 * 2 ^ 3 + 1 * 2 ^ 5 = 42 dec
```
### № 2
```math
563 oct = 3 * 8 ^ 0 + 6 * 8 ^ 1 + 5 * 8 ^ 2 = 371 dec
```
### № 3
```math
A1286 двенадцатиричной = 6 * 12 ^ 0 + 8 * 12 ^ 1 + 2 * 12 ^ 2 + 1 * 12 ^ 3 + 10 * 12 ^ 4 = 209478 dec
```
### № 4
```math
127 dec = 1111111 bin
7
```
## Задачи № 2
### № 1
```math
367 / 7 = 52 3
52 / 7 = 7 3
7 / 7 = 1 0
1 / 7 = 0 1
1033
```
### № 2
```math
1143 / 12 = 95 3
95 / 12 = 7 11
7 / 12 = 0 7
7B3
```
### № 3
```ma# Рабочая тетрадь № 2
## Задачи № 1
### № 1
```math
101010 bin = 1 * 2 ^ 1 + 1 * 2 ^ 3 + 1 * 2 ^ 5 = 42 dec
```
### № 2
```math
563 oct = 3 * 8 ^ 0 + 6 * 8 ^ 1 + 5 * 8 ^ 2 = 371 dec
```
### № 3
```math
A1286 двенадцатиричной = 6 * 12 ^ 0 + 8 * 12 ^ 1 + 2 * 12 ^ 2 + 1 * 12 ^ 3 + 10 * 12 ^ 4 = 209478 dec
```
### № 4
```math
127 dec = 1111111 bin
7
```th
127 oct = 7 * 8 ^ 0 + 2 * 8 ^ 1 + 1 * 8 ^ 2 = 87 dec
87 / 9 = 9 6
9 / 9 = 1 0
1 / 9 = 0 1
106
```
### № 4
```math
AB4 = 4 * 13 ^ 0 + 11 * 13 ^ 1 + 10 * 13 ^ 2 = 1837
1837 / 6 = 306 1
306 / 6 = 51 0
51 / 6 = 8 3
8 / 6 = 1 2
1 / 6 = 0 1
12301
```
## Задачи № 3
### № 1
```math
0010 1001 1101
29D
```
### № 2
```math
1 1 4 7 4 5 3
1001100111100101011
```
### № 3
```math
1 2 7
0000 0101 0111
57
```
### № 4
```math
C 3 E 1
110000111100001
8
```
### № 5
```math
A F 3 8
0101 0011 1100 0110 1001
53C69
001 010 011 110 001 101 001
1236151
1010011110001101001
```
## Тест № 2
1. A - 100101
2. C - 26
3. D - 11011000
4. B - X<Z<Y
5. C - 7
6. A - 3
7. C - 100000
8. 6 9 12
9. 5
10. 81
001011101010100000001110
001011101010100000001110
## Задачи № 4
### № 1
```python
n = int(input())
a = input()
print(int(a, n))
```
## Задачи № 5
### № 1
```python
a = int(input())
if a % 10 == 3 or a // 10 == 3:
print("Входит")
else:
print("Не входит")
```
### № 2
```python
a = int(input())
if a % 10 > a // 10:
print("Первая цифра больше")
elif a % 10 < a // 10:
print("Вторая цифра больше")
else:
print("Они одинаковые")
```
### № 3
```python
a = float(input())
b = float(input())
c = float(input())
d = b ** 2 - 4 * a * c
if d >= 0:
a1 = (-b + d ** 0.5) / (2 * a)
a2 = (-b - d ** 0.5) / (2 * a)
print(a1, a2)
else:
print("Корней нет")
```
## Задачи № 6
### № 1
```python
a = int(input())
i = 0
while a % i != 0:
i += 1
print(i)
```
### № 2
```python
a = int(input())
i = 0
while a != 0:
i += a
a -= 1
print(i)
```
### № 3
```python
a = int(input())
k = 0
for i in range(2, a // 2 + 1):
if a % i == 0:
k += 1
if k <= 0:
print("Простое")
else:
print("Не простое")
```
### № 4
```python
a = int(input())
n = int(input())
new = ""
while a > 0:
r = a % n
new += str(r)
a //= n
print(new[::-1])
```

150
First term/Informatics/IT-3.md Executable file
View File

@ -0,0 +1,150 @@
# Рабочая тетрадь № 3
## Задачи № 1
### № 1
```math
132 dec / 2 = 66 0
66 / 2 = 33 0
33 / 2 = 17 1
17 / 2 = 8 1
8 / 2 = 4 0
4 / 2 = 2 0
2 / 2 = 1 0
1 / 2 = 0 1
136 dec = 10001100 bin
0000000010001100
```
### № 2
```math
0000000000000000 bin = 0 dec
1111111111111111 bin = 65535 dec
```
## Задачи № 2
### № 1
```math
12 dec = 1100 bin
0.0001100
0.0001100
0.0001100
```
### № 2
```math
35 dec = 100011 bin
1.00100011
1.11011100
1.11011101
```
### № 3
```math
1.1011100
1.1111011
1111011 bin = 123 dec
-123
```
## Задачи № 3
### № 1
```math
A dec = 78 B dec = 56
A bin = +1001110
B bin = +0111000
[A]п = [A]ок = [A]дк = 0.1001110
[B]п = [B]ок = [B]дк = 0.0111000
0.1001110
0.0111000
---------
0.10000110
10000110 bin = 134 dec
```
## Тест № 3
1. B (прямой, обратный или дополнительный код)
2. C (выглядит одинаково в прямом, обратном и дополнительном кодах)
3. A (обратный код)
4. A (из обратного кода прибавлением единицы к младшему разряду без переноса в знаковый разряд)
5. B (прямой код)
6. A (00001110)
7. D (118)
8. B (+39)
9. A (10111111)
10. 10011001
## Задачи № 4
### № 1
```python
from math import *
def f(x, y: float) -> float:
return log(abs(sin(x+y)))
x = float(input())
y = float(input())
print(f(x, y))
```
### № 2
```python
from math import *
def (x, y: float) -> float:
if sin(x + y) <= -0.5:
return arctg(abs(x * y) ** (1/3) * (x * e ** y))
if -0.5 < sin(x + y) < 0.5:
return 3 * log(abs(x * y), 3)
if sin(x + y) >= 0.5:
return x ** 3 + y ** 1.5
x = float(input())
y = float(input())
print(f(x, y))
```
### № 3
```python
from math import *
def f(x: float) -> float:
return cos(e * x) ** 3 + sin(abs(x))
a = float(input())
b = float(input())
hx = float(input())
for x in range(a, b+1, hx):
print(f(x))
```

127
First term/Informatics/IT-4.md Executable file
View File

@ -0,0 +1,127 @@
# Рабочая тетрадь № 4
## Задачи № 1
### № 1
```math
AvB⇒A~B
a b f
0 0 0
1 1 1
0 1 0
1 0 0
A̅v¬(B~A)⊕B
a b f
0 0 1
1 1 1
1 0 0
0 1 1
AvB⇒C
a b c f
0 0 0 1
0 0 1 1
0 1 1 1
1 0 1 1
1 1 1 1
0 1 0 0
1 0 0 0
1 1 0 0
```
### № 2
```math
(4)
```
### № 3
```math
(2)
```
### № 4
```math
(4)
```
### № 5
```math
4
```
### № 6
```math
1 0 0 0
```
### № 7
```math
C, 2
```
## Тест № 3
1. 2 (Таблица истинности)
2. 1 (¬А&¬В)
3. 2 (Сергей)
4. 1 (¬A ¬B ¬C)
5. 4 (X Y Z)
6. 4 (2)
7. 3 (3)
8. 30
9. 10
10. M, B
## Задачи № 4
### № 1
```python
k = int(input())
n = int(input())
print(2 << k-1 + 2 << n-1)
```
### № 2
```python
n = int(input())
if (n > 0 and (n & (n - 1))) == 0:
print("Yes")
else:
print("No")
```
### № 3
```python
a = int(input())
k = int(input())
print(a | (1 << k))
```
### № 4
```python
n = int(input())
k = int(input())
ans = n & ~((1 << k) - 1)
print(ans)
print(bin(n & ~((1 << k) - 1)))
```

212
First term/Informatics/IT-5.md Executable file
View File

@ -0,0 +1,212 @@
# Рабочая тетрадь № 5
## Задачи № 1
### № 1
```math
¬( ( x ∧ y ) ̅z ) ≡ ¬( z → x ) ¬( z → y )
¬( x ∧ y ) ∧ z ≡ ¬( ̅z x ) ¬( ̅z y )
( ̅x ̅y ) ∧ z ≡ ( z ∧ ̅x ) ( z ∧ ̅y )
( ̅x ̅y ) ∧ z ≡ z ∧ ( ̅x ̅y )
( ̅x ̅y ) ∧ z ≡ ( ̅x ̅y ) ∧ z
```
### № 2
```math
¬( ( x ∧ y ) ̅z) ≡ ¬( z → x ) ¬( z → y )
x y z f1 f2
0 0 0 0 0
0 0 1 1 1
0 1 1 1 1
0 1 0 0 0
1 0 0 0 0
1 0 1 1 1
1 1 0 0 0
1 1 1 0 0
```
### № 3
```math
F(x,y,z) = ( ̅z → x ) ↔ ( ̅x │ y )
x y z f
0 0 0 0
0 0 1 1
0 1 1 0
0 1 0 1
1 0 0 1
1 0 1 1
1 1 0 1
1 1 1 1
ДНФ: ( y ∧ ̅z ) ( ̅y ∧ z ) x
КНФ: ( x ̅y z ) ∧ ( x y z )
```
### № 4
```math
A = ( x → y ) ∧ ( x → ̅y ) ∧ x
A = ( ̅x y ) ∧ ( ̅x ̅y ) ∧ x
A = ( ̅x ( y ∧ ̅y ) ) ∧ x
A = ( ̅x 0 ) ∧ x
A = ̅x ∧ x
A = 0
```
## Задачи № 2
### № 1
```math
1) x ∧ y x ∧ y ̅x ∧ ̅y
( x ∧ y ) ( ̅x ∧ ̅y )
( x ∧ y ) ( ̅x ∧ ̅y )
x ↔ y
2) ( x ̅y ) ∧ ( ̅x y ) ∧ ( ̅x ̅y )
( x ̅y ) ∧ ̅x
( x ∧ ̅x ) ( ̅y ∧ ̅x )
0 ¬( y ∧ x )
y | x
```
### № 2
```math
( x1 x2 x3 ) ∧ ( ̅x1 ̅x2 x3 ) ∧ ( x1 x2 ̅x3 ) ∧ ( ̅x1 ̅x2 ̅x3 )
```
### № 3
```math
1) ( x ̅x )
2) ( ̅x ∧ ̅y ) ( x ∧ y ) ( ̅x ∧ y ) ( x ∧ ̅y )
```
### № 4
```math
1) ( x ∧ ̅x )
2) ( ̅x ̅y ) ∧ ( x y ) ∧ ( ̅x y ) ∧ ( x ̅y )
```
### № 5
```math
НФ: ( x ∧ y ∧ z ) ( ̅x ∧ y ∧ z ) ( ̅x ∧ ̅y ∧ z )
CКНФ: ( x y z ) ∧ ( x ̅y z ) ∧ ( ̅x y z ) ∧ ( ̅x y ̅z ) ∧ ( ̅x ̅y z )
```
## Тест № 5
1. 4
2. 1
3. 1
4. 2
5. 1
6. 3
7. 4
8. 2
9. 2
10. 4
## Задачи № 3
### № 1
```python
a = int(input())
if 100 <= a < 1000 and a % 5 == 0:
print("Является")
else:
print("Не является")
```
### № 2
```python
a = int(input())
b = int(input())
c = int(input())
if (a % 2) + (b % 2) + (c % 2) <= 1:
print("2 и более")
else:
print("Меньше 2")
```
### № 3
```python
x, y = float(input()), float(input())
if (x >= 0 and x**2 + y**2 <= 1) or (y <= 1 and x >= 0 and y >= x - 1):
print("Yes")
else:
print("No")
```
### № 4
```python
import math as m
x, y = float(input()), float(input())
if (y <= m.sin(x) and 0 <= y <= 0.5 and 0 <= x <= m.pi):
print("Yes")
else:
print("No")
```
### № 5
```python
x, y = float(input()), float(input())
if (x <= 0 and x**2 + y**2 <= 1) or (x**2 + y**2 <= 1 and y >= x):
print("Yes")
else:
print("No")
```
## Задачи № 4
### № 1
```python
# 3
x, y = float(input()), float(input())
if (x >= 0 and x**2 + y**2 <= 1) or (y <= 1 and x >= 0 and y >=// x - 1):
print("Yes")
else:
print("No")
# 4
import math as m
x, y = float(input()), float(input())
if (y <= m.sin(x) and 0 <= y <= 0.5 and 0 <= x <= m.pi):
print("Yes")
else:
print("No")
# 5
x, y = float(input()), float(input())
if (x <= 0 and x**2 + y**2 <= 1) or (x**2 + y**2 <= 1 and y >= x):
print("Yes")
else:
print("No")
```

92
First term/Informatics/IT-6.md Executable file
View File

@ -0,0 +1,92 @@
# Рабочая тетрадь № 6
## Задачи № 3
### № 1
```python
word = intput()
if word[::-1] == word:
print("Палиндром")
else:
print("Не палиндром")
```
### № 2
```python
word = intput()
print(word.lower())
```
### № 3
```python
word = intput()
print(word.upper())
```
### № 4
```python
word = intput()
for num in 0,1,2,3,4,5,6,7,8,9:
if str(num) in word:
print("Есть")
break
else:
print("Нет")
```
### № 5
```python
word = intput()
print(" ".join(list(word)))
```
### № 6
```python
c = "C"
print(ord(c))
```
## Задачи № 4
### № 1
```python
print(list(range(0, 101, 17)))
```
### № 2
```python
w = []
c = []
for _ in range(5):
w.appen(input())
c.append(w[-1])
print(w, c)
```
## Задачи № 5
### № 1
```python
a = set([1,2,3,4])
b = set([4,34,2,6])
print(a | b)
print(a & b)
print(a - b)
```

107
First term/Informatics/IT-7.md Executable file
View File

@ -0,0 +1,107 @@
# Рабочая тетрадь № 7
## Задачи № 1
### № 1
```math
А) 0, 0, 0, 5
Б) 0, 0, 5, 0
В) 10, 10, 20, 6
```
### № 2
```math
1) s1 = 1, n = 1, n = 2, s = 1,5
2) s1 = 1, n = 2, n = 3, s1 = 1,8
3) 1,8 3 4 2,08
4) 2,08 4 5 2,8
```
### № 3
```math
5
```
### № 4
```math
А) z = 1
Б) z = 1,9375
```
## Задачи № 2
### № 1
![image](./src/Screenshot%202023-12-02%20094710.png)
### № 2
![image](./src/Screenshot%202023-12-02%20094736.png)
### № 3
![image](./src/Screenshot%202023-12-02%20094750.png)
## Задачи № 3
### № 1
```python
n = 10
b = 2
k = a // b
l = n % b
print("Остаток:", k)
print("Целая часть:", l)
```
### № 2
```python
def Sign(x):
if x < 0:
return -1
elif x > 0:
return 1
return 0
```
### № 3
```python
word = str(input())
if word == word[::-1]:
print("yes")
else:
print("no")
```
### № 4
```python
sec = int(input())
day = 86400
hour = 3600
minute = 60
second = 1
print(sec // day, (sec % day) // hour, ((sec % day) % hour) // minute, ((sec % day) % hour) % minute, sep=':')
```
### № 5
```python
def fibonacci_of(n):
if n in {0, 1}:
return n
return fibonacci_of(n - 1) + fibonacci_of(n - 2)
print(fibonacci_of(int(input())))
```

73
First term/Informatics/IT-8.md Executable file
View File

@ -0,0 +1,73 @@
# Рабочая тетрадь № 6
## Задачи № 1
### № 1
```python
def function(string: str) -> str:
half_length = len(string) // 2
return string[:half_length][::-1] + string[half_length:][::-1]
some_string = "привет"
print(function(some_string))
```
### № 2
```python
def is_valid_bracket_structure(expression: str) -> bool:
stack = []
bracket_pairs = {')': '(', '}': '{', ']': '['}
for char in expression:
if char in bracket_pairs.values():
stack.append(char)
elif char in bracket_pairs.keys():
if not stack or bracket_pairs[char] != stack.pop():
return False
return not stack
expression = ")(, ())((), (, )))), ((())" # "(), (())(), ()(), ((()))"
if is_valid_bracket_structure(expression):
print("Скобочная структура правильная.")
else:
print("Скобочная структура неправильная.")
```
## Задачи № 2
### № 1
```python
import random
class Warrior:
def __init__(self, name: str, health: int = 100):
self.name = name
self.health = health
def attack(self, enemy: Warrior):
print(f"{self.name} атакует {enemy.name}")
enemy.health -= 20
print(f"У {enemy.name} осталось {enemy.health} единиц здоровья")
warrior1 = Warrior("Воин 1")
warrior2 = Warrior("Воин 2")
while warrior1.health > 0 and warrior2.health > 0:
attacker = random.choice([warrior1, warrior2])
defender = warrior2 if attacker == warrior1 else warrior1
attacker.attack(defender)
if warrior1.health <= 0:
print(f"{warrior2.name} одержал победу!")
elif warrior2.health <= 0:
print(f"{warrior1.name} одержал победу!")
else:
print("Бой окончен в ничью.")
```

View File

@ -0,0 +1,14 @@
# Algorithms
number | name | grade
:----: | --------------------------------------------------------------------- | :---:
1 | Работа с размером информации | ✅
2 | Системы счисления | ✅
3 | Прямой, обратный, дополненный коды | ✅
4 | Алгебра логики (часть 1) | ✅
5 | Алгебра логики (часть 2) | ✅
6 | Алгебра логики (python) | ✅
7 | Машина Тьюринга | ✅
8 | ООП | ✅
[Back](/NKTKLN/mirea-projects)

Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

26
README.md Executable file
View File

@ -0,0 +1,26 @@
# Mirea projects
***project codename:*** Lucy
This repository was created for saving and transferring MIREA Institute assignment solutions.
## First term
* [Algorithms](/NKTKLN/mirea-projects/src/branch/main/First%20term/Algorithms)
* [Informatics](/NKTKLN/mirea-projects/src/branch/main/First%20term/Informatics)
## Second term
* [Algorithms](/NKTKLN/mirea-projects/src/branch/main/Second%20term/Algorithms)
* [Discrete math](/NKTKLN/mirea-projects/src/branch/main/Second%20term/Discrete%20math)
* [Familiarization practice](/NKTKLN/mirea-projects/src/branch/main/Second%20term/Familiarization%20practice)
* [Industrial programming technologies](/NKTKLN/mirea-projects/src/branch/main/Second%20term/Industrial%20programming%20technologies)
* [Term papper](/NKTKLN/mirea-projects/src/branch/main/Term%20papers/%D0%AD%D0%A4%D0%91%D0%9E-09-23%20%D0%9A%D0%B0%D0%BB%D0%B8%D0%BD%D0%B8%D0%BD%20%D0%9D%D0%B8%D0%BA%D0%B8%D1%82%D0%B0%20%D0%92%D0%B8%D0%BA%D1%82%D0%BE%D1%80%D0%BE%D0%B2%D0%B8%D1%87%20%D0%9A%D1%83%D1%80%D1%81%D0%BE%D0%B2%D0%B0%D1%8F%20%D1%80%D0%B0%D0%B1%D0%BE%D1%82%D0%B0%20%D0%BF%D0%BE%20%D0%B8%D0%BD%D0%B4%D1%83%D1%81%D1%82%D1%80%D0%B5%D0%B0%D0%BB%D1%8C%D0%BD%D0%BE%D0%BC%D1%83%20%D0%BF%D1%80%D0%BE%D0%B3%D1%80%D0%B0%D0%BC%D0%BC%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8E%20%D0%BF%D1%80%D0%BE%D0%B4%D0%B2%D0%B8%D0%BD%D1%83%D1%82%D1%8B%D0%B9%20%D1%83%D1%80%D0%BE%D0%B2%D0%B5%D0%BD%D1%8C%202%20%D1%81%D0%B5%D0%BC%D0%B5%D1%81%D1%82%D1%80)
## Third term
* [Discrete math](/NKTKLN/mirea-projects/src/branch/main/Third%20term/Discrete%20math)
* [Industrial programming technologies](/NKTKLN/mirea-projects/src/branch/main/Third%20term/Industrial%20programming%20technologies)
* [Frontend and backend development](/NKTKLN/mirea-projects/src/branch/main/Third%20term/Frontend%20and%20backend%20development)
* [Programming of corporate systems](/NKTKLN/mirea-projects/src/branch/main/Third%20term/Programming%20of%20corporate%20systems)
* [Artificial intelligence systems and big data](/NKTKLN/mirea-projects/src/branch/main/Third%20term/Artificial%20intelligence%20systems%20and%20big%20data)

View File

@ -0,0 +1,66 @@
#include <iostream>
using namespace std;
struct Node {
int minNum;
int maxNum;
Node *left;
Node *right;
Node(int minValue, int maxValue) : minNum(minValue), maxNum(maxValue), left(nullptr), right(nullptr) {}
};
Node *buildTree(int minValue, int maxValue) {
if (minValue >= maxValue) return nullptr;
Node *root = new Node(minValue, maxValue);
if (maxValue - minValue > 1) {
int middleValue = (minValue + maxValue) / 2;
root->left = buildTree(minValue, middleValue);
root->right = buildTree(middleValue, maxValue);
}
return root;
}
int searchX(Node *&node, int value) {
if(node == nullptr) return 0;
int count = 0;
if(node->minNum <= value && node->maxNum >= value) count++;
return count + searchX(node->left, value) + searchX(node->right, value);
}
void printTree(Node *node) {
if (node == nullptr) return;
printTree(node->left);
cout << "(" << node->minNum << ", " << node->maxNum << ") ";
printTree(node->right);
}
int searchSum(Node *&node, int minValue, int maxValue) {
if (node == nullptr || minValue >= maxValue) return 0;
if(node->left != nullptr || node->right != nullptr) return searchSum(node->left, minValue, maxValue) + searchSum(node->right, minValue, maxValue);
int sum = 0;
if (node->maxNum <= maxValue && node->maxNum > minValue) sum += node->maxNum;
if (node->minNum == minValue) sum += node->minNum;
return sum;
}
int main() {
int a, b;
cout << "> ";
cin >> a;
cout << "> ";
cin >> b;
Node *root = buildTree(a, b);
printTree(root);
cout << endl;
cout << "> ";
cin >> a;
cout << "Number of elements containing the number : " << searchX(root, a) << endl;
cout << "> ";
cin >> a;
cout << "> ";
cin >> b;
cout << "Counting the sum of elements on the segment : " << searchSum(root, a, b) << endl;
return 0;
}

106
Second term/Algorithms/1/1.cpp Executable file
View File

@ -0,0 +1,106 @@
#include <ctime>
#include <iostream>
using namespace std;
struct Node {
int key;
int count;
Node *left;
Node *right;
int height;
Node(int value) : key(value), left(nullptr), right(nullptr), height(0), count(1) {}
};
int getHeight(Node *node) {
return (node == nullptr) ? -1 : node->height;
}
void updateHeight(Node *&node) {
node->height = max(getHeight(node->left), getHeight(node->right)) + 1;
}
void insert(Node *&node, int key) {
if (node->key > key) {
if (node->left == nullptr) node->left = new Node(key);
else insert(node->left, key);
}
else if (node->key < key) {
if (node->right == nullptr) node->right = new Node(key);
else insert(node->right, key);
}
else node->count++;
updateHeight(node);
}
Node *search(Node *&node, int key) {
if (node == nullptr) return nullptr;
if (node->key == key) return node;
return search((node->key > key) ? node->left : node->right, key);
}
Node *getMin(Node *&node) {
if (node == nullptr) return nullptr;
if (node->left == nullptr) return node;
return getMin(node->left);
}
Node *getMax(Node *&node) {
if (node == nullptr) return nullptr;
if (node->right == nullptr) return node;
return getMax(node->right);
}
Node *deleteNode(Node *&node, int key) {
if (node == nullptr) return nullptr;
else if (node->key > key) node->left = deleteNode(node->left, key);
else if (node->key < key) node->right = deleteNode(node->right, key);
else if (node->key == key && node->count != 1) node->count--;
else {
if (node->left == nullptr || node->right == nullptr)
node = (node->left == nullptr) ? node->right : node->left;
else {
Node *maxLeft = getMax(node->left);
node->key = maxLeft->key;
node->left = deleteNode(node->left, maxLeft->key);
}
}
if (node != nullptr) updateHeight(node);
return node;
}
void printTree(Node *node) {
if (node == nullptr) return;
printTree(node->left);
cout << node->key << " (" << node->count << ") ";
printTree(node->right);
}
Node *generateRandomTree(int countOfNodes) {
Node *root = new Node(rand() % 100);
for (; countOfNodes > 0; countOfNodes--) insert(root, rand() % 100);
return root;
}
int main() {
srand(time(0));
Node *root = generateRandomTree(10);
cout << "root: " << root->key << endl;
printTree(root);
cout << endl;
insert(root, 9);
cout << "root: " << root->key << endl;
printTree(root);
cout << endl;
cout << "height: " << root->height + 1 << endl;
Node *buffer = search(root, 9);
cout << buffer << endl;
cout << "root: " << root->key << endl;
root = deleteNode(root, 9);
printTree(root);
cout << endl;
return 0;
}

155
Second term/Algorithms/1/2.cpp Executable file
View File

@ -0,0 +1,155 @@
#include <ctime>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
struct Node {
string name;
vector<string> numbers;
Node *left;
Node *right;
Node(string nameValue, string numberValue) {
name = nameValue;
numbers.push_back(numberValue);
right = nullptr;
left = nullptr;
}
};
Node *insert(Node *&node, string name, string number) {
if (node == nullptr) return new Node(name, number);
if (node->name > name) {
if (node->left == nullptr) node->left = new Node(name, number);
else insert(node->left, name, number);
}
else if (node->name < name) {
if (node->right == nullptr) node->right = new Node(name, number);
else insert(node->right, name, number);
}
else node->numbers.push_back(number);
return node;
}
Node *search(Node *&node, string name) {
if (node == nullptr) return nullptr;
if (node->name == name) return node;
return search((node->name > name) ? node->left : node->right, name);
}
Node *getMax(Node *&node) {
if (node == nullptr) return nullptr;
if (node->right == nullptr) return node;
return getMax(node->right);
}
Node *deleteNode(Node *&node, string name) {
if (node == nullptr) return nullptr;
else if (node->name > name) node->left = deleteNode(node->left, name);
else if (node->name < name) node->right = deleteNode(node->right, name);
else {
if (node->left == nullptr || node->right == nullptr)
node = (node->left == nullptr) ? node->right : node->left;
else {
Node *maxLeft = getMax(node->left);
node->name = maxLeft->name;
node->left = deleteNode(node->left, maxLeft->name);
}
}
return node;
}
void printTree(Node *node) {
if (node == nullptr) return;
printTree(node->left);
cout << node->name << ":" << endl;
for (vector<string>::const_iterator number = node->numbers.begin(); number != node->numbers.end(); number++)
cout << " * " << *number << endl;
printTree(node->right);
}
int main() {
srand(time(0));
Node *root = nullptr;
cout << "Phone book" << endl
<< "Use 'help' to output all available commands." << endl;
while (true) {
string inputCommand;
cout << "> ";
cin >> inputCommand;
if (inputCommand == "help")
cout << "Commands:" << endl
<< " * help - output all available commands" << endl
<< " * add - add a new record" << endl
<< " * del-person - delete person" << endl
<< " * del-number - delete phone number from a person" << endl
<< " * search - output phone numbers for a particular person" << endl
<< " * list - output all names and phone numbers for each person" << endl
<< " * exit - exit the program" << endl;
else if (inputCommand == "add") {
string name, phoneNumber;
cout << "Enter the person's name: ";
cin >> name;
cout << "Enter the person's phone number: ";
cin >> phoneNumber;
root = insert(root, name, phoneNumber);
cout << "The phone number '" << phoneNumber << "' was successfully added to the person named '" << name << "'." << endl;
}
else if (inputCommand == "del-person") {
string name;
cout << "Enter the person's name: ";
cin >> name;
root = deleteNode(root, name);
cout << "Person named '" << name << "' has been deleted." << endl;
}
else if (inputCommand == "del-number") {
string name;
cout << "Enter the person's name: ";
cin >> name;
Node *personNode = search(root, name);
if (personNode == nullptr) {
cout << "Person named '" << name << "' not found." << endl;
continue;
}
string phoneNumber;
cout << "Enter the person's phone number: ";
cin >> phoneNumber;
vector<string>::iterator position = find(personNode->numbers.begin(), personNode->numbers.end(), phoneNumber);
if (position == personNode->numbers.end()) {
cout << "The phone number '" << phoneNumber << "' of a person named '" << name << "' was not found." << endl;
continue;
}
personNode->numbers.erase(position);
cout << "The phone number '" << phoneNumber << "' of a person named '" << name << "' has been deleted." << endl;
}
else if (inputCommand == "search") {
string name;
cout << "Enter the person's name: ";
cin >> name;
Node *personNode = search(root, name);
if (personNode == nullptr) {
cout << "Person named '" << name << "' not found." << endl;
continue;
}
cout << "The phone numbers of a person named '" << name << "':" << endl;
for (vector<string>::const_iterator number = personNode->numbers.begin(); number != personNode->numbers.end(); number++)
cout << " * " << *number << endl;
}
else if (inputCommand == "list") {
cout << "List of all users and their phone numbers:" << endl;
printTree(root);
}
else if (inputCommand == "exit") {
cout << "Goodbye!" << endl;
break;
}
else cout << "Unknown command." << endl;
}
return 0;
}

View File

@ -0,0 +1,5 @@
.SILENT:
run:
g++ -o main "$(name).cpp"
./main
rm main

65
Second term/Algorithms/2/1.cpp Executable file
View File

@ -0,0 +1,65 @@
#include <ctime>
#include <iostream>
using namespace std;
struct Node {
int key;
int count;
Node *left;
Node *right;
int height;
Node(int value) : key(value), left(nullptr), right(nullptr), height(0), count(1) {}
};
int getHeight(Node *node) {
return (node == nullptr) ? -1 : node->height;
}
void updateHeight(Node *&node) {
node->height = max(getHeight(node->left), getHeight(node->right)) + 1;
}
int getBalance(Node *node) {
return (node == nullptr) ? 0 : getHeight(node->right) - getHeight(node->left);
}
void insert(Node *&node, int key) {
if (node->key > key) {
if (node->left == nullptr) node->left = new Node(key);
else insert(node->left, key);
}
else if (node->key < key) {
if (node->right == nullptr) node->right = new Node(key);
else insert(node->right, key);
}
else node->count++;
updateHeight(node);
}
void printTree(Node *node) {
if (node == nullptr) return;
printTree(node->left);
cout << node->key << " (" << node->count << ") " << "[" << getBalance(node) << "] | ";
printTree(node->right);
}
Node *generateRandomTree(int countOfNodes) {
Node *root = new Node(rand() % 100);
for (; countOfNodes > 0; countOfNodes--)
insert(root, rand() % 100);
return root;
}
int main() {
srand(time(0));
cout << "[] - balance | () - count" << endl << endl;
Node *root = generateRandomTree(10);
printTree(root);
cout << endl;
return 0;
}

108
Second term/Algorithms/2/2.cpp Executable file
View File

@ -0,0 +1,108 @@
#include <ctime>
#include <iostream>
using namespace std;
struct Node {
int key;
int count;
Node *left;
Node *right;
int height;
Node(int value) : key(value), left(nullptr), right(nullptr), height(0), count(1) {}
};
int getHeight(Node *node) {
return (node == nullptr) ? -1 : node->height;
}
void updateHeight(Node *&node) {
node->height = max(getHeight(node->left), getHeight(node->right)) + 1;
}
int getBalance(Node *node) {
return (node == nullptr) ? 0 : getHeight(node->right) - getHeight(node->left);
}
void swap(Node *&first, Node *&second) {
int firstKey = first->key;
first->key = second->key;
second->key = firstKey;
}
void rightRotate(Node *&node) {
swap(node, node->left);
Node *buffer = node->right;
node->right = node->left;
node->left = node->right->left;
node->right->left = node->right->right;
node->right->right = buffer;
updateHeight(node->right);
updateHeight(node);
}
void leftRotate(Node *&node) {
swap(node, node->right);
Node *buffer = node->left;
node->left = node->right;
node->right = node->left->right;
node->left->right = node->left->left;
node->left->left = buffer;
updateHeight(node->left);
updateHeight(node);
}
void balanceTree(Node *&node) {
int balance = getBalance(node);
if (balance == -2) {
if (getBalance(node->left) == 1) leftRotate(node->left);
rightRotate(node);
}
else if (balance == 2) {
if (getBalance(node->right) == -1) rightRotate(node->right);
leftRotate(node);
}
}
void insert(Node *&node, int key) {
if (node->key > key) {
if (node->left == nullptr) node->left = new Node(key);
else insert(node->left, key);
}
else if (node->key < key) {
if (node->right == nullptr) node->right = new Node(key);
else insert(node->right, key);
}
else node->count++;
updateHeight(node);
balanceTree(node);
}
void printTree(Node *node) {
if (node == nullptr) return;
printTree(node->left);
cout << node->key << " (" << node->count << ") " << "[" << getBalance(node) << "] | ";
printTree(node->right);
}
Node *generateRandomTree(int countOfNodes) {
Node *root = new Node(rand() % 100);
for (; countOfNodes > 0; countOfNodes--)
insert(root, rand() % 100);
return root;
}
int main() {
srand(time(0));
cout << "[] - balance | () - count" << endl << endl;
Node *root = generateRandomTree(10);
printTree(root);
cout << endl;
cout << "root height: " << root->height << endl;
cout << "root key: " << root->key << endl;
return 0;
}

151
Second term/Algorithms/2/3.cpp Executable file
View File

@ -0,0 +1,151 @@
#include <ctime>
#include <iostream>
using namespace std;
struct Node {
int key;
int count;
Node *left;
Node *right;
int height;
Node(int value) : key(value), left(nullptr), right(nullptr), height(0), count(1) {}
};
int getHeight(Node *node) {
return (node == nullptr) ? -1 : node->height;
}
void updateHeight(Node *&node) {
node->height = max(getHeight(node->left), getHeight(node->right)) + 1;
}
int getBalance(Node *node) {
return (node == nullptr) ? 0 : getHeight(node->right) - getHeight(node->left);
}
void swap(Node *&first, Node *&second) {
int firstKey = first->key;
first->key = second->key;
second->key = firstKey;
}
void rightRotate(Node *&node) {
swap(node, node->left);
Node *buffer = node->right;
node->right = node->left;
node->left = node->right->left;
node->right->left = node->right->right;
node->right->right = buffer;
updateHeight(node->right);
updateHeight(node);
}
void leftRotate(Node *&node) {
swap(node, node->right);
Node *buffer = node->left;
node->left = node->right;
node->right = node->left->right;
node->left->right = node->left->left;
node->left->left = buffer;
updateHeight(node->left);
updateHeight(node);
}
void balanceTree(Node *&node) {
int balance = getBalance(node);
if (balance == -2) {
if (getBalance(node->left) == 1) leftRotate(node->left);
rightRotate(node);
}
else if (balance == 2) {
if (getBalance(node->right) == -1) rightRotate(node->right);
leftRotate(node);
}
}
void insert(Node *&node, int key) {
if (node->key > key) {
if (node->left == nullptr) node->left = new Node(key);
else insert(node->left, key);
}
else if (node->key < key) {
if (node->right == nullptr) node->right = new Node(key);
else insert(node->right, key);
}
else node->count++;
updateHeight(node);
balanceTree(node);
}
Node *search(Node *&node, int key) {
if (node == nullptr) return nullptr;
if (node->key == key) return node;
return search((node->key > key) ? node->left : node->right, key);
}
Node *getMin(Node *&node) {
if (node == nullptr) return nullptr;
if (node->left == nullptr) return node;
return getMin(node->left);
}
Node *getMax(Node *&node) {
if (node == nullptr) return nullptr;
if (node->right == nullptr) return node;
return getMax(node->right);
}
Node *deleteNode(Node *&node, int key) {
if (node == nullptr) return nullptr;
else if (node->key > key) node->left = deleteNode(node->left, key);
else if (node->key < key) node->right = deleteNode(node->right, key);
else {
if (node->left == nullptr || node->right == nullptr)
node = (node->left == nullptr) ? node->right : node->left;
else {
Node *maxLeft = getMax(node->left);
node->key = maxLeft->key;
node->left = deleteNode(node->left, maxLeft->key);
}
}
if (node != nullptr) {
updateHeight(node);
balanceTree(node);
}
return node;
}
void printTree(Node *node) {
if (node == nullptr) return;
printTree(node->left);
cout << node->key << " (" << node->count << ") " << "[" << getBalance(node) << "] | ";
printTree(node->right);
}
Node *generateRandomTree(int countOfNodes, int head) {
Node *root = new Node(head);
for (; countOfNodes > 0; countOfNodes--)
insert(root, rand() % 100);
return root;
}
int main() {
srand(time(0));
cout << "[] - balance | () - count" << endl << endl;
Node *root = generateRandomTree(10, 8);
printTree(root);
cout << endl;
cout << "root height: " << root->height << endl;
cout << "root key: " << root->key << endl;
root = deleteNode(root, root->key);
cout << "root height: " << root->height << endl;
cout << "root key: " << root->key << endl;
printTree(root);
cout << endl;
return 0;
}

102
Second term/Algorithms/2/4.cpp Executable file
View File

@ -0,0 +1,102 @@
#include <iostream>
#define RED true
#define BLACK false
using namespace std;
struct Node {
int key;
Node *left;
Node *right;
Node *parent;
bool color;
Node(int value) : key(value), left(nullptr), right(nullptr), color(RED) {}
};
bool getColor(Node *node) {
if (node == nullptr) return BLACK;
return node->color;
}
void setColor(Node *node, bool color) {
if (node == nullptr) return;
node->color = color;
}
void insert(Node *&root, Node *&node, int key) {
if (root == nullptr) {
root = new Node(key);
setColor(root, BLACK);
return;
}
if (node->key > key) {
if (node->left == nullptr) {
node->left = new Node(key);
setColor(node->left, !getColor(node));
}
else insert(root, node->left, key);
}
else if (node->key <= key) {
if (node->right == nullptr) {
node->right = new Node(key);
setColor(node->right, !getColor(node));
}
else insert(root, node->right, key);
}
setColor(root, BLACK);
}
void printTree(Node *node) {
if (node == nullptr) return;
printTree(node->left);
cout << node->key << " (" << ((node->color == RED) ? "RED" : "BLACK") << ") " << endl;
printTree(node->right);
}
int blackHeight(Node* node) {
if (node == nullptr) return 1;
int leftHeight = blackHeight(node->left);
int rightHeight = blackHeight(node->right);
if (leftHeight != rightHeight) return 0;
if (leftHeight == 0 || rightHeight == 0) return 0;
if (getColor(node) == BLACK) leftHeight++;
return leftHeight;
}
void checkRedBlackTreeProperties(Node* root) {
if (blackHeight(root) != 0)
cout << "Correct" << endl;
else
cout << "Incorrect" << endl;
}
int main() {
Node *root = nullptr;
insert(root, root, 13);
insert(root, root, 8);
insert(root, root, 17);
insert(root, root, 15);
insert(root, root, 25);
insert(root, root, 22);
insert(root, root, 27);
insert(root, root, 1);
insert(root, root, 11);
insert(root, root, 6);
printTree(root);
cout << endl;
cout << "Checking for rules: ";
checkRedBlackTreeProperties(root);
cout << "Add 7" << endl;
insert(root, root, 7);
cout << "Checking for rules: ";
checkRedBlackTreeProperties(root);
return 0;
}

319
Second term/Algorithms/2/5.cpp Executable file
View File

@ -0,0 +1,319 @@
#include <ctime>
#include <iostream>
#define RED true
#define BLACK false
using namespace std;
struct Node {
int key;
Node *left;
Node *right;
Node *parent;
bool color;
Node(int value) : key(value), left(nullptr), right(nullptr), color(RED) {}
};
bool getColor(Node *node) {
if (node == nullptr) return BLACK;
return node->color;
}
void setColor(Node *node, bool color) {
if (node == nullptr) return;
node->color = color;
}
void rightRotate(Node *&root, Node *&node) {
Node *leftChild = node->left;
node->left = leftChild->right;
if(node->left != nullptr) node->left->parent = node;
leftChild->parent = node->parent;
if(node->parent == nullptr) root = leftChild;
else if(node == node->parent->left) node->parent->left = leftChild;
else node->parent->right = leftChild;
leftChild->right = node;
node->parent = leftChild;
}
void leftRotate(Node *&root, Node *&node) {
Node *rightChild = node->right;
node->right = rightChild->left;
if(node->right != nullptr) node->right->parent = node;
rightChild->parent = node->parent;
if(node->parent == nullptr) root = rightChild;
else if(node == node->parent->left) node->parent->left = rightChild;
else node->parent->right = rightChild;
rightChild->left = node;
node->parent = rightChild;
}
void fixRulesAfterInsertion(Node *&root, Node*& node) {
Node* parent = nullptr;
Node* grandParent = nullptr;
while (node != root && getColor(node) == RED && getColor(node->parent) == RED) {
parent = node->parent;
grandParent = parent->parent;
if(parent == grandParent->left) {
Node* uncle = grandParent->right;
if(getColor(uncle) == RED) {
setColor(uncle, BLACK);
setColor(parent, BLACK);
setColor(grandParent, RED);
node = grandParent;
}
else {
if(node == parent->right) {
leftRotate(root, parent);
node = parent;
parent = node->parent;
}
rightRotate(root, grandParent);
const bool color = grandParent->color;
grandParent->color = parent->color;
parent->color = color;
node = parent;
}
}
else {
Node* uncle = grandParent->left;
if(getColor(uncle) == RED) {
setColor(uncle, BLACK);
setColor(parent, BLACK);
setColor(grandParent, RED);
node = grandParent;
}
else {
if(node == parent->left) {
rightRotate(root, parent);
node = parent;
parent = node->parent;
}
leftRotate(root, grandParent);
const bool color = grandParent->color;
grandParent->color = parent->color;
parent->color = color;
node = parent;
}
}
}
setColor(root, BLACK);
}
void insertNode(Node *&root, Node *&node) {
if (root == nullptr) {
root = node;
return;
}
if (node->key < root->key) {
insertNode(root->left, node);
root->left->parent = root;
}
else if (node->key >= root->key) {
insertNode(root->right, node);
root->right->parent = root;
}
}
void insertNodeValue(Node *&root, const int key) {
Node *node = new Node(key);
insertNode(root, node);
fixRulesAfterInsertion(root, node);
}
Node *search(Node *&node, int key) {
if (node == nullptr) return nullptr;
if (node->key == key) return node;
return search((node->key > key) ? node->left : node->right, key);
}
Node *getMin(Node *&node) {
if (node == nullptr) return nullptr;
if (node->left == nullptr) return node;
return getMin(node->left);
}
Node *getMax(Node *&node) {
if (node == nullptr) return nullptr;
if (node->right == nullptr) return node;
return getMax(node->right);
}
int getChildrenCount(Node *&node) {
int count = 0;
if (node->left != nullptr) count++;
if (node->right != nullptr) count++;
return count;
}
Node *getChildOrMock(Node*& node) {
return node->left != nullptr ? node->left : node->right;
}
void transplantNode(Node *&root, Node *&toNode, Node *&fromNode) {
if (toNode == root) root = toNode;
else if (toNode == toNode->parent->left) toNode->parent->left = fromNode;
else toNode->parent->right = fromNode;
fromNode->parent = toNode->parent;
}
void fixRulesAfterRemoval(Node *&root, Node *&node) {
if (node == nullptr) return;
if (node == root) {
root = nullptr;
return;
}
if (getColor(node) == RED || getColor(node->left) == RED || getColor(node->right) == RED) {
Node *child = node->left != nullptr ? node->left : node->right;
if (node == node->parent->left) {
node->parent->left = child;
if (child != nullptr) child->parent = node->parent;
setColor(child, BLACK);
delete (node);
} else {
node->parent->right = child;
if (child != nullptr) child->parent = node->parent;
setColor(child, BLACK);
delete (node);
}
} else {
Node *sibling = nullptr;
Node *parent = nullptr;
Node *ptr = node;
setColor(ptr, BLACK);
while (ptr != root && getColor(ptr) == BLACK) {
parent = ptr->parent;
if (ptr == parent->left) {
sibling = parent->right;
if (getColor(sibling) == RED) {
setColor(sibling, BLACK);
setColor(parent, RED);
leftRotate(root, parent);
} else {
if (getColor(sibling->left) == BLACK && getColor(sibling->right) == BLACK) {
setColor(sibling, RED);
if(getColor(parent) == RED) setColor(parent, BLACK);
else setColor(parent, BLACK);
ptr = parent;
} else {
if (getColor(sibling->right) == BLACK) {
setColor(sibling->left, BLACK);
setColor(sibling, RED);
rightRotate(root, sibling);
sibling = parent->right;
}
setColor(sibling, parent->color);
setColor(parent, BLACK);
setColor(sibling->right, BLACK);
leftRotate(root, parent);
break;
}
}
} else {
sibling = parent->left;
if (getColor(sibling) == RED) {
setColor(sibling, BLACK);
setColor(parent, RED);
rightRotate(root, parent);
} else {
if (getColor(sibling->left) == BLACK && getColor(sibling->right) == BLACK) {
setColor(sibling, RED);
if (getColor(parent) == RED) setColor(parent, BLACK);
else setColor(parent, BLACK);
ptr = parent;
} else {
if (getColor(sibling->left) == BLACK) {
setColor(sibling->right, BLACK);
setColor(sibling, RED);
leftRotate(root, sibling);
sibling = parent->left;
}
setColor(sibling, parent->color);
setColor(parent, BLACK);
setColor(sibling->left, BLACK);
rightRotate(root, parent);
break;
}
}
}
}
if (node == node->parent->left) node->parent->left = nullptr;
else node->parent->right = nullptr;
delete(node);
setColor(root, BLACK);
}
}
Node *deleteNode(Node *&node, int key) {
if (node == nullptr) return nullptr;
if (node->key > key) return deleteNode(node->left, key);
if (node->key < key) return deleteNode(node->right, key);
if (node->left == nullptr || node->right == nullptr) return node;
Node *minRight = getMin(node->right);
node->key = minRight->key;
return deleteNode(node->right, minRight->key);
}
void deleteNodeValue(Node *&root, const int key) {
Node* node = deleteNode(root, key);
fixRulesAfterRemoval(root, node);
}
void printTree(Node *node) {
if (node == nullptr) return;
printTree(node->left);
cout << node->key << " (" << ((node->color == RED) ? "RED" : "BLACK") << ")"<< endl;
printTree(node->right);
}
Node *generateRandomTree(int countOfNodes) {
Node *root = nullptr;
for (; countOfNodes > 0; countOfNodes--) insertNodeValue(root, rand() % 100);
return root;
}
int blackHeight(Node* node) {
if (node == nullptr) return 1;
int leftHeight = blackHeight(node->left);
int rightHeight = blackHeight(node->right);
if (leftHeight != rightHeight) return 0;
if (leftHeight == 0 || rightHeight == 0) return 0;
if (getColor(node) == BLACK) leftHeight++;
return leftHeight;
}
void checkRedBlackTreeProperties(Node* root) {
cout << "Checking for rules: ";
if (blackHeight(root) != 0)
cout << "Correct" << endl;
else
cout << "Incorrect" << endl;
}
int main() {
srand(time(0));
Node *root = generateRandomTree(10);
printTree(root);
checkRedBlackTreeProperties(root);
cout << "rm " << root->key << endl;
deleteNodeValue(root, root->key);
printTree(root);
checkRedBlackTreeProperties(root);
return 0;
}

151
Second term/Algorithms/2/6.cpp Executable file
View File

@ -0,0 +1,151 @@
#include <iostream>
using namespace std;
struct Node {
int key;
int count;
Node *left;
Node *right;
Node(int value) : key(value), left(nullptr), right(nullptr), count(1) {}
};
Node *getMax(Node *&node) {
if (node == nullptr) return nullptr;
if (node->right == nullptr) return node;
return getMax(node->right);
}
Node *rightRotate(Node *node) {
Node *buffer = node->left;
node->left = buffer->right;
buffer->right = node;
return buffer;
}
Node *leftRotate(Node *node) {
Node *buffer = node->right;
node->right = buffer->left;
buffer->left = node;
return buffer;
}
void insertNode(Node *node, int key) {
if (node->key > key) {
if (node->left == nullptr) node->left = new Node(key);
else insertNode(node->left, key);
}
else if (node->key < key) {
if (node->right == nullptr) node->right = new Node(key);
else insertNode(node->right, key);
}
else node->count++;
}
Node *deleteNode(Node *&node, int key) {
if (node == nullptr) return nullptr;
else if (node->key > key) node->left = deleteNode(node->left, key);
else if (node->key < key) node->right = deleteNode(node->right, key);
else if (node->key == key && node->count != 1) node->count--;
else {
if (node->left == nullptr || node->right == nullptr)
node = (node->left == nullptr) ? node->right : node->left;
else {
Node *maxLeft = getMax(node->left);
node->key = maxLeft->key;
node->left = deleteNode(node->left, maxLeft->key);
}
}
return node;
}
Node *splay(Node *root, int key) {
if (root == nullptr || root->key == key) return root;
if (root->key > key) {
if (root->left == nullptr) return root;
if (root->left->key > key) {
root->left->left = splay(root->left->left, key);
root = rightRotate(root);
}
else if (root->left->key < key) {
root->left->right = splay(root->left->right, key);
if (root->left->right != nullptr) root->left = leftRotate(root->left);
}
return (root->left == nullptr) ? root : rightRotate(root);
}
if (root->right == nullptr) return root;
if (root->right->key > key) {
root->right->left = splay(root->right->left, key);
if (root->right->left != nullptr) root->right = rightRotate(root->right);
}
else if (root->right->key < key) {
root->right->right = splay(root->right->right, key);
root = leftRotate(root);
}
return (root->right == nullptr) ? root : leftRotate(root);
}
void searchNodeValue(Node *&root, const int key) {
root = splay(root, key);
}
void insertNodeValue(Node *&root, const int key) {
insertNode(root, key);
root = splay(root, key);
}
void deleteNodeValue(Node *&root, const int key) {
root = splay(deleteNode(root, key), key);
}
// ============================================= //
int getKey(Node *&node) {
if (node == nullptr) return -1;
return node->key;
}
void printTree(Node *&node) {
if (node == nullptr) return;
printTree(node->left);
cout << node->key << " (" << node->count << ") [" << getKey(node->left)
<< ", " << getKey(node->right) << "]" << endl;
printTree(node->right);
}
Node *generateRandomTree(int countOfNodes) {
Node *root = new Node(rand() % 100);
for (; countOfNodes > 0; countOfNodes--) insertNodeValue(root, rand() % 100);
return root;
}
// ============================================= //
int main() {
srand(13);
Node *root = generateRandomTree(10);
printTree(root);
cout << "root: " << root->key << endl;
cout << endl << "Search (8)" << endl;
searchNodeValue(root, 8);
printTree(root);
cout << "root: " << root->key << endl;
cout << endl << "Insert (73)" << endl;
insertNodeValue(root, 73);
printTree(root);
cout << "root: " << root->key << endl;
cout << endl << "Delete (38)"<< endl;
deleteNodeValue(root, 38);
printTree(root);
cout << "root: " << root->key << endl;
return 0;
}

82
Second term/Algorithms/3/1.cpp Executable file
View File

@ -0,0 +1,82 @@
#include <iostream>
using namespace std;
class Heap {
private:
int *data;
int length;
int lastIndex;
void swap(int firstIndex, int secondIndex);
void heapify(int index);
public:
Heap(int maxHeapLength);
Heap(int* array, int arrayLength, int maxHeapLength);
~Heap();
void print();
};
Heap::Heap(int maxHeapLength) {
this->data = new int[maxHeapLength];
this->length = maxHeapLength;
this->lastIndex = 0;
}
Heap::Heap(int* array, int arrayLength, int maxHeapLength) {
this->data = new int[maxHeapLength];
this->length = maxHeapLength;
this->lastIndex = arrayLength - 1;
copy(array, array+arrayLength, this->data);
for (int index = this->lastIndex / 2; index >= 0; index--)
heapify(index);
}
Heap::~Heap() { delete[] this->data; }
void Heap::swap(int firstIndex, int secondIndex) {
int tempElement = this->data[firstIndex];
this->data[firstIndex] = this->data[secondIndex];
this->data[secondIndex] = tempElement;
}
void Heap::heapify(int index) {
int largestIndex = index;
int leftIndex = 2 * index + 1;
int rightIndex = 2 * index + 2;
if (leftIndex <= this->lastIndex && this->data[leftIndex] > this->data[largestIndex])
largestIndex = leftIndex;
if (rightIndex <= this->lastIndex && this->data[rightIndex] > this->data[largestIndex])
largestIndex = rightIndex;
if (largestIndex == index)
return;
swap(index, largestIndex);
heapify(largestIndex);
}
void Heap::print() {
for (int index = 0; index <= this->lastIndex; index++)
cout << this->data[index] << " ";
cout << endl;
}
int main() {
int length;
cout << "Enter array length: ";
cin >> length;
int* arr = new int[length];
cout << "Enter elements: ";
for (int index = 0; index < length; index++)
cin >> arr[index];
Heap* heap = new Heap(arr, length, 100);
heap->print();
delete heap;
return 0;
}

136
Second term/Algorithms/3/2.cpp Executable file
View File

@ -0,0 +1,136 @@
#include <iostream>
using namespace std;
class Heap {
private:
int *data;
int length;
int lastIndex;
void heapify(int index);
void insertFix(int index);
void swap(int firstIndex, int secondIndex);
public:
Heap(int maxHeapLength);
Heap(int* array, int arrayLength, int maxHeapLength);
~Heap();
void print();
int getMax();
void deleteMax();
void insert(int element);
void merge(Heap *heap);
};
Heap::Heap(int maxHeapLength) {
this->data = new int[maxHeapLength];
this->length = maxHeapLength;
this->lastIndex = -1;
}
Heap::Heap(int* array, int arrayLength, int maxHeapLength) {
this->data = new int[maxHeapLength];
this->length = maxHeapLength;
this->lastIndex = arrayLength - 1;
copy(array, array+arrayLength, this->data);
for (int index = arrayLength / 2 - 1; index >= 0; index--)
heapify(index);
}
Heap::~Heap() { delete[] this->data; }
void Heap::heapify(int index) {
int largestIndex = index;
int leftIndex = 2 * index + 1;
int rightIndex = 2 * index + 2;
if (leftIndex <= this->lastIndex && this->data[leftIndex] > this->data[largestIndex])
largestIndex = leftIndex;
if (rightIndex <= this->lastIndex && this->data[rightIndex] > this->data[largestIndex])
largestIndex = rightIndex;
if (largestIndex == index)
return;
swap(index, largestIndex);
heapify(largestIndex);
}
void Heap::insertFix(int index) {
int parentIndex = (index - 1) / 2;
if (index <= parentIndex || this->data[parentIndex] >= this->data[index])
return;
swap(index, parentIndex);
insertFix(parentIndex);
}
void Heap::swap(int firstIndex, int secondIndex) {
int tempElement = this->data[firstIndex];
this->data[firstIndex] = this->data[secondIndex];
this->data[secondIndex] = tempElement;
}
void Heap::print() {
for (int index = 0; index <= this->lastIndex; index++)
cout << this->data[index] << " ";
cout << endl;
}
int Heap::getMax() {
if (this->lastIndex == -1)
return -1;
return this->data[0];
}
void Heap::deleteMax() {
if (this->lastIndex == -1)
return;
this->lastIndex--;
this->data[0] = this->data[this->lastIndex+1];
heapify(0);
}
void Heap::insert(int element) {
this->lastIndex++;
this->data[this->lastIndex] = element;
insertFix(this->lastIndex);
}
void Heap::merge(Heap *heap) {
copy(heap->data, heap->data+heap->lastIndex+1, this->data + this->lastIndex + 1);
this->lastIndex += heap->lastIndex + 1;
for (int index = (this->lastIndex + 1) / 2 - 1; index >= 0; index--)
heapify(index);
}
int main() {
int length = 10;
int arr[] = {1, 3, 2, 4, 8, 7, 10, 14, 9, 16};
int length2 = 9;
int arr2[] = {6, 5, 11, 16, 17, 18, 20, 24, 29};
Heap* heap = new Heap(arr, length, 100);
Heap* heap2 = new Heap(arr2, length2, 100);
heap->print();
cout << "Max element: " << heap->getMax() << endl;
cout << "Remove the max element." << endl;
heap->deleteMax();
heap->print();
cout << "Insert element (19)." << endl;
heap->insert(19);
heap->print();
cout << "Print heap №2." << endl;
heap2->print();
cout << "Merge heap and heap2." << endl;
heap->merge(heap2);
heap->print();
delete heap;
delete heap2;
return 0;
}

113
Second term/Algorithms/3/3.cpp Executable file
View File

@ -0,0 +1,113 @@
#include <iostream>
using namespace std;
class Heap {
private:
int *data;
int length;
int lastIndex;
void heapify(int index);
void insertFix(int index);
void swap(int firstIndex, int secondIndex);
public:
Heap(int maxHeapLength);
Heap(int* array, int arrayLength, int maxHeapLength);
~Heap();
int getLength();
int deleteMin();
void insert(int element);
};
Heap::Heap(int maxHeapLength) {
this->data = new int[maxHeapLength];
this->length = maxHeapLength;
this->lastIndex = -1;
}
Heap::Heap(int* array, int arrayLength, int maxHeapLength) {
this->data = new int[maxHeapLength];
this->length = maxHeapLength;
this->lastIndex = arrayLength - 1;
copy(array, array+arrayLength, this->data);
for (int index = arrayLength / 2 - 1; index >= 0; index--)
heapify(index);
}
Heap::~Heap() { delete[] this->data; }
void Heap::heapify(int index) {
int largestIndex = index;
int leftIndex = 2 * index + 1;
int rightIndex = 2 * index + 2;
if (leftIndex <= this->lastIndex && this->data[leftIndex] < this->data[largestIndex])
largestIndex = leftIndex;
if (rightIndex <= this->lastIndex && this->data[rightIndex] < this->data[largestIndex])
largestIndex = rightIndex;
if (largestIndex == index)
return;
swap(index, largestIndex);
heapify(largestIndex);
}
void Heap::insertFix(int index) {
int parentIndex = (index - 1) / 2;
if (index <= parentIndex || this->data[parentIndex] <= this->data[index])
return;
swap(index, parentIndex);
insertFix(parentIndex);
}
void Heap::swap(int firstIndex, int secondIndex) {
int tempElement = this->data[firstIndex];
this->data[firstIndex] = this->data[secondIndex];
this->data[secondIndex] = tempElement;
}
int Heap::getLength() { return this->lastIndex + 1; }
int Heap::deleteMin() {
if (this->lastIndex == -1)
return -1;
int minElement = this->data[0];
this->lastIndex--;
this->data[0] = this->data[this->lastIndex+1];
heapify(0);
return minElement;
}
void Heap::insert(int element) {
this->lastIndex++;
this->data[this->lastIndex] = element;
insertFix(this->lastIndex);
}
int main() {
cout << "Array: [5, 4, 2, 8]" << endl;
int length = 4;
int arr[] = {5, 4, 2, 8};
Heap* heap = new Heap(arr, length, 10);
int spending = 0;
int sumOfMinElements, firstMin, secondMin;
while (heap->getLength() > 1) {
firstMin = heap->deleteMin();
secondMin = heap->deleteMin();
sumOfMinElements = firstMin + secondMin;
cout << firstMin << " + " << secondMin << " = " << sumOfMinElements << endl;
spending += sumOfMinElements;
heap->insert(sumOfMinElements);
}
cout << spending << endl;
delete heap;
return 0;
}

89
Second term/Algorithms/3/4.cpp Executable file
View File

@ -0,0 +1,89 @@
#include <iostream>
using namespace std;
struct Node {
int key;
Node *left;
Node *right;
Node(int value) : key(value), left(nullptr), right(nullptr) {}
};
bool leftOrRight(Node *&node, int* depth = 0) {
if (node == nullptr) return -1;
int leftDepth = 0;
int rightDepth = 0;
leftOrRight(node->left, &leftDepth);
leftOrRight(node->right, &rightDepth);
*depth += 1 + min(leftDepth, rightDepth);
return leftDepth > rightDepth;
}
void insert(Node *&node, int key) {
if (node->left == nullptr) {
node->left = new Node(key);
return;
}
else if (node->right == nullptr) {
node->right = new Node(key);
return;
}
int temp = 0;
insert((leftOrRight(node, &temp)) ? node->right : node->left, key);
}
int getKey(Node *&node) { return (node == nullptr) ? -1 : node->key; }
void printTree(Node *node) {
if (node == nullptr) return;
printTree(node->left);
cout << node->key << " [" << getKey(node->left) << ", " << getKey(node->right) << "]" << endl;
printTree(node->right);
}
bool isMinBinaryHeap(Node *&node) {
if (node == nullptr) return true;
if (node->left != nullptr && node->left->key < node->key) return false;
if (node->right != nullptr && node->right->key < node->key) return false;
return isMinBinaryHeap(node->left) && isMinBinaryHeap(node->right);
}
bool isMaxBinaryHeap(Node *&node) {
if (node == nullptr) return true;
if (node->left != nullptr && node->left->key > node->key) return false;
if (node->right != nullptr && node->right->key > node->key) return false;
return isMaxBinaryHeap(node->left) && isMaxBinaryHeap(node->right);
}
void checkForBinaryHeap(Node*& root) {
if (isMaxBinaryHeap(root)) cout << "Max binary heap" << endl;
else if (isMinBinaryHeap(root)) cout << "Min binary heap" << endl;
else cout << "Not a binary heap" << endl;
}
int main() {
int value;
int length;
cout << "Enter array length: ";
cin >> length;
int* arr = new int[length];
cout << "Enter elements: ";
cin >> value;
Node *root = new Node(value);
for (int index = 1; index < length; index++) {
cin >> value;
insert(root, value);
}
printTree(root);
checkForBinaryHeap(root);
return 0;
}

88
Second term/Algorithms/3/5.cpp Executable file
View File

@ -0,0 +1,88 @@
#include <iostream>
using namespace std;
class Heap {
private:
int *data;
int length;
int lastIndex;
void heapify(int index);
void swap(int firstIndex, int secondIndex);
public:
Heap(int* array, int arrayLength);
int* getArray();
void heapSort();
};
Heap::Heap(int* array, int arrayLength) {
this->data = array;
this->length = arrayLength - 1;
this->lastIndex = arrayLength - 1;
for (int index = arrayLength / 2 - 1; index >= 0; index--)
heapify(index);
}
void Heap::heapify(int index) {
int largestIndex = index;
int leftIndex = 2 * index + 1;
int rightIndex = 2 * index + 2;
if (leftIndex <= this->lastIndex && this->data[leftIndex] > this->data[largestIndex])
largestIndex = leftIndex;
if (rightIndex <= this->lastIndex && this->data[rightIndex] > this->data[largestIndex])
largestIndex = rightIndex;
if (largestIndex == index)
return;
swap(index, largestIndex);
heapify(largestIndex);
}
void Heap::swap(int firstIndex, int secondIndex) {
int tempElement = this->data[firstIndex];
this->data[firstIndex] = this->data[secondIndex];
this->data[secondIndex] = tempElement;
}
int* Heap::getArray() { return this->data; }
void Heap::heapSort() {
if (this->lastIndex == 0) return;
swap(0, this->lastIndex--);
heapify(0);
heapSort();
}
void pyramidalSorting(int *array, int length) {
Heap* heap = new Heap(array, length);
heap->heapSort();
array = heap->getArray();
}
void printArray(int *array, int length) {
for (int index = 0; index < length; index++)
cout << array[index] << " ";
cout << endl;
}
int main() {
int length;
cout << "Enter array length: ";
cin >> length;
int* array = new int[length];
cout << "Enter elements: ";
for (int index = 0; index < length; index++)
cin >> array[index];
printArray(array, length);
pyramidalSorting(array, length);
printArray(array, length);
delete[] array;
return 0;
}

164
Second term/Algorithms/3/6.cpp Executable file
View File

@ -0,0 +1,164 @@
#include <string>
#include <iostream>
using namespace std;
struct heapnode {
int key;
string data;
};
class Heap {
private:
struct heapnode *data;
int length;
int lastIndex;
void heapify(int index);
void insertFix(int index);
void swap(int firstIndex, int secondIndex);
public:
Heap(int maxHeapLength);
~Heap();
void print();
struct heapnode *deleteMax();
void insert(int priority, string name);
struct heapnode *search(int priority, string name);
void edit(struct heapnode *node, int newPriority, string newName);
};
Heap::Heap(int maxHeapLength) {
this->data = new struct heapnode[maxHeapLength];
this->length = maxHeapLength;
this->lastIndex = -1;
}
Heap::~Heap() { delete[] this->data; }
void Heap::heapify(int index) {
int largestIndex = index;
int leftIndex = 2 * index + 1;
int rightIndex = 2 * index + 2;
if (leftIndex <= this->lastIndex && this->data[leftIndex].key > this->data[largestIndex].key)
largestIndex = leftIndex;
if (rightIndex <= this->lastIndex && this->data[rightIndex].key > this->data[largestIndex].key)
largestIndex = rightIndex;
if (largestIndex == index)
return;
swap(index, largestIndex);
heapify(largestIndex);
}
void Heap::insertFix(int index) {
int parentIndex = (index - 1) / 2;
if (index <= parentIndex || this->data[parentIndex].key >= this->data[index].key)
return;
swap(index, parentIndex);
insertFix(parentIndex);
}
void Heap::swap(int firstIndex, int secondIndex) {
struct heapnode tempElement = this->data[firstIndex];
this->data[firstIndex] = this->data[secondIndex];
this->data[secondIndex] = tempElement;
}
struct heapnode *Heap::search(int priority, string name) {
for (int index = 0; index <= this->lastIndex; index++)
if (this->data[index].data == name && this->data[index].key == priority)
return &this->data[index];
return nullptr;
}
struct heapnode *Heap::deleteMax() {
if (this->lastIndex == -1) return nullptr;
this->lastIndex--;
swap(0, this->lastIndex+1);
heapify(0);
return &this->data[this->lastIndex+1];
}
void Heap::insert(int priority, string name) {
this->lastIndex++;
this->data[this->lastIndex].key = priority;
this->data[this->lastIndex].data = name;
insertFix(this->lastIndex);
}
void Heap::edit(struct heapnode *node, int newPriority, string newName) {
node->data = newName;
node->key = newPriority;
heapify(0);
}
void Heap::print() {
for (int index = 0; index <= this->lastIndex; index++)
cout << "[" << this->data[index].key << "] " << this->data[index].data << endl;
}
int main() {
Heap* heap = new Heap(100);
struct heapnode* trash = new heapnode[100];
struct heapnode *node;
int lastTrashIndex = -1;
string command;
string name;
int priority;
while (true) {
cout << "> ";
cin >> command;
if (command == "add") {
cout << "Enter task name: ";
getline(cin >> ws, name);
cout << "Enter task priority: ";
cin >> priority;
heap->insert(priority, name);
}
else if (command == "execute") {
node = heap->deleteMax();
if (node == nullptr) {
cout << "No tasks." << endl;
continue;
}
trash[++lastTrashIndex] = *node;
cout << trash[lastTrashIndex].data << endl;
}
else if (command == "list") {
cout << "Tasks:" << endl;
heap->print();
for (int index = 0; index <= lastTrashIndex; index++)
cout << "[" << trash[index].key << "] " << trash[index].data << " (completed)" << endl;
}
else if (command == "edit") {
cout << "Enter task name: ";
getline(cin >> ws, name);
cout << "Enter task priority: ";
cin >> priority;
node = heap->search(priority, name);
if (node == nullptr) {
cout << "Task not found." << endl;
continue;
}
cout << "Enter new task name: ";
getline(cin >> ws, name);
cout << "Enter new task priority: ";
cin >> priority;
heap->edit(node, priority, name);
}
else if (command == "exit") break;
}
delete heap;
delete[] trash;
delete node;
return 0;
}

View File

@ -0,0 +1,5 @@
.SILENT:
run:
g++ -o main "$(name).cpp"
./main
rm main

106
Second term/Algorithms/5.1/1.py Executable file
View File

@ -0,0 +1,106 @@
class Node():
def __init__(self, count, data, left=None, right=None) -> None:
self.count = count
self.data = data
self.left = left
self.right = right
def create_coding_formats(node: Node, encoding_format: dict[str, str], decoding_format: dict[str, str], bits="") -> None:
if node is None:
return
if node.data is not None:
encoding_format[node.data] = bits
decoding_format[bits] = node.data
create_coding_formats(node.left, encoding_format, decoding_format, bits + "0")
create_coding_formats(node.right, encoding_format, decoding_format, bits + "1")
def get_unique_letters(message: str) -> list[Node]:
nodes = []
for letter in set(message):
node = Node(message.count(letter), letter)
nodes.append(node)
nodes.sort(key=lambda node: node.count, reverse=True)
return nodes
def huffman_algorithm(nodes: list[Node]) -> tuple[dict[str, str], dict[str, str], Node]:
while len(nodes) > 1:
first_node = nodes.pop()
second_node = nodes.pop()
new_node = Node(first_node.count + second_node.count,
None, first_node, second_node)
nodes.append(new_node)
nodes.sort(key=lambda node: node.count, reverse=True)
encoding_format = {}
decoding_format = {}
create_coding_formats(nodes[0], encoding_format, decoding_format)
return encoding_format, decoding_format, nodes[0]
def encode(message: str, encoding_format: dict[str, str]) -> str:
encoded_message = ""
for letter in message:
encoded_message += encoding_format[letter]
return encoded_message
def decode(encoded_message: int, decoding_format: dict[str, str]) -> str:
decoded_message = ""
bits = ""
for bit in encoded_message:
bits += bit
if decoding_format.get(bits) is not None:
decoded_message += decoding_format[bits]
bits = ""
return decoded_message
def print_tree(node: Node, message: str, depth: int = 0) -> None:
if node is None:
return
print_tree(node.right, message, depth + 1)
print(" " * depth * 5, f"{node.data or '*'} ({node.count / len(message) :.7f})", sep="")
print_tree(node.left, message, depth + 1)
def main() -> None:
print("Введите текст, содержащий не менее двух символов...")
message = input()
unique_letters = get_unique_letters(message)
print("Полученный список:")
for node in unique_letters:
print(f"{node.data} ({node.count / len(message) :.7f})", end=" ---> ")
print("\nПостроим дерево...")
new_encoding_fromat, new_decoding_format, huffman_tree = huffman_algorithm(unique_letters)
print_tree(huffman_tree, message)
print("---------------------------------------------")
print("Приступим к кодировке введенного текста...")
encoded_message = encode(message, new_encoding_fromat)
print("Код перед Вами...", encoded_message)
print(f"Коэффициент сжатия: {len(encoded_message) / (len(message) * 8) * 100 :.4f}%")
decoded_message = decode(encoded_message, new_decoding_format)
print("Ранее было зашифровано...", message)
print("Расшифровано...", decoded_message)
if __name__ == "__main__":
main()

34
Second term/Algorithms/5/1.py Executable file
View File

@ -0,0 +1,34 @@
from string import ascii_lowercase
def caesar_cipher(alphabet: str, key: int, message: str) -> str:
new_message = ""
for char in message:
is_upper = char.isupper()
char = char.lower()
if char not in alphabet:
new_message += char
continue
index_of_new_char = (alphabet.find(char) + key) % len(alphabet)
new_char = alphabet[index_of_new_char]
new_message += new_char.upper() if is_upper else new_char
return new_message
def main() -> None:
input_message = input("Please enter text: ")
key = int(input("Please enter key: "))
alphabet = ascii_lowercase
encrypted_message = caesar_cipher(alphabet, key, input_message)
print("Encrypted message:", encrypted_message)
decrypted_message = caesar_cipher(alphabet, -key, encrypted_message)
print("Decrypted message:", decrypted_message)
if __name__ == "__main__":
main()

48
Second term/Algorithms/5/2.py Executable file
View File

@ -0,0 +1,48 @@
from operator import itemgetter
def caesar_cipher(alphabet: str, key: int, message: str) -> str:
new_message = ""
for char in message:
is_upper = char.isupper()
char = char.lower()
if char not in alphabet:
new_message += char
continue
index_of_new_char = (alphabet.find(char) + key) % len(alphabet)
new_char = alphabet[index_of_new_char]
new_message += new_char.upper() if is_upper else new_char
return new_message
def hack(alphabet: str, delta: dict[str, float], message: str) -> int:
delta_arr = []
for key in delta.keys():
for char in alphabet:
shift = abs(alphabet.find(key) - alphabet.find(char))
delta_arr.append((abs(delta[key] - message.count(char) / len(message)), shift))
return min(delta_arr, key=itemgetter(0))[1]
def main() -> None:
encrypted_message = "Елжзо фср, дцжхс Лсфлч Гознфзлъ е псзп жспз флжлх, л в угж съзря л йзогб зёс цёсфхлхя. Дцжхс в ф тсфхсусррлпл рзцпсоърс дсохгб л ежуцё ефтспрло, ъхс ахс зпц рз псйзх ругелхяфв, л йзогб н рзпц тулдолклхяфв л зёс сдрвхя. Рс хсоянс ъхс тулдолклофв, елйц, ъхс олщс зёс тузсдугклосфя, фхгос псосжсз, л ср прз хлшс, хлшс ъхс-хс ёсесулх лк цъзряв сужзрг, хгн хлшс, ъхс в рз псёц угффоюыгхя. Тсхсп дцжхс еюыол пю ефз лк нспргхю, л ъхс-хс хцх фоцълосфя пцжузрсз. Пю флжзол лол озйгол рг тсоц. Ср прз ъхс-хс ёсесуло. Г прз дцжхс кгшсхзосфя тснгкгхя зпц фесб ъцефхелхзоярсфхя, л в, рз ефоцылегвфя е зёс узъл, фхго фздз ессдугйгхя фсфхсврлз фесзёс ерцхузррзёс ъзосезнг л сфзрлеыцб пзрв плосфхя Дсйлб. Л тсвелолфя ц пзрв фозкю рг ёогкгш, л в дюо жсесозр, ъхс ср ахс тулпзхло. Рс ср екёоврцо рг пзрв ф жсфгжсм л ефнсъло, тузфзныл фесм угкёсесу. В сусдзо л фтусфло, рз нс прз ол фнгкгррсз схрсфлосфя; рс ср рлъзёс рз схезъго, тснгкго прз огфнсеюм елж, л тсфоз ежуцё съцхлолфя пю е фтгоярз псзм, ёжз фхслх жесмргв нусегхя. Ср озё рг рзз рг нугм, л в, дцжхс тюогв н рзпц йзогрлзп огфнгхяфв, тулозё хцх йз. Л ср дцжхс ц пзрв фтугылегзх: „Фнгйлхз тс тугежз, нгнсз ею лпззхз ёогерсз тулфхугфхлз? Цкргол ол ею зёс? В жцпгб, ъхс ею цйз зёс цкргол“. В, фпцхлеылфя флп естусфсп, схезъго, ъхс озря псз ёогерсз тулфхугфхлз. Ср рзжсезуълес тснгъго ёсосесм. Л в, зьз дсозз фпцхлеылфя, схезъго, ъхс в шсхв л йлец ф йзрсб, тс зёс фсезхц, рс рз нгн пцй йзрю фесзм. Рг ахс ср ескугкло, ъхс рз жсойрс йзрц олыгхя фесзм огфнл, жго ъцефхесегхя, ъхс е ахсп дюог псв сдвкгррсфхя. Рс в схезъго, ъхс в фхюйцфя ахсёс; л ежуцё ефз фснуюосфя. Л в тусфрцофв л ргызо е пюфовш феслш хзнфх фе. Тлфгрлв: Йлесх дз фезх ъзосезнсп, г фезх ес хяпз фезхлх л хяпг зёс рз сдэвх. Олщс ц Лсфлчг Гознфззелъг дюос псосйгесз л фезхосз. Е ахсх жзря тсоцъло тлфяпс сх догёсжзхзов, е нсхсусп ср тлызх сд сдвкгррсфхл фцтуцйзфхег»."
alphabet = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя"
delta = {
"о": 0.10983,
"е": 0.08483,
"а": 0.07998,
}
key = hack(alphabet, delta, encrypted_message)
print("Key:", key)
decrypted_message = caesar_cipher(alphabet, -key, encrypted_message)
print("Decrypted message:", decrypted_message)
if __name__ == "__main__":
main()

33
Second term/Algorithms/5/3.py Executable file
View File

@ -0,0 +1,33 @@
from string import ascii_lowercase
def substitution_cipher(alphabet: str, replacement_alphabet: str, message: str) -> str:
new_message = ""
for char in message:
is_upper = char.isupper()
char = char.lower()
if char not in alphabet:
new_message += char
continue
new_char = replacement_alphabet[alphabet.find(char)]
new_message += new_char.upper() if is_upper else new_char
return new_message
def main() -> None:
input_message = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
alphabet = ascii_lowercase
replacement_alphabet = "goydsipeluavcrjwxznhbqftmk"
encrypted_message = substitution_cipher(alphabet, replacement_alphabet, input_message)
print("Encrypted message:", encrypted_message)
decrypted_message = substitution_cipher(replacement_alphabet, alphabet, encrypted_message)
print("Decrypted message:", decrypted_message)
if __name__ == "__main__":
main()

103
Second term/Algorithms/5/4.py Executable file
View File

@ -0,0 +1,103 @@
class Gost(object):
def __init__(self, key, sbox):
self._key = 0
self._subkeys = None
self.key = key
self.sbox = sbox
@property
def key(self) -> int:
return self._key
@key.setter
def key(self, key: str) -> None:
assert len(key) <= 32
encoded_key = key.encode("ascii")
for index in range(31, -1, -1):
self._key |= encoded_key[index] << (index * 8)
self._subkeys = [(self._key >> (32 * index)) & 0xFFFFFFFF for index in range(8)]
def _function(self, part: int, key: int) -> int:
part = (part + key) % (1 << 32)
temp = 0
for index in range(8):
temp |= ((self.sbox[index][(part >> (4 * index)) & 0b1111]) << (4 * index))
return ((temp >> 11) | (temp << 21)) & 0xFFFFFFFF
def encrypt_part(self, message_part: int) -> int:
left = message_part >> 32
right = message_part & 0xFFFFFFFF
for index in range(24):
left, right = right, left ^ self._function(right, self._subkeys[index % 8])
for index in range(8):
left, right = right, left ^ self._function(right, self._subkeys[7 - index])
return (left << 32) | right
def decrypt_part(self, crypted_message_part: int) -> int:
left = crypted_message_part >> 32
right = crypted_message_part & 0xFFFFFFFF
for index in range(8):
left, right = right ^ self._function(left, self._subkeys[index]), left
for index in range(24):
left, right = right ^ self._function(left, self._subkeys[(7 - index) % 8]), left
return (left << 32) | right
def encrypt(self, message: str) -> int:
encoded_message = message.encode("ascii")
encrypted_message = 0
for part_index in range(len(message) // 8 + 1 * (len(message) % 8 != 0)):
binary_part = 0
for letter_index in range(8):
letter = 0x0000
if (letter_index + part_index * 8 < len(message)):
letter = encoded_message[letter_index + part_index * 8]
binary_part = (binary_part << 8) | letter
encrypted_message = (encrypted_message << 64) | self.encrypt_part(binary_part)
return encrypted_message
def decrypt(self, encrypted_message: int) -> str:
decrypted_message = ""
for index in range(len(bin(encrypted_message)[2:]) // 64, -1, -1):
binary_part = (encrypted_message >> (64 * index)) & 0xFFFFFFFFFFFFFFFF
decrypted_binary_part = self.decrypt_part(binary_part)
for letter_index in range(8):
decrypted_message += chr((decrypted_binary_part >> ((7 - letter_index) * 8)) & 0xFF)
return decrypted_message
def main():
sbox = [
[0x4, 0xA, 0x9, 0x2, 0xD, 0x8, 0x0, 0xE, 0x6, 0xB, 0x1, 0xC, 0x7, 0xF, 0x5, 0x3],
[0xE, 0xB, 0x4, 0xC, 0x6, 0xD, 0xF, 0xA, 0x2, 0x3, 0x8, 0x1, 0x0, 0x7, 0x5, 0x9],
[0x5, 0x8, 0x1, 0xD, 0xA, 0x3, 0x4, 0x2, 0xE, 0xF, 0xC, 0x7, 0x6, 0x0, 0x9, 0xB],
[0x7, 0xD, 0xA, 0x1, 0x0, 0x8, 0x9, 0xF, 0xE, 0x4, 0x6, 0xC, 0xB, 0x2, 0x5, 0x3],
[0x6, 0xC, 0x7, 0x1, 0x5, 0xF, 0xD, 0x8, 0x4, 0xA, 0x9, 0xE, 0x0, 0x3, 0xB, 0x2],
[0x4, 0xB, 0xA, 0x0, 0x7, 0x2, 0x1, 0xD, 0x3, 0x6, 0x8, 0x5, 0x9, 0xC, 0xF, 0xE],
[0xD, 0xB, 0x4, 0x1, 0x3, 0xF, 0x5, 0x9, 0x0, 0xA, 0xE, 0x7, 0x6, 0x8, 0x2, 0xC],
[0x1, 0xF, 0xD, 0x0, 0x5, 0x7, 0xA, 0x4, 0x9, 0x2, 0x3, 0xE, 0x6, 0xB, 0x8, 0xC]
]
message = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
key = "zqHqtbGwB41OOsm5EeGmG0VKeJWrnhML"
gost = Gost(key, sbox)
crypted_message = gost.encrypt(message)
encrypted_message = gost.decrypt(crypted_message)
print("Original message: ", message)
print("Crypted: ", crypted_message)
print("Encrypted message: ", encrypted_message)
if __name__ == "__main__":
main()

47
Second term/Algorithms/6/1.py Executable file
View File

@ -0,0 +1,47 @@
from random import randint
def main() -> None:
inf = float("inf")
names = [
"Пр-т Вернадского, 78",
"Пр-т Вернадского, 86",
"Стромынка, 20",
"Малая Пироговская, 1",
"5-я улица Соколиной горы, 22",
"Усачева, 7"
]
graph = [
[inf, 1.97, 21.6, 10.7, 22.3, 10.4],
[1.97, inf, 22.3, 11.4, 23, 11.1],
[21.6, 22.3, inf, 11.5, 5.2, 12],
[10.7, 1.4, 11.5, inf, 13.4, 0.68],
[22.3, 23, 5.2, 13.4, inf, 13.8],
[10.4, 11.1, 12, 0.68, 13.8, inf]
]
node = randint(0, 5)
indexes = [node]
edges = []
while len(indexes) < len(graph):
new_edge = (indexes[0], indexes[0])
for node in indexes:
for new_node in range(len(graph)):
if new_node in indexes:
continue
if graph[node][new_node] < graph[new_edge[0]][new_edge[1]]:
new_edge = (node, new_node)
edges.append(new_edge)
indexes.append(new_edge[1])
for edge in edges:
print(f"{names[edge[0]] :>28} --> {names[edge[1]]}")
print("Length:", sum([graph[edge[1]][edge[0]] for edge in edges]))
if __name__ == "__main__":
main()

32
Second term/Algorithms/6/2-1.py Executable file
View File

@ -0,0 +1,32 @@
def remover(nodes: list[int], graph: list[list[int]], pnode: int) -> None:
for node in nodes:
if graph[pnode][node]:
nodes.remove(node)
remover(nodes, graph, node)
def main() -> None:
graph = [
[0, 0, 0, 0, 0, 1, 0, 1],
[0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 1],
[0, 0, 0, 0, 1, 0, 0, 0],
[0, 1, 0, 1, 0, 0, 0, 0],
[1, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 1, 0, 0, 0, 0, 0]
]
nodes = [0, 1, 2, 3, 4, 5, 6, 7]
count = 0
while len(nodes) != 0:
count += 1
index = nodes[0]
nodes.remove(index)
remover(nodes, graph, index)
print("Connectivity score:", count)
if __name__ == "__main__":
main()

32
Second term/Algorithms/6/2-2.py Executable file
View File

@ -0,0 +1,32 @@
def remover(nodes: list[int], graph: list[list[int]], pnode: int) -> None:
for node in range(len(graph[pnode])):
if node in nodes and graph[pnode][node]:
nodes.remove(node)
remover(nodes, graph, node)
def main() -> None:
graph = [
[1, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 0, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 1],
[0, 0, 0, 0, 1, 1],
[1, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 1, 0, 1, 0, 0],
]
nodes = [0, 1, 2, 3, 4, 5, 6, 7]
count = 0
while len(nodes) != 0:
count += 1
index = nodes[0]
nodes.remove(index)
remover(nodes, graph, index)
print("Connectivity score:", count)
if __name__ == "__main__":
main()

39
Second term/Algorithms/6/3.py Executable file
View File

@ -0,0 +1,39 @@
from random import randint
def main() -> None:
inf = float("inf")
graph = [
[inf, 44, 46, 32, inf, 37],
[44, inf, 45, inf, 30, inf],
[46, 45, inf, inf, inf, 15],
[32, inf, inf, inf, 17, 22],
[inf, 30, inf, 17, inf, inf],
[37, inf, 15, 22, inf, inf],
]
index = randint(0, len(graph)-1)
indexes = [index]
while len(indexes) < len(graph):
min_val_index = indexes[-1]
for index in range(len(graph)):
if index in indexes:
continue
if graph[indexes[-1]][index] <= graph[indexes[-1]][min_val_index]:
min_val_index = index
indexes.append(min_val_index)
indexes.append(indexes[0])
length = 0
for index in range(1, len(indexes)):
length += graph[indexes[index-1]][indexes[index]]
print(f" {graph[indexes[index-1]][indexes[index]] :^5}", end="")
print()
print(" --> ".join(map(str, indexes)))
print("Length:", length)
if __name__ == "__main__":
main()

113
Second term/Algorithms/6/4.py Executable file
View File

@ -0,0 +1,113 @@
class Graph:
def __init__(self) -> None:
self.graph = []
def add_edge(self, first_index: int, second_index: int, length: int) -> None:
if len(self.graph) <= first_index and len(self.graph) <= second_index:
return
self.graph[first_index][second_index] = length
self.graph[second_index][first_index] = length
def remove_edge(self, first_index: int, second_index: int) -> None:
self.add_edge(first_index, second_index, 0)
def print_matrix(self) -> None:
node_count = len(self.graph)
if node_count == 0:
return
print(" |", *range(node_count))
print("--+" + "--" * node_count)
for index in range(node_count):
print(index, "|", *self.graph[index])
def print_list(self) -> None:
for first_index in range(len(self.graph)):
edges = self.graph[first_index]
print(f"{first_index :>2}: ", end="")
for second_index in range(len(edges)):
if edges[second_index]:
print(f"{second_index} ({edges[second_index]}) ", end="")
print()
def create_empty_graph(self, node_count: int) -> None:
self.graph = [[0 for _ in range(node_count)] for _ in range(node_count)]
def save(self) -> None:
if len(self.graph) == 0:
return
with open("graph.txt", "w") as file:
file.write(f"{len(self.graph)}\n")
for index in range(len(self.graph)):
file.write(" ".join(map(str, self.graph[index])) + "\n")
file.close()
def first_import_type(self, file_name: str) -> None:
with open(file_name, "r") as file:
node_count = int(file.readline())
self.create_empty_graph(node_count)
while True:
line = file.readline().split()
if len(line) < 2:
break
for second_index in line[1:]:
self.add_edge(int(line[0]), int(second_index), 1)
file.close()
def second_import_type(self, file_name: str) -> None:
with open(file_name, "r") as file:
node_count = int(file.readline())
self.create_empty_graph(node_count)
while True:
line = file.readline().split()
if len(line) != 3:
break
self.add_edge(int(line[0]), int(line[1]), int(line[2]))
file.close()
def third_import_type(self, file_name: str) -> None:
with open(file_name, "r") as file:
node_count = int(file.readline())
self.create_empty_graph(node_count)
for first_index in range(node_count):
line = file.readline().split()
for second_index in range(node_count):
self.add_edge(first_index, second_index, int(line[second_index]))
file.close()
def main() -> None:
g = Graph()
print("Import of the first graph type (А)")
g.first_import_type("first_type_graph.txt")
g.print_matrix()
print("Import of the second graph type (Б)")
g.second_import_type("second_type_graph.txt")
g.print_matrix()
print("Import of the third graph type (В)")
g.third_import_type("third_type_graph.txt")
g.print_matrix()
print("Print the graph as a list")
g.print_list()
print("Adding a new edge 1-2 with length 6")
g.add_edge(1, 2, 6)
g.print_matrix()
print("Removing the edge 3-4")
g.remove_edge(3, 4)
g.print_matrix()
print("Saving a new graph")
g.save()
if __name__ == "__main__":
main()

39
Second term/Algorithms/7/1.py Executable file
View File

@ -0,0 +1,39 @@
def main() -> None:
inf = float("inf")
graph = [
[ 0, 7, inf, inf, 4, inf],
[ 7, 0, 5, inf, inf, 2],
[inf, 5, 0, 11, inf, 6],
[inf, inf, 11, 0, 8, 9],
[ 4, inf, inf, 8, 0, 3],
[inf, 2, 6, 9, 3, 0],
]
start_node = 0
dist = graph[start_node].copy()
queue = list(range(len(dist)))
routes = [[] if dist[index] == inf else [start_node] for index in range(len(dist))]
while len(queue) > 0:
min_index = queue[0]
for node in queue:
if dist[node] < dist[min_index]:
min_index = node
queue.remove(min_index)
for node in queue:
new_dist = dist[min_index] + graph[min_index][node]
if dist[node] > new_dist:
dist[node] = new_dist
routes[node] = routes[min_index] + [min_index]
for index in range(len(routes)):
if index == start_node:
continue
print(f"{start_node} --> {index} ({dist[index] :>2}):", end=" ")
print(" --> ".join(map(str, routes[index] + [index])))
if __name__ == "__main__":
main()

58
Second term/Algorithms/7/2.py Executable file
View File

@ -0,0 +1,58 @@
def dijkstra(graph: list[list[int]], start_node: int, end_node: int) -> list[int]:
dist = graph[start_node].copy()
queue = list(range(len(dist)))
routes = [[] if dist[index] == float("inf") else [start_node] for index in range(len(dist))]
while len(queue) > 0:
min_index = queue[0]
for node in queue:
if dist[node] < dist[min_index]:
min_index = node
queue.remove(min_index)
for node in queue:
new_dist = dist[min_index] + graph[min_index][node]
if dist[node] > new_dist:
dist[node] = new_dist
routes[node] = routes[min_index] + [min_index]
return routes[end_node] + [end_node]
def main() -> None:
inf = float("inf")
graph = [
[ 0, 7, 4, inf, inf, inf],
[inf, 0, 4, inf, 2, inf],
[inf, inf, 0, 4, 8, inf],
[inf, inf, inf, 0, inf, 12],
[inf, inf, inf, 4, 0, 5],
[inf, inf, inf, inf, inf, 0]
]
start_node = 0
end_node = 5
flow_sum = 0
while True:
min_flow = inf
route = dijkstra(graph, start_node, end_node)
if len(route) == 1:
break
for index in range(len(route)-1):
min_flow = min(min_flow, graph[route[index]][route[index+1]])
flow_sum += min_flow
for index in range(len(route)-1):
graph[route[index]][route[index+1]] -= min_flow
graph[route[index+1]][route[index]] = min_flow
if graph[route[index]][route[index+1]] == 0:
graph[route[index]][route[index+1]] = inf
print("Sum:",flow_sum)
if __name__ == "__main__":
main()

14
Second term/Algorithms/8/1.py Executable file
View File

@ -0,0 +1,14 @@
def gcd_extended(a: int, b: int) -> tuple[int, int, int]:
if b == 0:
return a, 1, 0
gcd, x, y = gcd_extended(b, a % b)
return gcd, y, x - (a // b) * y
def main() -> None:
print(gcd_extended(240, 46))
if __name__ == "__main__":
main()

96
Second term/Algorithms/8/2.py Executable file
View File

@ -0,0 +1,96 @@
from random import choice
def gcd(a: int, b: int) -> int:
if b == 0:
return a
return gcd(b, a % b)
def gcd_extended(a: int, b: int) -> tuple[int, int, int]:
if b == 0:
return a, 1, 0
gcd, x, y = gcd_extended(b, a % b)
return gcd, y, x - (a // b) * y
def mod_inverse(n: int, x: int) -> int:
inv_x = gcd_extended(n, x)[2]
if inv_x <= 0:
inv_x += n
return inv_x
def mod_extended(x: int, y: int, n: int) -> int:
if y == 0:
return 1
z = mod_extended(x, y // 2, n)
if y % 2 == 0:
return (z * z) % n
return (x * z * z) % n
def generate_keys(p: int, q: int) -> tuple[tuple[int, int], tuple[int, int]]:
n = p * q
phi = (p - 1) * (q - 1)
e = 3
for ferm_number in [5, 17, 257, 65537]:
if ferm_number < phi:
e = ferm_number
d = mod_inverse(phi, e)
return (e, n), (d, n)
def encrypt(message: str, key: tuple[int, int]):
e, n = key
encrypted_message = [mod_extended(ord(char), e, n) for char in message]
return encrypted_message
def decrypt(encrypted_message: str, key: tuple[int, int]):
d, n = key
decrypted_message = [chr(mod_extended(char, d, n))
for char in encrypted_message]
return "".join(decrypted_message)
def get_primes(n: int):
sieve = [True] * n
primes = []
for p in range(2, n):
if sieve[p]:
primes.append(p)
for i in range(p * p, n, p):
sieve[i] = False
return primes
def main() -> None:
primes = get_primes(100000)
p = choice(primes)
q = choice(primes)
while p == q:
q = choice(primes)
message = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
public, private = generate_keys(p, q)
encrypted_message = encrypt(message, public)
decrypted_message = decrypt(encrypted_message, private)
print("Public key: ", public)
print("Private key:", private)
print("Original message: ", message)
print("Encrypted message:", "".join(map(str, encrypted_message)))
print("Decrypted message:", decrypted_message)
if __name__ == "__main__":
main()

View File

@ -0,0 +1,15 @@
# Algorithms
number | name | grade
:----: | ----------------------------------------------------------------------------------- | :---:
1 | Двоичное дерево поиска | ✅
1.1 | Дерево отрезков | ✅
2 | Сбалансированные двоичные деревья поиска | ✅
3 | Двоичная куча. Очередь с приоритетом. Пирамидальная сортировка. | ✅
5 | Основы криптографических алгоритмов | ✅
5.1 | Дерево Хаффмана | ✅
6 | Основы теории графов | ✅
7 | Алгоритмы на графах (Удален из программы) | ❓
8 | Шифрование с открытым ключом. Расширенный алгоритм Евклида. Алгоритм шифрования RSA | ✅
[Back](/NKTKLN/mirea-projects)

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 377 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 255 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 352 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 114 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 169 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 840 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 402 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 264 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

Some files were not shown because too many files have changed in this diff Show More