├── Semester_1 ├── Lab_6 │ ├── input │ │ ├── small.txt │ │ ├── test.txt │ │ └── medium.txt │ ├── CMakeLists.txt │ ├── main.c │ └── dop.c ├── Lab_0 │ ├── CMakeLists.txt │ ├── main.c │ └── dop.c ├── Lab_1 │ ├── CMakeLists.txt │ ├── main.c │ └── dop.c ├── Lab_2 │ ├── CMakeLists.txt │ ├── main.c │ └── dop.c ├── Lab_3 │ ├── CMakeLists.txt │ ├── main.c │ └── dop.c ├── Lab_4 │ ├── CMakeLists.txt │ ├── main.c │ └── dop.c ├── Lab_5 │ ├── CMakeLists.txt │ ├── reducts.h │ ├── main.c │ └── dop.c └── CMakeLists.txt ├── Semester_2 ├── Lab_6 │ ├── input │ │ ├── small.txt │ │ └── medium.txt │ ├── CMakeLists.txt │ ├── dop │ │ ├── CMakeLists.txt │ │ ├── input.txt │ │ ├── snippets.h │ │ └── main.cpp │ └── base │ │ ├── CMakeLists.txt │ │ ├── input.txt │ │ ├── main.cpp │ │ └── snippets.h ├── Lab_12 │ ├── base │ │ ├── input.txt │ │ ├── output.txt │ │ ├── CMakeLists.txt │ │ └── HugeInt.h │ ├── dop │ │ ├── input.txt │ │ ├── output.txt │ │ ├── CMakeLists.txt │ │ ├── main.cpp │ │ └── HugeInt.h │ └── CMakeLists.txt ├── Lab_8 │ ├── base │ │ ├── sort.h │ │ ├── CMakeLists.txt │ │ ├── sort.cpp │ │ └── main.cpp │ ├── dop │ │ ├── sort.h │ │ ├── CMakeLists.txt │ │ ├── sort.cpp │ │ └── main.cpp │ └── CMakeLists.txt ├── Lab_7 │ ├── base │ │ ├── rand.h │ │ ├── CMakeLists.txt │ │ ├── main.cpp │ │ └── rand.cpp │ ├── dop │ │ ├── rand.h │ │ ├── CMakeLists.txt │ │ ├── rand.cpp │ │ └── main.cpp │ └── CMakeLists.txt ├── Lab_10 │ ├── base │ │ ├── file.h │ │ ├── CMakeLists.txt │ │ ├── input.txt │ │ ├── main.cpp │ │ ├── output.txt │ │ └── file.cpp │ ├── dop │ │ ├── file.h │ │ ├── CMakeLists.txt │ │ ├── output.txt │ │ ├── input.txt │ │ ├── main.cpp │ │ └── file.cpp │ ├── CMakeLists.txt │ └── v2 │ │ ├── file.h │ │ ├── CMakeLists.txt │ │ ├── input.txt │ │ ├── main.cpp │ │ ├── output.txt │ │ └── file.cpp ├── Lab_13 │ ├── CMakeLists.txt │ └── base │ │ └── CMakeLists.txt ├── Lab_11 │ ├── CMakeLists.txt │ ├── base │ │ ├── CMakeLists.txt │ │ ├── strpbrk.h │ │ └── main.cpp │ └── dop │ │ ├── CMakeLists.txt │ │ ├── strcmp.h │ │ └── main.cpp ├── Lab_14 │ ├── CMakeLists.txt │ ├── base │ │ ├── CMakeLists.txt │ │ ├── list.h │ │ ├── shape.h │ │ ├── shape.cpp │ │ └── list.cpp │ └── dop │ │ ├── CMakeLists.txt │ │ ├── list.h │ │ ├── shape.h │ │ ├── shape.cpp │ │ └── list.cpp ├── Lab_9 │ ├── CMakeLists.txt │ ├── dop │ │ ├── CMakeLists.txt │ │ ├── polynom.h │ │ ├── fractions.h │ │ ├── main.cpp │ │ └── fractions.cpp │ └── base │ │ ├── CMakeLists.txt │ │ ├── polynom.h │ │ ├── fractions.h │ │ ├── main.cpp │ │ └── fractions.cpp └── CMakeLists.txt ├── Variants ├── Lab_6 │ ├── var_11 │ │ ├── test.txt │ │ └── main.c │ ├── var_7 │ │ └── test.txt │ └── var_9 │ │ ├── newtext.txt │ │ └── main.c ├── Lab_7 │ ├── var_7 │ │ ├── dtoa.h │ │ ├── main.cpp │ │ └── dtoa.cpp │ ├── var_5 │ │ ├── frand.cpp │ │ ├── frand.h │ │ └── main.cpp │ ├── var_12 │ │ ├── frand.h │ │ ├── frand.cpp │ │ └── main.cpp │ └── var_11 │ │ ├── frand.h │ │ ├── main.cpp │ │ └── frand.cpp ├── Lab_18 │ ├── var_1 │ │ ├── notebook.txt │ │ └── main.cpp │ └── var_2 │ │ ├── db.txt │ │ ├── database.h │ │ ├── main.cpp │ │ └── database.cpp ├── Lab_10 │ └── var_7 │ │ ├── abbrev.txt │ │ ├── abbrev.h │ │ ├── main.cpp │ │ ├── input.txt │ │ └── output.txt ├── Lab_20 │ ├── var_2 │ │ ├── base │ │ │ ├── graph.png │ │ │ └── graph.txt │ │ └── dop │ │ │ ├── graph.txt │ │ │ └── graph.dot │ └── var_13_half │ │ └── input.txt ├── Lab_8 │ └── var_5 │ │ ├── lab.h │ │ ├── dop │ │ ├── lab.h │ │ ├── lab.cpp │ │ └── main.cpp │ │ ├── lab.cpp │ │ └── main.cpp ├── Lab_9 │ ├── var_11 │ │ ├── sequence.h │ │ ├── main.cpp │ │ └── sequence.cpp │ └── var_12 │ │ ├── lab.h │ │ ├── main.cpp │ │ └── lab.cpp ├── Lab_12 │ ├── var_11 │ │ ├── main.cpp │ │ ├── time.h │ │ └── time.cpp │ └── var_12 │ │ └── matrix.h ├── Lab_5 │ ├── var_11 │ │ └── main.c │ └── var_9 │ │ └── dop.c ├── Lab_4 │ ├── var_17 │ │ └── main.c │ └── var_7 │ │ ├── main.c │ │ └── dop.c └── Lab_17 │ └── var_1 │ ├── main.cpp │ └── dop │ └── main.cpp ├── Test ├── BitMap │ └── help.jpg ├── Templates │ ├── locale.cpp │ ├── upper_lower.c │ ├── primes.cpp │ └── neuro.cpp └── Meme │ ├── python.cpp │ └── pointers.c ├── Practice ├── Lab_15 │ ├── base │ │ ├── input.bmp │ │ └── CMakeLists.txt │ ├── extended │ │ ├── input.bmp │ │ ├── CMakeLists.txt │ │ ├── main.cpp │ │ └── bmp.hpp │ └── CMakeLists.txt └── CMakeLists.txt ├── Turlikov ├── Report_1 │ ├── report.pdf │ ├── pascal_triangle │ │ ├── main.cpp │ │ ├── pascal_vec.h │ │ └── pascal_arr.h │ ├── combinations │ │ ├── other_versions │ │ │ ├── kostya.cpp │ │ │ └── andrey.cpp │ │ ├── binom_v0.h │ │ ├── binom_optimal.h │ │ └── main.cpp │ └── count_ones │ │ ├── v_no_array.h │ │ ├── v_small_array.h │ │ ├── v_long_array.h │ │ └── main.cpp └── Report_2 │ ├── dop │ └── time_data.xlsx │ ├── report │ ├── n2.cpp │ ├── n1.cpp │ └── n3.cpp │ ├── hamming.h │ ├── min_hamming │ └── main.cpp │ ├── hamming_decoder │ └── main.cpp │ └── optimal_table │ └── main.cpp ├── .gitignore ├── Semester_3 ├── Lab_20 │ ├── base │ │ ├── graph.txt │ │ └── CMakeLists.txt │ ├── dop │ │ ├── graph.txt │ │ ├── graph.dot │ │ └── CMakeLists.txt │ └── CMakeLists.txt ├── Lab_17 │ ├── CMakeLists.txt │ ├── base │ │ ├── CMakeLists.txt │ │ └── exception.h │ └── dop │ │ ├── exception.h │ │ ├── matrix.json │ │ ├── CMakeLists.txt │ │ └── point.json ├── Lab_18 │ ├── CMakeLists.txt │ ├── base │ │ ├── CMakeLists.txt │ │ ├── cache.cpp │ │ ├── cache.h │ │ └── main.cpp │ └── dop │ │ ├── CMakeLists.txt │ │ ├── translate.cpp │ │ ├── main.cpp │ │ ├── cache.cpp │ │ ├── include │ │ ├── cache.h │ │ └── translate.h │ │ └── input.txt └── CMakeLists.txt ├── Exam ├── Semester_1 │ ├── n6_2.c │ ├── n1_1.c │ ├── n7_2.c │ ├── n1_2.c │ ├── n2_2.c │ ├── n4_1.c │ ├── n3_2.c │ ├── n8_2.c │ ├── n3_1.c │ ├── n5_2.c │ ├── n8_1.c │ ├── n5_1.c │ ├── n7_1.c │ ├── n2_1.c │ └── n6_1.c ├── Semester_2 │ ├── task_5.cpp │ └── task_3.cpp └── Semester_3 │ ├── vtit.cpp │ └── ferz.cpp ├── CMakeLists.txt ├── LICENSE ├── .github └── workflows │ └── cmake.yml └── README.md /Semester_1/Lab_6/input/small.txt: -------------------------------------------------------------------------------- 1 | lorem ipsum dolor sit amet -------------------------------------------------------------------------------- /Semester_2/Lab_6/input/small.txt: -------------------------------------------------------------------------------- 1 | lorem ipsum dolor sit amet -------------------------------------------------------------------------------- /Semester_2/Lab_12/base/input.txt: -------------------------------------------------------------------------------- 1 | -1234567890987654321 2 | 618000123 -------------------------------------------------------------------------------- /Semester_2/Lab_12/base/output.txt: -------------------------------------------------------------------------------- 1 | -1234567890987654321 2 | 618000123 -------------------------------------------------------------------------------- /Semester_2/Lab_12/dop/input.txt: -------------------------------------------------------------------------------- 1 | -1234567890987654321 2 | 618000123 -------------------------------------------------------------------------------- /Semester_2/Lab_12/dop/output.txt: -------------------------------------------------------------------------------- 1 | -1234567890987654321 2 | 618000123 -------------------------------------------------------------------------------- /Variants/Lab_6/var_11/test.txt: -------------------------------------------------------------------------------- 1 | 0 1 2 .. 3 4 test 5 6 7 8 9 kek 10 11 12 13 -------------------------------------------------------------------------------- /Semester_1/Lab_6/input/test.txt: -------------------------------------------------------------------------------- 1 | lorem ipsum dolor lol sit amet consectetur adipiscing elit -------------------------------------------------------------------------------- /Test/BitMap/help.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/potat-dev/cpplabs/HEAD/Test/BitMap/help.jpg -------------------------------------------------------------------------------- /Variants/Lab_7/var_7/dtoa.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | char* dtoa(double num, int npos, int nfr); -------------------------------------------------------------------------------- /Variants/Lab_18/var_1/notebook.txt: -------------------------------------------------------------------------------- 1 | 123456 Ivan 2 | 214365 Oleg 3 | 654321 Petr 4 | 987654 Vlad 5 | -------------------------------------------------------------------------------- /Practice/Lab_15/base/input.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/potat-dev/cpplabs/HEAD/Practice/Lab_15/base/input.bmp -------------------------------------------------------------------------------- /Turlikov/Report_1/report.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/potat-dev/cpplabs/HEAD/Turlikov/Report_1/report.pdf -------------------------------------------------------------------------------- /Practice/Lab_15/extended/input.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/potat-dev/cpplabs/HEAD/Practice/Lab_15/extended/input.bmp -------------------------------------------------------------------------------- /Turlikov/Report_2/dop/time_data.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/potat-dev/cpplabs/HEAD/Turlikov/Report_2/dop/time_data.xlsx -------------------------------------------------------------------------------- /Variants/Lab_10/var_7/abbrev.txt: -------------------------------------------------------------------------------- 1 | Somebody Shrek 2 | She Fiona 3 | roll fuck 4 | never always 5 | stars guns 6 | "L" LOL 7 | I You -------------------------------------------------------------------------------- /Variants/Lab_20/var_2/base/graph.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/potat-dev/cpplabs/HEAD/Variants/Lab_20/var_2/base/graph.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled source # 2 | *.com 3 | *.class 4 | *.dll 5 | *.exe 6 | *.o 7 | *.so 8 | 9 | .vscode 10 | tempCodeRunnerFile.* 11 | build/ -------------------------------------------------------------------------------- /Semester_2/Lab_8/base/sort.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void swap(int *a, int *b); 4 | void sort(int *arr, int n); 5 | void print_arr(int *arr, int n); -------------------------------------------------------------------------------- /Semester_2/Lab_7/base/rand.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #define NUMS 211 4 | 5 | int gen(); 6 | void pretty_print(int *arr, int n, int wide); -------------------------------------------------------------------------------- /Variants/Lab_8/var_5/lab.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | int gen(int a, int b); 7 | void sort(int size, int* mas); -------------------------------------------------------------------------------- /Semester_2/Lab_10/base/file.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | void print_file(const char *path); 4 | void parse_file(const char *in, const char *out, int start, int end); -------------------------------------------------------------------------------- /Variants/Lab_20/var_2/base/graph.txt: -------------------------------------------------------------------------------- 1 | 10 2 | -1 3 | 2 5 4 | 1 5 | 8 5 6 | 5 7 | 1 3 4 6 7 8 | 5 10 9 | 5 10 12 10 | 3 9 11 11 | 8 12 | 6 7 13 | 8 12 14 | 7 11 -------------------------------------------------------------------------------- /Variants/Lab_20/var_2/dop/graph.txt: -------------------------------------------------------------------------------- 1 | 10 2 | -1 3 | 2 5 4 | 1 5 | 8 5 6 | 5 7 | 1 3 4 6 7 8 | 5 10 9 | 5 10 12 10 | 3 9 11 11 | 8 12 | 6 7 13 | 8 12 14 | 7 11 -------------------------------------------------------------------------------- /Variants/Lab_7/var_5/frand.cpp: -------------------------------------------------------------------------------- 1 | #include "frand.h" 2 | 3 | float frand10() { 4 | float f; 5 | do { 6 | f = frand(); 7 | } while (f >= 1); 8 | return f * 10; 9 | } -------------------------------------------------------------------------------- /Variants/Lab_7/var_5/frand.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | #define frand() ((float)(rand())/(RAND_MAX)) 7 | 8 | float frand10(); -------------------------------------------------------------------------------- /Practice/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Semester_1) 5 | 6 | # Добавление подпроектов 7 | add_subdirectory(Lab_15) -------------------------------------------------------------------------------- /Semester_2/Lab_13/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_13) 5 | 6 | # Добавляем подпроекты 7 | add_subdirectory(base) -------------------------------------------------------------------------------- /Semester_2/Lab_7/dop/rand.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #define NUMS 211 4 | 5 | int gen(); 6 | int gen_normal(int n); 7 | void pretty_print(int *arr, int n, int wide); -------------------------------------------------------------------------------- /Semester_2/Lab_8/dop/sort.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void swap(int *a, int *b); 4 | void sort(int *arr, int n); 5 | void qsort(int *arr, int n); 6 | void print_arr(int *arr, int n); -------------------------------------------------------------------------------- /Semester_3/Lab_20/base/graph.txt: -------------------------------------------------------------------------------- 1 | 0 2 | 0 1 0 0 1 0 0 1 3 | 0 0 1 0 0 0 0 0 4 | 0 0 0 1 0 0 0 0 5 | 0 1 0 0 0 0 0 0 6 | 0 0 0 0 0 1 0 0 7 | 0 0 1 0 0 0 1 1 8 | 0 0 0 0 0 0 0 0 9 | 0 0 0 0 0 0 0 0 -------------------------------------------------------------------------------- /Semester_3/Lab_20/dop/graph.txt: -------------------------------------------------------------------------------- 1 | 0 2 | 0 1 0 0 1 0 0 1 3 | 0 0 1 0 0 0 0 0 4 | 0 0 0 1 0 0 0 0 5 | 0 1 0 0 0 0 0 0 6 | 0 0 0 0 0 1 0 0 7 | 0 0 1 0 0 0 1 1 8 | 0 0 0 0 0 0 0 0 9 | 0 0 0 0 0 0 0 0 -------------------------------------------------------------------------------- /Semester_2/Lab_10/dop/file.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | void print_file(const char *path); 4 | void parse_file(const char *in, const char *out, int start, int end, 5 | bool no_whitespace); -------------------------------------------------------------------------------- /Variants/Lab_20/var_13_half/input.txt: -------------------------------------------------------------------------------- 1 | 0 2 | 0 1 0 0 1 0 0 1 3 | 1 0 1 1 0 0 0 0 4 | 0 1 0 1 0 1 0 0 5 | 0 1 1 0 0 0 0 0 6 | 1 0 0 0 0 1 0 0 7 | 0 0 1 0 1 0 1 1 8 | 0 0 0 0 0 1 0 0 9 | 1 0 0 0 0 1 0 0 -------------------------------------------------------------------------------- /Practice/Lab_15/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_15) 5 | 6 | # Добавить подпроекты 7 | add_subdirectory(base) 8 | add_subdirectory(extended) -------------------------------------------------------------------------------- /Semester_2/Lab_11/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_11) 5 | 6 | # Добавляем подпроекты 7 | add_subdirectory(base) 8 | add_subdirectory(dop) -------------------------------------------------------------------------------- /Semester_2/Lab_11/base/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_11_base) 5 | 6 | # Создает исполняемый файл 7 | add_executable(Lab_11_base main.cpp) -------------------------------------------------------------------------------- /Semester_2/Lab_11/dop/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_11_dop) 5 | 6 | # Создает исполняемый файл 7 | add_executable(Lab_11_dop main.cpp) -------------------------------------------------------------------------------- /Semester_2/Lab_12/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_12) 5 | 6 | # Добавляем подпроекты 7 | add_subdirectory(base) 8 | add_subdirectory(dop) -------------------------------------------------------------------------------- /Semester_2/Lab_14/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_14) 5 | 6 | # Добавляем подпроекты 7 | add_subdirectory(base) 8 | add_subdirectory(dop) -------------------------------------------------------------------------------- /Semester_2/Lab_6/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_6) 5 | 6 | # Добавляем подпроекты 7 | add_subdirectory(base) 8 | add_subdirectory(dop) -------------------------------------------------------------------------------- /Semester_2/Lab_7/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_7) 5 | 6 | # Добавляем подпроекты 7 | add_subdirectory(base) 8 | add_subdirectory(dop) -------------------------------------------------------------------------------- /Semester_2/Lab_8/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_8) 5 | 6 | # Добавляем подпроекты 7 | add_subdirectory(base) 8 | add_subdirectory(dop) -------------------------------------------------------------------------------- /Semester_2/Lab_9/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_9) 5 | 6 | # Добавляем подпроекты 7 | add_subdirectory(base) 8 | add_subdirectory(dop) -------------------------------------------------------------------------------- /Semester_3/Lab_17/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_17) 5 | 6 | # Добавляем подпроекты 7 | add_subdirectory(base) 8 | add_subdirectory(dop) -------------------------------------------------------------------------------- /Semester_3/Lab_17/base/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_17_base) 5 | 6 | # Создает исполняемый файл 7 | add_executable(Lab_17_base main.cpp) -------------------------------------------------------------------------------- /Semester_3/Lab_18/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_18) 5 | 6 | # Добавляем подпроекты 7 | add_subdirectory(base) 8 | add_subdirectory(dop) -------------------------------------------------------------------------------- /Semester_3/Lab_20/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_20) 5 | 6 | # Добавляем подпроекты 7 | add_subdirectory(base) 8 | add_subdirectory(dop) -------------------------------------------------------------------------------- /Semester_2/Lab_7/dop/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_7_dop) 5 | 6 | # Создает исполняемый файл 7 | add_executable(Lab_7_dop main.cpp rand.cpp) -------------------------------------------------------------------------------- /Semester_2/Lab_8/dop/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_8_dop) 5 | 6 | # Создает исполняемый файл 7 | add_executable(Lab_8_dop main.cpp sort.cpp) -------------------------------------------------------------------------------- /Semester_2/Lab_7/base/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_7_base) 5 | 6 | # Создает исполняемый файл 7 | add_executable(Lab_7_base main.cpp rand.cpp) -------------------------------------------------------------------------------- /Semester_2/Lab_8/base/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_8_base) 5 | 6 | # Создает исполняемый файл 7 | add_executable(Lab_8_base main.cpp sort.cpp) -------------------------------------------------------------------------------- /Semester_3/Lab_18/base/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_18_base) 5 | 6 | # Создает исполняемый файл 7 | add_executable(Lab_18_base main.cpp cache.cpp) -------------------------------------------------------------------------------- /Semester_2/Lab_13/base/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_13_base) 5 | 6 | # Создает исполняемый файл 7 | add_executable(Lab_13_base main.cpp rational.cpp) -------------------------------------------------------------------------------- /Practice/Lab_15/extended/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_15_extended) 5 | 6 | # Создает исполняемый файл 7 | add_executable(Lab_15_extended main.cpp bmp.cpp) -------------------------------------------------------------------------------- /Semester_2/Lab_14/base/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_14_base) 5 | 6 | # Создает исполняемый файл 7 | add_executable(Lab_14_base main.cpp list.cpp shape.cpp) -------------------------------------------------------------------------------- /Semester_2/Lab_14/dop/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_14_dop) 5 | 6 | # Создает исполняемый файл 7 | add_executable(Lab_14_dop main.cpp list.cpp shape.cpp) -------------------------------------------------------------------------------- /Semester_2/Lab_9/dop/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_9_dop) 5 | 6 | # Создает исполняемый файл 7 | add_executable(Lab_9_dop main.cpp fractions.cpp polynom.cpp) -------------------------------------------------------------------------------- /Variants/Lab_8/var_5/dop/lab.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | int gen(int a, int b); 8 | void sort(int size, int* mas); 9 | double ran_expo(double lambda); -------------------------------------------------------------------------------- /Semester_1/Lab_0/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_0) 5 | 6 | # Создает исполняемый файл 7 | add_executable(Lab_0_base main.c) 8 | add_executable(Lab_0_dop dop.c) -------------------------------------------------------------------------------- /Semester_1/Lab_1/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_1) 5 | 6 | # Создает исполняемый файл 7 | add_executable(Lab_1_base main.c) 8 | add_executable(Lab_1_dop dop.c) -------------------------------------------------------------------------------- /Semester_1/Lab_2/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_2) 5 | 6 | # Создает исполняемый файл 7 | add_executable(Lab_2_base main.c) 8 | add_executable(Lab_2_dop dop.c) -------------------------------------------------------------------------------- /Semester_1/Lab_3/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_3) 5 | 6 | # Создает исполняемый файл 7 | add_executable(Lab_3_base main.c) 8 | add_executable(Lab_3_dop dop.c) -------------------------------------------------------------------------------- /Semester_1/Lab_4/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_4) 5 | 6 | # Создает исполняемый файл 7 | add_executable(Lab_4_base main.c) 8 | add_executable(Lab_4_dop dop.c) -------------------------------------------------------------------------------- /Semester_1/Lab_5/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_5) 5 | 6 | # Создает исполняемый файл 7 | add_executable(Lab_5_base main.c) 8 | add_executable(Lab_5_dop dop.c) -------------------------------------------------------------------------------- /Semester_2/Lab_10/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_10) 5 | 6 | # Добавляем подпроекты 7 | add_subdirectory(base) 8 | add_subdirectory(dop) 9 | add_subdirectory(v2) -------------------------------------------------------------------------------- /Semester_2/Lab_9/base/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_9_base) 5 | 6 | # Создает исполняемый файл 7 | add_executable(Lab_9_base main.cpp fractions.cpp polynom.cpp) -------------------------------------------------------------------------------- /Semester_3/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Semester_3) 5 | 6 | # Добавление подпроектов 7 | add_subdirectory(Lab_17) 8 | add_subdirectory(Lab_18) 9 | add_subdirectory(Lab_20) -------------------------------------------------------------------------------- /Semester_1/Lab_0/main.c: -------------------------------------------------------------------------------- 1 | // Ввести три целых числа 2 | // Вычислить и вывести произведение первого и второго числа 3 | 4 | #include 5 | 6 | void main() { 7 | int a, b, c; 8 | scanf("%d %d %d", &a, &b, &c); 9 | printf("%d", a * b); 10 | } -------------------------------------------------------------------------------- /Variants/Lab_6/var_7/test.txt: -------------------------------------------------------------------------------- 1 | lorem ipsum dolor sit amet consectetur adipiscing elit nullam ut lectus eget nulla molestie luctus at a sapien nullam sit amet mollis lectus morbi massa magna commodo ut sollicitudin eget ultrices eget ante duis ac ullamcorper velitr -------------------------------------------------------------------------------- /Test/Templates/locale.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | setlocale(LC_ALL, "Russian"); 6 | wcout << L"Русский текст" << endl; 7 | cout << "English " << L"text" << endl; 8 | // в обычный cout нельзя выводить wide-строки 9 | } -------------------------------------------------------------------------------- /Variants/Lab_18/var_2/db.txt: -------------------------------------------------------------------------------- 1 | Rayan Gosling 1980 0 420069 2 | Angelina Jolie 1975 1 420070 3 | Leonardo DiCaprio 1974 0 420072 4 | Scarlett Johansson 1984 1 420073 5 | Tom Cruise 1962 0 420074 6 | Jennifer Lawrence 1990 1 420075 7 | Emma Watson 1990 1 420076 8 | Andrey Kruk 1963 1 666 9 | -------------------------------------------------------------------------------- /Semester_2/Lab_10/v2/file.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | std::string read_file(const char *path); 7 | void read_file(const char *path, std::string &str); 8 | void split_lines(std::string &str); 9 | void write_file(std::string str, const char *path); -------------------------------------------------------------------------------- /Practice/Lab_15/base/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_15_base) 5 | 6 | # Создает исполняемый файл 7 | add_executable(Lab_15_base main.cpp) 8 | 9 | # Скопировать файлы в папку сборки 10 | configure_file(input.bmp input.bmp COPYONLY) -------------------------------------------------------------------------------- /Semester_2/Lab_10/v2/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_10_v2) 5 | 6 | # Создает исполняемый файл 7 | add_executable(Lab_10_v2 main.cpp file.cpp) 8 | 9 | # Копируем файлы в папку с билдом 10 | configure_file(input.txt input.txt COPYONLY) -------------------------------------------------------------------------------- /Semester_3/Lab_20/base/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_20_base) 5 | 6 | # Создает исполняемый файл 7 | add_executable(Lab_20_base main.cpp) 8 | 9 | # Скопировать файлы в папку с билдом 10 | configure_file(graph.txt graph.txt COPYONLY) -------------------------------------------------------------------------------- /Semester_2/Lab_10/dop/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_10_dop) 5 | 6 | # Создает исполняемый файл 7 | add_executable(Lab_10_dop main.cpp file.cpp) 8 | 9 | # Копируем файлы в папку с билдом 10 | configure_file(input.txt input.txt COPYONLY) -------------------------------------------------------------------------------- /Semester_2/Lab_10/base/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_10_base) 5 | 6 | # Создает исполняемый файл 7 | add_executable(Lab_10_base main.cpp file.cpp) 8 | 9 | # Копируем файлы в папку с билдом 10 | configure_file(input.txt input.txt COPYONLY) -------------------------------------------------------------------------------- /Semester_2/Lab_12/base/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_12_base) 5 | 6 | # Создает исполняемый файл 7 | add_executable(Lab_12_base main.cpp HugeInt.cpp) 8 | 9 | # Скопировать файлы в папку сборки 10 | configure_file(input.txt input.txt COPYONLY) -------------------------------------------------------------------------------- /Semester_2/Lab_12/dop/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_12_dop) 5 | 6 | # Создает исполняемый файл 7 | add_executable(Lab_12_dop main.cpp HugeInt.cpp) 8 | 9 | # Скопировать файлы в папку сборки 10 | configure_file(input.txt input.txt COPYONLY) -------------------------------------------------------------------------------- /Semester_2/Lab_6/dop/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_6_dop_cpp) 5 | 6 | # Создает исполняемый файл 7 | add_executable(Lab_6_dop_cpp main.cpp snippets.cpp) 8 | 9 | # Скопировать файлы в папку сборки 10 | configure_file(input.txt input.txt COPYONLY) -------------------------------------------------------------------------------- /Semester_2/Lab_6/base/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_6_base_cpp) 5 | 6 | # Создает исполняемый файл 7 | add_executable(Lab_6_base_cpp main.cpp snippets.cpp) 8 | 9 | # Скопировать файлы в папку сборки 10 | configure_file(input.txt input.txt COPYONLY) -------------------------------------------------------------------------------- /Semester_3/Lab_20/dop/graph.dot: -------------------------------------------------------------------------------- 1 | digraph G { 2 | 0 -> 1 [color=green] 3 | 0 -> 4 [color=green] 4 | 0 -> 7 [color=green] 5 | 1 -> 2 [color=green] 6 | 2 -> 3 [color=green] 7 | 3 -> 1 [color=red] 8 | 4 -> 5 [color=green] 9 | 5 -> 2 [color=blue] 10 | 5 -> 6 [color=green] 11 | 5 -> 7 [color=blue] 12 | } -------------------------------------------------------------------------------- /Exam/Semester_1/n6_2.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void test(int a) { 4 | return a; 5 | } 6 | 7 | void main() { 8 | int a = 0; 9 | scanf("%d", &a); 10 | 11 | switch (a) 12 | { 13 | case 1: 14 | int temp = 0; 15 | temp = test(a); 16 | break; 17 | 18 | default: 19 | break; 20 | } 21 | } -------------------------------------------------------------------------------- /Semester_1/Lab_6/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_6) 5 | 6 | # Создает исполняемый файл 7 | add_executable(Lab_6_base main.c) 8 | add_executable(Lab_6_dop dop.c) 9 | 10 | # Скопировать папку input в папку сборки 11 | file(COPY input DESTINATION ${CMAKE_BINARY_DIR}) -------------------------------------------------------------------------------- /Semester_1/Lab_6/input/medium.txt: -------------------------------------------------------------------------------- 1 | lorem ipsum dolor sit amet consectetur adipiscing elit nullam ut lectus eget nulla molestie luctus at a sapien nullam sit amet mollis lectus morbi massa magna commodo ut sollicitudin eget ultrices eget ante duis ac ullamcorper velit id rhoncus nunc nullam a libero vel nisl sagittis faucibus eu nec tortor -------------------------------------------------------------------------------- /Semester_2/Lab_6/base/input.txt: -------------------------------------------------------------------------------- 1 | lorem ipsum dolor sit amet consectetur adipiscing elit nullam ut lectus eget nulla molestie luctus at a sapien nullam sit amet mollis lectus morbi massa magna commodo ut sollicitudin eget ultrices eget ante duis ac ullamcorper velit id rhoncus nunc nullam a libero vel nisl sagittis faucibus eu nec tortor -------------------------------------------------------------------------------- /Semester_2/Lab_6/dop/input.txt: -------------------------------------------------------------------------------- 1 | lorem ipsum dolor sit amet consectetur adipiscing elit nullam ut lectus eget nulla molestie luctus at a sapien nullam sit amet mollis lectus morbi massa magna commodo ut sollicitudin eget ultrices eget ante duis ac ullamcorper velit id rhoncus nunc nullam a libero vel nisl sagittis faucibus eu nec tortor -------------------------------------------------------------------------------- /Semester_2/Lab_6/input/medium.txt: -------------------------------------------------------------------------------- 1 | lorem ipsum dolor sit amet consectetur adipiscing elit nullam ut lectus eget nulla molestie luctus at a sapien nullam sit amet mollis lectus morbi massa magna commodo ut sollicitudin eget ultrices eget ante duis ac ullamcorper velit id rhoncus nunc nullam a libero vel nisl sagittis faucibus eu nec tortor -------------------------------------------------------------------------------- /Variants/Lab_7/var_12/frand.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | // выдает случайное число из промежутка [0..1] 4 | #define rand_1 ((float)(rand()) / (RAND_MAX)) 5 | 6 | // инициализация генератора 7 | void rand_init(); 8 | 9 | // генератор нормально распределенного 10 | // случайного числа в промежутке [0..n] 11 | double frand(double n, int count); -------------------------------------------------------------------------------- /Semester_1/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Semester_1) 5 | 6 | # Добавление подпроектов 7 | add_subdirectory(Lab_0) 8 | add_subdirectory(Lab_1) 9 | add_subdirectory(Lab_2) 10 | add_subdirectory(Lab_3) 11 | add_subdirectory(Lab_4) 12 | add_subdirectory(Lab_5) 13 | add_subdirectory(Lab_6) -------------------------------------------------------------------------------- /Turlikov/Report_1/pascal_triangle/main.cpp: -------------------------------------------------------------------------------- 1 | #include "pascal_arr.h" 2 | 3 | int main() { 4 | int n = 67; // 67 максимум 5 | // так как 14226520737620288370 (число посередине) 6 | // в двоичном виде: 1100010101101110110000010011110001001011100101011110001101110010 7 | // ровно 64 бита - uint64 8 | 9 | cout << "line " << n << ":\n"; 10 | print_line(n); 11 | } -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(SUAI-Labs) 5 | 6 | # Настройка CMake 7 | set(CMAKE_CXX_STANDARD 17) 8 | 9 | # Подключение лабораторных работ 10 | add_subdirectory(Semester_1) 11 | add_subdirectory(Semester_2) 12 | add_subdirectory(Semester_3) 13 | 14 | # Подключение практических работ 15 | add_subdirectory(Practice) -------------------------------------------------------------------------------- /Semester_1/Lab_0/dop.c: -------------------------------------------------------------------------------- 1 | // Ввести три целых числа 2 | // Вычислить и вывести произведение первого и второго числа 3 | // доп: c умножить на b и поделить на a вывести результат как float 4 | 5 | #include 6 | 7 | void main() { 8 | float a, b, c; 9 | printf("Input a, b, c: "); 10 | scanf("%f %f %f", &a, &b, &c); 11 | printf("c * b / a = %f\n", c * b / a); 12 | } -------------------------------------------------------------------------------- /Semester_3/Lab_20/dop/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Lab_20_dop) 5 | 6 | # Создает исполняемый файл 7 | add_executable(Lab_20_dop main.cpp) 8 | 9 | # Скопировать файлы в папку с билдом 10 | configure_file(graph.txt graph.txt COPYONLY) 11 | 12 | # Add definitions 13 | target_compile_definitions(Lab_20_dop PRIVATE DOP) -------------------------------------------------------------------------------- /Semester_2/Lab_11/dop/strcmp.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | // изменено на my_strcmp для избежания конфликта с библиотечной функцией 4 | int my_strcmp(const char *s1, const char *s2) { 5 | while (*s1 && (*s1 == *s2)) { 6 | s1++; 7 | s2++; 8 | } 9 | return *(const char *)s1 - *(const char *)s2; 10 | } 11 | 12 | // от последнего символа 2 строки отнимается 13 | // последний символ 1 строки -------------------------------------------------------------------------------- /Test/Meme/python.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | string operator*(string str, int count) { 7 | // теперь можно умножать строки :) 8 | string temp; 9 | for (int i = 0; i < count; i++) 10 | temp += str; 11 | return temp; 12 | } 13 | 14 | int main() { 15 | string str; 16 | cin >> str; 17 | cout << str * 50; // прям как в python 18 | } -------------------------------------------------------------------------------- /Test/Templates/upper_lower.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | char tolower(char c) { 4 | // (int)a = 97, (int)A = 65 5 | // (a)97 - (A)65 = 32 6 | // therefore 32 + 65 = a 7 | return c > 64 && c < 91 ? c + 32 : c; 8 | } 9 | 10 | char toupper(char c) { 11 | // (int)a = 97, (int)A = 65 12 | // (a)97 - (A)65 = 32 13 | // therefore 97 - 32 = A 14 | return c > 96 && c < 123 ? c - 32 : c; 15 | } -------------------------------------------------------------------------------- /Test/Templates/primes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int is_prime(int n) { 5 | if (n < 3) return (n == 2); 6 | if (~n & 1) return 0; 7 | for (int i = 3; i*i <= n; i += 2) 8 | if (n % i == 0) return 0; 9 | return 1; 10 | } 11 | 12 | int main (int argc, char *argv[]) { 13 | for (int i = 0; i < 10000; i++) 14 | if (is_prime(i)) 15 | printf("%4d ", i); 16 | } -------------------------------------------------------------------------------- /Semester_2/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | # Название проекта 4 | project(Semester_2) 5 | 6 | # Добавление подпроектов 7 | add_subdirectory(Lab_6) 8 | add_subdirectory(Lab_7) 9 | add_subdirectory(Lab_8) 10 | add_subdirectory(Lab_9) 11 | add_subdirectory(Lab_10) 12 | add_subdirectory(Lab_11) 13 | add_subdirectory(Lab_12) 14 | add_subdirectory(Lab_13) 15 | add_subdirectory(Lab_14) -------------------------------------------------------------------------------- /Turlikov/Report_1/combinations/other_versions/kostya.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void test() { 4 | unsigned long long k = 0, raz = 0, i = 1; 5 | float a = 0, n = 0, C = 1; 6 | 7 | printf("Enter n: "); 8 | scanf("%f", &n); 9 | printf("Enten k: "); 10 | scanf("%d", &k); 11 | 12 | raz = n - k; 13 | while (i++ <= raz) 14 | C *= (a = (n - (i - 1)) / i); 15 | 16 | printf("C = %f", C); 17 | } -------------------------------------------------------------------------------- /Turlikov/Report_1/count_ones/v_no_array.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | // алгоритм нахождения количества единиц в двоичной записи числа 4 | // количество итераций цикла зависит от числа двоичных разрядов числа n 5 | // сложность: O(n) 6 | 7 | unsigned char count_ones (unsigned long long n) { 8 | unsigned char w = 0; 9 | while (n > 0) { 10 | w += n & 1; 11 | n = n >> 1; 12 | } 13 | return w; 14 | } 15 | -------------------------------------------------------------------------------- /Semester_1/Lab_1/main.c: -------------------------------------------------------------------------------- 1 | // Ввести 10 действительных чисел 2 | // Вывести максимальное по абсолютной величине число 3 | 4 | #include 5 | #define abs(a) (a > 0 ? a : -1 * a) 6 | 7 | void main() { 8 | int n, max = 0; 9 | 10 | printf("Enter 10 integers:\n"); 11 | for (int i = 0; i < 10; i++) { 12 | scanf("%d", &n); 13 | if (abs(n) > max) max = abs(n); 14 | } 15 | 16 | printf("%d", max); 17 | } -------------------------------------------------------------------------------- /Variants/Lab_8/var_5/dop/lab.cpp: -------------------------------------------------------------------------------- 1 | #include "lab.h" 2 | 3 | void sort(int size, int* mas) { 4 | int arr[10000] = { 0 }; 5 | 6 | for (int i = 0; i < size; i++) 7 | arr[mas[i]]++; 8 | 9 | int k = 0; 10 | for (int i = 0; i < 10000; i++) 11 | while (arr[i]--) 12 | mas[k++] = i; 13 | } 14 | 15 | double ran_expo(double lambda) { 16 | double u = rand() / (RAND_MAX + 1.0); 17 | return -log(1 - u) * lambda; 18 | } -------------------------------------------------------------------------------- /Variants/Lab_8/var_5/lab.cpp: -------------------------------------------------------------------------------- 1 | #include "lab.h" 2 | 3 | int gen(int a, int b) { 4 | int c = ("%d\n", a + rand() % (b - a + 1)); 5 | printf("%d, ", c); 6 | return c; 7 | } 8 | 9 | void sort(int size, int* mas) { 10 | int arr[10000] = { 0 }; 11 | 12 | for (int i = 0; i < size; i++) 13 | arr[mas[i]]++; 14 | 15 | int k = 0; 16 | for (int i = 0; i < 10000; i++) 17 | while (arr[i]--) 18 | mas[k++] = i; 19 | } -------------------------------------------------------------------------------- /Semester_3/Lab_17/base/exception.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class MatrixException { 8 | private: 9 | string msg; 10 | 11 | public: 12 | MatrixException(const string &msg): msg(msg) {}; 13 | friend ostream& operator<<(ostream& out, const MatrixException& e) { 14 | out << "MatrixException: " << e.msg; 15 | return out; 16 | } 17 | }; -------------------------------------------------------------------------------- /Semester_3/Lab_17/dop/exception.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | class MatrixException { 8 | private: 9 | string msg; 10 | 11 | public: 12 | MatrixException(const string &msg): msg(msg) {}; 13 | friend ostream& operator<<(ostream& out, const MatrixException& e) { 14 | out << "MatrixException: " << e.msg; 15 | return out; 16 | } 17 | }; -------------------------------------------------------------------------------- /Semester_2/Lab_10/dop/output.txt: -------------------------------------------------------------------------------- 1 | Loremipsumdolorsitamet,consecteturadipisicingelit,seddoeiu 2 | smodtemporincididuntutlaboreetdoloremagnaaliqua.Utenimadmi 3 | nimveniam,quisnostrudexercitationullamcolaborisnisiutaliqu 4 | ipexeacommodoconsequat.Duisauteiruredolorinreprehenderitin 5 | voluptatevelitessecillumdoloreeufugiatnullapariatur.Except 6 | eursintoccaecatcupidatatnonproident,suntinculpaquiofficiad 7 | eseruntmollitanimidestlaborum -------------------------------------------------------------------------------- /Turlikov/Report_1/count_ones/v_small_array.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | // алгоритм нахождения количества единиц в двоичной записи числа 4 | // сложность: O(1) 5 | 6 | unsigned char arr[16] = { 7 | 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 8 | }; 9 | 10 | unsigned char count_ones (unsigned long long n) { 11 | unsigned char w = 0; 12 | while (n > 0) { 13 | w += arr[n & 15]; 14 | n = n >> 4; 15 | } 16 | return w; 17 | } -------------------------------------------------------------------------------- /Semester_2/Lab_10/base/input.txt: -------------------------------------------------------------------------------- 1 | Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum -------------------------------------------------------------------------------- /Semester_2/Lab_10/v2/input.txt: -------------------------------------------------------------------------------- 1 | Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum -------------------------------------------------------------------------------- /Semester_2/Lab_10/v2/main.cpp: -------------------------------------------------------------------------------- 1 | // По символьному файлу с текстом создать новый файл 2 | // с форматированным текстом, в котором в каждой строке 3 | // первое слово начинается с 3-ей позиции, 4 | // а последнее заканчивается в 60-ой позиции 5 | 6 | #include "file.h" 7 | 8 | using namespace std; 9 | 10 | int main() { 11 | string str = read_file("input.txt"); 12 | split_lines(str); 13 | write_file(str, "output.txt"); 14 | cout << endl << str << endl; 15 | } -------------------------------------------------------------------------------- /Variants/Lab_6/var_9/newtext.txt: -------------------------------------------------------------------------------- 1 | Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. -------------------------------------------------------------------------------- /Semester_2/Lab_10/dop/input.txt: -------------------------------------------------------------------------------- 1 | Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum -------------------------------------------------------------------------------- /Semester_2/Lab_14/base/list.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "shape.h" 4 | 5 | class Node { 6 | public: 7 | Shape* shape; 8 | Node* next; 9 | Node(Shape* s = NULL, Node* next = NULL); 10 | }; 11 | 12 | class FigureList { 13 | private: 14 | Node* head; 15 | int size; 16 | 17 | public: 18 | FigureList(); 19 | void push_front(Shape* s); 20 | void push_back(Shape* s); 21 | Shape& get(int id); 22 | void erase(int id); 23 | void print_all(); 24 | }; -------------------------------------------------------------------------------- /Semester_2/Lab_14/dop/list.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "shape.h" 4 | 5 | class Node { 6 | public: 7 | Shape* shape; 8 | Node* next; 9 | Node(Shape* s = NULL, Node* next = NULL); 10 | }; 11 | 12 | class FigureList { 13 | private: 14 | Node* head; 15 | int size; 16 | 17 | public: 18 | FigureList(); 19 | void push_front(Shape* s); 20 | void push_back(Shape* s); 21 | Shape& get(int id); 22 | void erase(int id); 23 | void print_all(); 24 | }; -------------------------------------------------------------------------------- /Variants/Lab_10/var_7/abbrev.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "stdio.h" 4 | #include "stdlib.h" 5 | 6 | #define BASE_CAPACITY 4 7 | 8 | int strlen(const char *s); 9 | int strcmp(char *s1, char *s2); 10 | int file_size(FILE *file); 11 | int get_lines(FILE *file); 12 | char *strpbrk(const char *string, const char *strCharSet); 13 | 14 | char *** read_word_pairs(FILE *file); 15 | char *read_file(FILE *file); 16 | int find_substr(char *str, char *** abbrevs, int count); -------------------------------------------------------------------------------- /Exam/Semester_1/n1_1.c: -------------------------------------------------------------------------------- 1 | // это фрагмент программы на си 2 | void main() { 3 | int a = 0; 4 | int b = 42; 5 | int c = a + b; 6 | } 7 | 8 | // а это фрагмент программы на ассембере 9 | // load 500 1 // перемещяем из 500 ячейки оперативки в 1 регистр 10 | // load 300 2 // перемещяем из 300 ячейки оперативки во 2 регистр 11 | // sum 1 2 3 // складываем значения в 1 и 2 регистрах и вносим в регистр 3 12 | // dump 3 700 // записываем значение из регистра 3 в 700 ячейку оперативки -------------------------------------------------------------------------------- /Exam/Semester_2/task_5.cpp: -------------------------------------------------------------------------------- 1 | // class Figure { 2 | // private: 3 | // int x, y; 4 | // }; 5 | 6 | // class Rect : public Figure { 7 | // private: 8 | // int h, w; 9 | // }; 10 | 11 | #include 12 | using namespace std; 13 | 14 | class Date { 15 | private: 16 | int y, m, d; 17 | 18 | public: 19 | friend ostream& operator<<(std::ostream& out, const Date& d) { 20 | out << d.y << "." << d.m << "." << d.d; 21 | return out; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Semester_2/Lab_8/base/sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void swap(int *a, int *b) { 4 | *a += *b; 5 | *b = *a - *b; 6 | *a -= *b; 7 | } 8 | 9 | void sort(int *arr, int n) { 10 | for (int k = 1; k < n; k++) { 11 | for (int i = k; i > 0 && arr[i - 1] > arr[i]; i--) { 12 | swap(&arr[i - 1], &arr[i]); 13 | } 14 | } 15 | } 16 | 17 | void print_arr(int *arr, int n) { 18 | for (int i = 0; i < n; i++) { 19 | printf("%d ", arr[i]); 20 | } 21 | printf("\n"); 22 | } -------------------------------------------------------------------------------- /Turlikov/Report_1/combinations/binom_v0.h: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int fact_multiply(int start, int end) { 5 | int temp = 1; 6 | for (int i = start; i <= end; i++) 7 | temp *= i; 8 | return temp; 9 | } 10 | 11 | int fact(int n) { 12 | int temp = 1; 13 | for (int i = 2; i <= n; i++) 14 | temp *= i; 15 | return temp; 16 | } 17 | 18 | int c(int n, int k) { 19 | if (n == k) 20 | return 1; 21 | return fact_multiply(k + 1, n) / fact(n - k); 22 | } -------------------------------------------------------------------------------- /Variants/Lab_7/var_5/main.cpp: -------------------------------------------------------------------------------- 1 | // Написать генератор псевдослучайных чисел, распределенных на интервале[0, 10). 2 | // Подсчитать и вывести частоты попадания в каждый из единичных интервалов при выборке 100000 3 | // использовать rand() 4 | 5 | #include "frand.h" 6 | #define NUM 100000 7 | 8 | int main() { 9 | int freq[10] = {0}; 10 | for (int i = 0; i < NUM; i++) 11 | freq[(int)frand10()]++; 12 | 13 | for (int i = 0; i < 10; i++) 14 | printf("%d - %-5d times\n", i, freq[i]); 15 | } -------------------------------------------------------------------------------- /Semester_1/Lab_5/reducts.h: -------------------------------------------------------------------------------- 1 | #define W_COUNT 24 2 | 3 | const char words[W_COUNT][7] = { 4 | "XCLM", "QTES", "HASH", "DLLR", "PRCNT", "AMPSND", 5 | "LBRCK", "RBRCK", "ASTRK", "PLUS", "MINUS", "SLSH", 6 | "DOT", "COMMA", "COLON", "SCLN", "ATSMB", "QSTN", 7 | "LARR", "EQUL", "RARR", "TILDE", "PIPE", "UNDSC" 8 | }; 9 | 10 | const char punct[W_COUNT] = { 11 | '!', '"', '#', '$', '%', '&', 12 | '(', ')', '*', '+', '-', '/', 13 | '.', ',', ':', ';', '@', '?', 14 | '<', '=', '>', '~', '|', '_' 15 | }; -------------------------------------------------------------------------------- /Semester_2/Lab_10/base/main.cpp: -------------------------------------------------------------------------------- 1 | // По символьному файлу с текстом создать новый файл 2 | // с форматированным текстом, в котором в каждой строке 3 | // первое слово начинается с 3-ей позиции, 4 | // а последнее заканчивается в 60-ой позиции 5 | 6 | #include "file.h" 7 | 8 | #define START_POS 3 // начальная позиция (отступ) 9 | #define END_POS 60 // конечная позиция (перенос строки) 10 | 11 | int main() { 12 | parse_file("input.txt", "output.txt", START_POS, END_POS); 13 | print_file("output.txt"); 14 | } -------------------------------------------------------------------------------- /Semester_2/Lab_10/base/output.txt: -------------------------------------------------------------------------------- 1 | Lorem ipsum dolor sit amet, consectetur adipisicing elit, 2 | sed do eiusmod tempor incididunt ut labore et dolore magna 3 | aliqua. Ut enim ad minim veniam, quis nostrud exercitation 4 | ullamco laboris nisi ut aliquip ex ea commodo consequat. D 5 | uis aute irure dolor in reprehenderit in voluptate velit e 6 | sse cillum dolore eu fugiat nulla pariatur. Excepteur sint 7 | occaecat cupidatat non proident, sunt in culpa qui officia 8 | deserunt mollit anim id est laborum -------------------------------------------------------------------------------- /Semester_2/Lab_10/v2/output.txt: -------------------------------------------------------------------------------- 1 | Lorem ipsum dolor sit amet, consectetur adipisicing elit, 2 | sed do eiusmod tempor incididunt ut labore et dolore magn 3 | a aliqua. Ut enim ad minim veniam, quis nostrud exercitat 4 | ion ullamco laboris nisi ut aliquip ex ea commodo consequ 5 | at. Duis aute irure dolor in reprehenderit in voluptate v 6 | elit esse cillum dolore eu fugiat nulla pariatur. Excepte 7 | ur sint occaecat cupidatat non proident, sunt in culpa qu 8 | i officia deserunt mollit anim id est laborum -------------------------------------------------------------------------------- /Exam/Semester_1/n7_2.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void main() { 5 | int n = 0; 6 | scanf("%d\n", &n); 7 | 8 | char* arr = (char*) malloc((n + 1) * sizeof(char)); 9 | for (int i = 0; i < n; i++) 10 | scanf("%c", &arr[i]); 11 | arr[n] = 0; 12 | 13 | printf("%s\n", arr); 14 | 15 | arr = (char*) realloc(arr, (2*n+1) * sizeof(char)); 16 | for (int i = 0; i < n; i++) 17 | arr[i+n] = arr[i]; 18 | arr[2*n] = 0; 19 | 20 | printf("%s", arr); 21 | 22 | free(arr); 23 | } -------------------------------------------------------------------------------- /Variants/Lab_9/var_11/sequence.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "stdio.h" 4 | #include "stdlib.h" 5 | 6 | // подсчет количества значащих бит в числе 7 | int count_bits(unsigned long long N); 8 | 9 | // конвертация uint64 в массив бит 10 | char *dtoab(unsigned long long N); 11 | 12 | // нахождение длины максимальной 13 | // последовательности из единиц 14 | int count_max_ones(unsigned long long N); 15 | 16 | // нахождение количества серий 17 | // из единиц длинной больше 2 18 | int count_ones_series(unsigned long long N); -------------------------------------------------------------------------------- /Variants/Lab_9/var_12/lab.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "stdio.h" 4 | #include "stdlib.h" 5 | 6 | // инвертирует каждый четвертый бит числа 7 | unsigned int invert_4(unsigned int N); 8 | 9 | // инвертирует каждый N-ый бит числа (32 bit) 10 | unsigned int invert_every_nth(unsigned int N, unsigned int bit); 11 | 12 | // определяет, каждый какой бит инвертирован 13 | unsigned int get_invert_offset(unsigned int a, unsigned int b); 14 | 15 | // красивый вывод двоичного числа на экран 16 | void print_bin(unsigned int N); -------------------------------------------------------------------------------- /Semester_2/Lab_11/base/strpbrk.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | // изменено на my_strpbrk для избежания конфликта с библиотечной функцией 4 | const char *my_strpbrk(const char *string, const char *chars) { 5 | char *temp = (char *)string; 6 | while (*temp != 0) { 7 | for (int i = 0; chars[i] != 0; i++) 8 | if (*temp == chars[i]) return temp; 9 | temp++; 10 | } 11 | return nullptr; 12 | } 13 | 14 | // ищет в строке string символы из строки chars 15 | // возвращает указатель на первый найденный символ в строке string -------------------------------------------------------------------------------- /Variants/Lab_12/var_11/main.cpp: -------------------------------------------------------------------------------- 1 | // Создайте класс Time с конструкторами 2 | // Time(), Time(int hour), Time(int hour, int min), 3 | // Time(int h, int m, int s) и Time(char *time) 4 | 5 | #include "time.h" 6 | 7 | using namespace std; 8 | 9 | int main() { 10 | Time test0(6, 18); 11 | test0.print(); 12 | 13 | Time test1("6:18:01"); 14 | test1.print(); 15 | 16 | Time test2("16:18"); 17 | test2.print(); 18 | 19 | test2 = test1; 20 | test2.print(); 21 | 22 | Time test3(test0); 23 | test3.print(); 24 | } -------------------------------------------------------------------------------- /Semester_1/Lab_1/dop.c: -------------------------------------------------------------------------------- 1 | // Ввести 10 действительных чисел 2 | // доп: вывести все локальные максимумы 3 | 4 | #include 5 | 6 | void main() { 7 | int flag = 0; 8 | int arr[10] = {0}; 9 | 10 | printf("Input 10 integers:\n"); 11 | for (int i = 0; i < 10; i++) scanf("%d", &arr[i]); 12 | 13 | for (int i = 1; i < 9; i++) 14 | if (arr[i] > arr[i + 1] && arr[i] > arr[i - 1]) { 15 | printf("%d ", arr[i]); 16 | flag = 1; 17 | } 18 | 19 | if (!flag) printf("There are no local max values :(\n"); 20 | } -------------------------------------------------------------------------------- /Exam/Semester_3/vtit.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() { 6 | int a[4] = {1, 2, 3, 4}; 7 | int cum_sum = 0; 8 | 9 | for (int i = 0; i < 4; i++) { 10 | cum_sum += a[i]; 11 | } 12 | 13 | cout << cum_sum << endl; 14 | 15 | // divide by 4 via bit shift 16 | cum_sum = cum_sum >> 2; 17 | 18 | cout << cum_sum << endl; 19 | return 0; 20 | 21 | // pseudo code (assembly using add and sh) 22 | // add r0, r1 23 | // add r0, r2 24 | // add r0, r3 25 | // sh r0 26 | // sh r0 27 | } -------------------------------------------------------------------------------- /Test/Templates/neuro.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Neuro { 8 | private: 9 | vector input; 10 | vector hidden; 11 | vector output; 12 | vector weights; 13 | 14 | public: 15 | Neuro(int in, int hide, int out): 16 | input(in), 17 | hidden(hide), 18 | output(out), 19 | weights(in * hide + hide * out) { 20 | } 21 | }; 22 | 23 | int main() { 24 | Neuro net(18, 9, 1); 25 | } -------------------------------------------------------------------------------- /Semester_3/Lab_17/dop/matrix.json: -------------------------------------------------------------------------------- 1 | { 2 | "columns": 7, 3 | "data": [ 4 | 41, 5 | 67, 6 | 34, 7 | 0, 8 | 69, 9 | 24, 10 | 78, 11 | 58, 12 | 62, 13 | 64, 14 | 5, 15 | 45, 16 | 81, 17 | 27, 18 | 61, 19 | 91, 20 | 95, 21 | 42, 22 | 27, 23 | 36, 24 | 91, 25 | 4, 26 | 2, 27 | 53, 28 | 92, 29 | 82, 30 | 21, 31 | 16, 32 | 18, 33 | 95, 34 | 47, 35 | 26, 36 | 71, 37 | 38, 38 | 69 39 | ], 40 | "rows": 5 41 | } 42 | -------------------------------------------------------------------------------- /Exam/Semester_1/n1_2.c: -------------------------------------------------------------------------------- 1 | #define test 42 // константа 2 | 3 | #define sum(a, b) a + b // макрос 4 | 5 | #define include_libs 1 // настройка 6 | 7 | #ifdef include_libs // эту проверку выполняет препроцессор 8 | #include 9 | #include 10 | #endif 11 | 12 | void main() { 13 | int a = 1; 14 | int b = 42; 15 | 16 | int x = sum(a, b); // тут просто происходит замена на макрос sum 17 | int y = sum(a, b) * 2; // a + b * 2 18 | int z = (sum(a, b)) * 2; // (a + b) * 2 19 | printf("%d %d %d", x, y, z); 20 | 21 | } -------------------------------------------------------------------------------- /Exam/Semester_1/n2_2.c: -------------------------------------------------------------------------------- 1 | void main() { 2 | int a = 3; 3 | int b = 5; 4 | 5 | int c1 = a + b; 6 | int c2 = a - b; 7 | unsigned int c21 = a - b; 8 | int c3 = a * b; 9 | int c41 = a / b; 10 | float c42 = a / b; 11 | float c43 = ((float) a) / b; 12 | 13 | int d0 = ~a; 14 | int d1 = a & b; 15 | int d2 = a | b; 16 | int d3 = a ^ b; 17 | 18 | // побитовый сдвиг влево на 2 19 | int e_l = a << 2; // 00000011 << 00001100 (12) 20 | 21 | // побитовый сдвиг вправо на 1 22 | int e_r = b >> 1; // 00000101 >> 00000010 (3) 23 | } -------------------------------------------------------------------------------- /Semester_2/Lab_7/base/main.cpp: -------------------------------------------------------------------------------- 1 | // Написать генератор псевдослучайных чисел по алгоритму 2 | // f(n) = f(n-1) + f(n-2) + f(n-3) mod 211 3 | // (начальные условия: f(0) = f(1) = f(2) = 1) 4 | // Подсчитать частоту каждого числа при выборке 100000 5 | 6 | #include "rand.h" 7 | 8 | #define ITER 100000 9 | #define WIDE 40 10 | 11 | int main() { 12 | int array[NUMS] = {0}; 13 | for (int i = 0; i < ITER; i++) array[gen()]++; 14 | printf("%-4s| %s\n----|-----\n", "num", "freq"); 15 | for (int i = 0; i < NUMS; i++) printf("%-4d| %d\n", i, array[i]); 16 | } -------------------------------------------------------------------------------- /Exam/Semester_1/n4_1.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void main () { 4 | int a = 1; 5 | int b = 2; 6 | 7 | if (a == b) { 8 | printf("это неправда"); 9 | } else if (a > b) { 10 | printf("это тоже неправда"); 11 | } else if (a < b) { 12 | printf("вот это уже правда"); 13 | } else { 14 | printf("это не выполнится"); 15 | } 16 | 17 | int s = 1; 18 | switch (s) { 19 | case 0: 20 | printf("s = 0"); 21 | break; 22 | case 1: 23 | printf("s = 1"); 24 | break; 25 | default: 26 | printf("s равен чему-то другому"); 27 | break; 28 | } 29 | } -------------------------------------------------------------------------------- /Exam/Semester_1/n3_2.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void main() { 4 | for (int i = 0; i < 10; i++) { 5 | if (i == 6) break; 6 | printf("%d ", i); 7 | } 8 | printf("\n"); 9 | 10 | for (int i = 0; i < 10; i++) { 11 | if (i == 6) continue; 12 | printf("%d ", i); 13 | } 14 | printf("\n"); 15 | 16 | for (int a = 0; a < 10; a++) { 17 | for (int b = 0; b < 10; b++) { 18 | for (int c = 0; c < 10; c++) { 19 | if ((a == 6) && (b == 1) && (c == 8)) goto exit; 20 | printf("%d%d%d ", a, b, c); 21 | } 22 | } 23 | } 24 | exit: 25 | printf("\nexit"); 26 | } -------------------------------------------------------------------------------- /Variants/Lab_7/var_11/frand.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | // случайное число в диапазоне [0, 1] 7 | #define frand() ((float)(rand())/(RAND_MAX)) 8 | 9 | // округление 10 | int round(float f, int N); 11 | 12 | // случайное число в диапазоне [-n ... n] 13 | #define frand_n(n) (frand() * n * 2 - n) 14 | 15 | // случайное число в диапазоне [-n ... n], 16 | // с нормальным распределением, используя 17 | // Центральную Предельную теорему 18 | float normal_frand_n(int count, int n); 19 | 20 | // красивый вывод на экран 21 | void pretty_print(int *arr, int n, int wide); -------------------------------------------------------------------------------- /Semester_2/Lab_8/base/main.cpp: -------------------------------------------------------------------------------- 1 | // Сортировка вставками: пусть первые k элементов упорядочены по возрастанию 2 | // Берется (k+1)-ый элемент и размещается среди первых k так, 3 | // чтобы упорядоченными оказались k+1 элементов. 4 | // Этот метод применяется при k от 1 до n-1 5 | 6 | #include "sort.h" 7 | #define N 15 // кол-во элементов 8 | 9 | int main() { 10 | int arr[N] = {7, 2, 12, 16, 8, 17, 11, 13, 4, 1, 15, 20, 19, 3, 18}; 11 | printf("%-11s", "original:"); 12 | print_arr(arr, N); 13 | 14 | // сортируем массив 15 | sort(arr, N); 16 | printf("%-11s", "sorted:"); 17 | print_arr(arr, N); 18 | } -------------------------------------------------------------------------------- /Exam/Semester_1/n8_2.c: -------------------------------------------------------------------------------- 1 | // stdin, stdout, stderr, printf, scanf, sprintf, sscanf 2 | 3 | #include 4 | 5 | void main() { 6 | // fprintf(stdout, ...) == printf(...) 7 | // fscanf(stdin, ...) == scanf(...) 8 | // stderr - стандартный поток для ошибок 9 | 10 | int a = 1; 11 | int b = 2; 12 | printf("a = %d, b = %d\n", a, b); 13 | scanf("%d %d", &a, &b); 14 | printf("a = %d, b = %d\n", a, b); 15 | 16 | char arr[] = "6 1 8"; 17 | int c = 0; 18 | sscanf(arr, "%d %d %d", &a, &b, &c); 19 | char arr2[20] = {0}; 20 | sprintf(arr2, "a = %d, b = %d, c = %d", a, b, c); 21 | printf(arr2); 22 | } -------------------------------------------------------------------------------- /Semester_2/Lab_10/dop/main.cpp: -------------------------------------------------------------------------------- 1 | // По символьному файлу с текстом создать новый файл 2 | // с форматированным текстом, в котором в каждой строке 3 | // первое слово начинается с 3-ей позиции, 4 | // а последнее заканчивается в 60-ой позиции 5 | 6 | // доп: удаление всех пробелов 7 | 8 | #include "file.h" 9 | 10 | #define START_POS 3 // начальная позиция (отступ) 11 | #define END_POS 60 // конечная позиция (перенос строки) 12 | #define NO_WHITESPACE true // удалять ли пробелы 13 | 14 | int main() { 15 | parse_file("input.txt", "output.txt", START_POS, END_POS, NO_WHITESPACE); 16 | print_file("output.txt"); 17 | } -------------------------------------------------------------------------------- /Semester_2/Lab_7/base/rand.cpp: -------------------------------------------------------------------------------- 1 | #include "rand.h" 2 | 3 | // генерируем случайное число 4 | int gen() { 5 | static int f0 = 1, f1 = 1, f2 = 1, f = 0; 6 | f = (f0 + f1 + f2) % NUMS; 7 | f0 = f1; 8 | f1 = f2; 9 | f2 = f; 10 | return f; 11 | } 12 | 13 | // красиво выводим на экран 14 | void pretty_print(int *arr, int n, int wide) { 15 | int max = 0; 16 | for (int i = 0; i < n; i++) 17 | if (arr[i] > max) max = arr[i]; 18 | int w = max / wide; 19 | for (int i = 0; i < n; i++) { 20 | printf("%-4d| ", i); 21 | for (int j = 0; j < arr[i] / w; j++) printf("#"); 22 | printf("\n"); 23 | } 24 | } -------------------------------------------------------------------------------- /Variants/Lab_12/var_11/time.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | class Time { 8 | private: 9 | int _hour, _minute, _second; 10 | 11 | public: 12 | // конструкторы 13 | 14 | Time(int hour = 0, int minute = 0, int second = 0); 15 | Time(const char *time); 16 | 17 | // сеттеры 18 | 19 | void set_hour(int h); 20 | void set_minute(int m); 21 | void set_second(int s); 22 | 23 | // геттеры 24 | 25 | int get_hour(); 26 | int get_minute(); 27 | int get_second(); 28 | 29 | // вывод на экран 30 | 31 | void print(); 32 | }; -------------------------------------------------------------------------------- /Exam/Semester_1/n3_1.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void main() { 4 | int a = 3; 5 | int b = 5; 6 | 7 | int c1 = a < b; 8 | int c2 = a > b; 9 | int c3 = a <= b; 10 | int c4 = a >= b; 11 | int c5 = a == b; 12 | int c6 = a != b; 13 | 14 | int sum = 0; 15 | int i = 0; 16 | for (i = 0; i < 10; i++) { 17 | sum += i; 18 | } 19 | 20 | sum = 0; 21 | for (i = 0; i <= 100; i *= 2) 22 | sum += i; 23 | 24 | i = 0; 25 | sum = 0; 26 | while (i < 10) { 27 | sum += i; 28 | i++; 29 | } 30 | 31 | i = 0; 32 | sum = 0; 33 | do { 34 | sum += i; 35 | i++; 36 | } while (i < 10); 37 | } -------------------------------------------------------------------------------- /Exam/Semester_1/n5_2.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void main() { 4 | int a = 42; 5 | int* p_a = &a; // указатель на ячейку a 6 | // размер указателя всегда одинаков 7 | // те. sizeof(char*) == sizeof(int*) == sizeof(float*) 8 | 9 | printf("%d %d %d\n", a, p_a, *p_a); 10 | // 42 6422296 42 (второе число = адрес в памяти) 11 | 12 | int arr[] = {0, 1, 2, 3, 4, 5}; 13 | // arr - это уже указатель на 0 элемент 14 | int* p_arr = arr; 15 | printf("%d %d ", p_arr, *p_arr); // 9683598 0 16 | printf("%d %d %d", *p_arr, *(p_arr+1), *(p_arr+2)); // 0 1 2 17 | } 18 | 19 | // arr[i] == *(arr + i) 20 | // i[arr] == *(i + arr) 21 | // эти записи аналогичны -------------------------------------------------------------------------------- /Semester_2/Lab_10/v2/file.cpp: -------------------------------------------------------------------------------- 1 | #include "file.h" 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | string read_file(const char *path) { 9 | ifstream file(path); 10 | stringstream stream; 11 | stream << file.rdbuf(); 12 | file.close(); 13 | return stream.str(); 14 | } 15 | 16 | void read_file(const char *path, string &str) { str = read_file(path); } 17 | 18 | void split_lines(string &str) { 19 | for (int i = 0; i < str.length(); i += 60) str.insert(i, (i) ? "\n " : " "); 20 | } 21 | 22 | void write_file(string str, const char *path) { 23 | ofstream out("output.txt"); 24 | out << str; 25 | out.close(); 26 | } -------------------------------------------------------------------------------- /Semester_1/Lab_6/main.c: -------------------------------------------------------------------------------- 1 | // По символьному файлу составить два линейных списка слов, 2 | // упорядоченных по алфавиту и по количеству гласных букв 3 | // вывести оба списка 4 | 5 | #include "snippets.h" 6 | #define ORDER NORMAL 7 | 8 | void main() { 9 | file *file = read_file("input/large.txt"); 10 | list *words = parse_file(file); 11 | 12 | printf("\n---- NOT SORTED -----\n"); 13 | print_list(words); 14 | 15 | printf("\n--- ALPHABET SORT ---\n"); 16 | sort_list(words, ALPHABET, ORDER); 17 | print_list(words); 18 | 19 | printf("\n---- VOWELS SORT ----\n"); 20 | sort_list(words, VOWELS, ORDER); 21 | print_list(words); 22 | 23 | destroy(words); 24 | } -------------------------------------------------------------------------------- /Semester_2/Lab_6/base/main.cpp: -------------------------------------------------------------------------------- 1 | // По символьному файлу составить два линейных списка слов, 2 | // упорядоченных по алфавиту и по количеству гласных букв 3 | // вывести оба списка 4 | 5 | #include "snippets.h" 6 | #define ORDER NORMAL 7 | 8 | int main() { 9 | file *file = read_file("input.txt"); 10 | list *words = parse_file(file); 11 | 12 | printf("\n---- NOT SORTED -----\n"); 13 | print_list(words); 14 | 15 | printf("\n--- ALPHABET SORT ---\n"); 16 | sort_list(words, ALPHABET, ORDER); 17 | print_list(words); 18 | 19 | printf("\n---- VOWELS SORT ----\n"); 20 | sort_list(words, VOWELS, ORDER); 21 | print_list(words); 22 | 23 | destroy(words); 24 | } -------------------------------------------------------------------------------- /Variants/Lab_7/var_7/main.cpp: -------------------------------------------------------------------------------- 1 | #include "dtoa.h" 2 | #include 3 | 4 | // Написать функцию для преобразования переменной типа double в строку символов 5 | // с заданной точностью представления dtoa(double num, int npos, int nfr) 6 | // npos - общее число знаков (включая запятую) 7 | // nfr - число знаков после запятой 8 | 9 | 10 | int main() { 11 | double d1 = -39877789.141592; 12 | double d2 = 36549876; 13 | double d3 = -3.141592; 14 | double d4 = 0; 15 | 16 | printf("\n%f\n%s\n", d1, dtoa(d1, 16, 6)); 17 | printf("\n%f\n%s\n", d2, dtoa(d2, 8, 0)); 18 | printf("\n%f\n%s\n", d3, dtoa(d3, 9, 6)); 19 | printf("\n%f\n%s\n", d4, dtoa(d4, 3, 1)); 20 | } -------------------------------------------------------------------------------- /Turlikov/Report_1/combinations/binom_optimal.h: -------------------------------------------------------------------------------- 1 | #include 2 | // #include 3 | using namespace std; 4 | 5 | uint64_t c (uint16_t n, uint16_t k) { 6 | if (n == 0 || n < k) return 0; 7 | if (k == 0 || n == k) return 1; 8 | if (k == 1 || k == n - 1) return n; 9 | 10 | uint16_t len = (n - k > k ? k : n - k); // min (k, n - k) 11 | 12 | double answer = 1; 13 | for (uint16_t i = 0; i < len; i++) 14 | answer *= ((double)(n - i) / (double)(i + 1)); 15 | 16 | // cout << (n - i) << " / " 17 | // << (i + 1) << " = " 18 | // << ((double)(n - i) / (double)(i + 1)) 19 | // << endl; 20 | 21 | return (uint64_t) answer; 22 | } -------------------------------------------------------------------------------- /Variants/Lab_20/var_2/dop/graph.dot: -------------------------------------------------------------------------------- 1 | digraph G { 2 | 1 -> 2 [color=green] 3 | 1 -> 5 [color=red] 4 | 2 -> 1 [color=red] 5 | 3 -> 5 [color=red] 6 | 3 -> 8 [color=green] 7 | 4 -> 5 [color=red] 8 | 5 -> 1 [color=green] 9 | 5 -> 3 [color=green] 10 | 5 -> 4 [color=green] 11 | 5 -> 6 [color=red] 12 | 5 -> 7 [color=blue] 13 | 6 -> 5 [color=green] 14 | 6 -> 10 [color=red] 15 | 7 -> 5 [color=blue] 16 | 7 -> 10 [color=red] 17 | 7 -> 12 [color=green] 18 | 8 -> 3 [color=red] 19 | 8 -> 9 [color=green] 20 | 8 -> 11 [color=blue] 21 | 9 -> 8 [color=red] 22 | 10 -> 6 [color=green] 23 | 10 -> 7 [color=green] 24 | 11 -> 8 [color=blue] 25 | 11 -> 12 [color=red] 26 | 12 -> 7 [color=red] 27 | 12 -> 11 [color=green] 28 | } -------------------------------------------------------------------------------- /Variants/Lab_9/var_11/main.cpp: -------------------------------------------------------------------------------- 1 | // Ввести целое число N. Найти длину 2 | // самой длинной последовательности единиц 3 | // в его двоичном представлении 4 | 5 | // доп: вывести кол во серий из единиц длинной больше 2 6 | 7 | #include "sequence.h" 8 | #define DOP 9 | 10 | int main() { 11 | // вводим N 12 | unsigned long long N; 13 | printf("Enter N: "); 14 | scanf("%llu", &N); 15 | 16 | printf( // выводим результат 17 | "%llu -> bin: %s\nMax length: %d\n", 18 | N, dtoab(N), count_max_ones(N) 19 | ); 20 | 21 | #ifdef DOP 22 | 23 | printf( // количество серий из единиц 24 | "Series with length > 2: %d\n", 25 | count_ones_series(N) 26 | ); 27 | 28 | #endif 29 | } -------------------------------------------------------------------------------- /Exam/Semester_1/n8_1.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void main() { 5 | char arr[100] = {0}; 6 | int i = 0; 7 | 8 | FILE *fin = fopen("test.txt", "r"); 9 | if (ferror(fin)) 10 | printf("ошибка открытия текстового файла"); 11 | 12 | while (!feof(fin)) { 13 | char c = 0; 14 | if (fscanf(fin, "%c", &c)) 15 | arr[i++] = c; 16 | } 17 | printf("%s", arr); 18 | fclose(fin); 19 | 20 | FILE *fout = fopen("output.txt", "w"); 21 | if (fout == NULL) 22 | printf("ошибка открытия текстового файла"); 23 | 24 | fprintf(fout, "%s", arr); 25 | fclose(fout); 26 | } 27 | 28 | // fseek - перемещает файловый курсор 29 | // ftell - возвращает текущую позицию в файле -------------------------------------------------------------------------------- /Semester_2/Lab_9/base/polynom.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "fractions.h" 3 | 4 | struct polynom { 5 | unsigned int n; // количество коэффициентов 6 | fraction *koeffs; // массив коэффициентов (дробей) 7 | }; 8 | 9 | polynom *new_polynom(long long *k, unsigned int n); 10 | polynom *new_polynom(fraction *f, unsigned int n); 11 | polynom *new_binom(long long a); 12 | 13 | void print_polynom(const char s[], polynom *p); 14 | void print_koeffs(long long *arr, unsigned int n); 15 | 16 | void upd_polynom(polynom *p, long long *k, unsigned int n); 17 | void upd_binom(polynom *p, long long a); 18 | void destroy(polynom *p); 19 | 20 | polynom *multiply(polynom *a, polynom *b); 21 | void multiply(polynom *m, polynom *a, polynom *b); 22 | -------------------------------------------------------------------------------- /Variants/Lab_7/var_11/main.cpp: -------------------------------------------------------------------------------- 1 | // Написать генератор псевдослучайных чисел, равномерно распределенных 2 | // на интервале [-5., 5.] (использовать rand()). Подсчитать частоты 3 | // попадания в каждый из интервалов длиной 1 при выборке 500000 4 | 5 | // реализовать равномерный закон распределения. у меня нормальный 6 | 7 | #include "frand.h" 8 | 9 | #define N 5 // границы интервала 10 | #define NUM 500000 // кол-во итераций 11 | #define POWER 6 // коэффициент распределения 12 | 13 | 14 | int main() { 15 | // массив [-5., 5.] 16 | int freq[N * 2] = {0}; 17 | 18 | // подсчитываем кол-во появлений 19 | for (int i = 0; i < NUM; i++) 20 | freq[round(frand_n(N), N)]++; 21 | 22 | // красиво выводим на экран 23 | pretty_print(freq, N, 30); 24 | } -------------------------------------------------------------------------------- /Practice/Lab_15/extended/main.cpp: -------------------------------------------------------------------------------- 1 | // Написать программу, формирующую по исходному BMP файлу новый BMP файл 2 | // повернутый по часовой стрелке на 90 градусов. 3 | 4 | // Указывать имена файлов исходных и результирующих файлов в командной строке 5 | // файлы после обработки заголовков читать целиком в динамически выделенную 6 | // память 7 | 8 | #include 9 | 10 | #include "bmp.hpp" 11 | 12 | using namespace std; 13 | 14 | int main(int argc, char* argv[]) { 15 | if (argc != 3) { 16 | cout << "Usage: " << argv[0] << " " << endl; 17 | return 1; 18 | } 19 | 20 | BitMap bmp(argv[1]); 21 | bmp.Print(); 22 | bmp.Rotate(BitMap::RotateType::Rotate90); 23 | bmp.Print(); 24 | bmp.Save(argv[2]); 25 | 26 | return 0; 27 | } -------------------------------------------------------------------------------- /Semester_2/Lab_9/dop/polynom.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "fractions.h" 3 | 4 | struct polynom { 5 | unsigned int n; // количество коэффициентов 6 | fraction *koeffs; // массив коэффициентов (дробей) 7 | }; 8 | 9 | polynom *new_polynom(long long *k, unsigned int n); 10 | polynom *new_polynom(fraction *f, unsigned int n); 11 | polynom *new_binom(long long a); 12 | 13 | void print_polynom(const char s[], polynom *p); 14 | void print_koeffs(long long *arr, unsigned int n); 15 | 16 | void upd_polynom(polynom *p, long long *k, unsigned int n); 17 | void upd_binom(polynom *p, long long a); 18 | void destroy(polynom *p); 19 | 20 | polynom *multiply(polynom *a, polynom *b); 21 | void multiply(polynom *m, polynom *a, polynom *b); 22 | void integral(polynom *y, polynom *f); 23 | -------------------------------------------------------------------------------- /Semester_3/Lab_17/dop/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | include(FetchContent) 4 | 5 | # Название проекта 6 | project(Lab_17_dop) 7 | 8 | # Отображает сообщение 9 | message(STATUS "Downloading json") 10 | 11 | # Отображает прогресс скачивания 12 | set(FETCHCONTENT_QUIET OFF) 13 | 14 | # Скачивает библиотеку 15 | FetchContent_Declare(json URL https://github.com/nlohmann/json/releases/download/v3.11.2/json.tar.xz) 16 | 17 | # Устанавливает библиотеку 18 | FetchContent_MakeAvailable(json) 19 | 20 | # Отображает сообщение 21 | message(STATUS "Downloading json done") 22 | 23 | # Создает исполняемый файл 24 | add_executable(Lab_17_dop main.cpp) 25 | 26 | # Линковка программы с библиотекой 27 | target_link_libraries(Lab_17_dop PRIVATE nlohmann_json::nlohmann_json) -------------------------------------------------------------------------------- /Turlikov/Report_1/pascal_triangle/pascal_vec.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | uint64_t get(vector &vec, uint16_t i) { 8 | if (i < 0 || i >= vec.size()) return 0; 9 | else return vec[i]; 10 | } 11 | 12 | void print(vector &vec) { 13 | for (int i = 0; i < vec.size(); i++) 14 | cout << vec[i] << endl; 15 | } 16 | 17 | void print_line(uint16_t line) { 18 | vector prev; 19 | vector now {1}; 20 | 21 | for (int i = 0; i < line; i++) { 22 | prev = now; 23 | now.resize(now.size() + 1); 24 | 25 | // заполняем новую строку треугольника 26 | for (int x = 0; x < now.size(); x++) 27 | now[x] = get(prev, x-1) + get(prev, x); 28 | } 29 | 30 | print(now); 31 | } -------------------------------------------------------------------------------- /Turlikov/Report_1/pascal_triangle/pascal_arr.h: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void print(unsigned long long *arr, int size) { 5 | for (int i = 0; i < size; i++) 6 | cout << arr[i] << endl; 7 | } 8 | 9 | void copy_arr(unsigned long long *arr1, unsigned long long *arr2, int size) { 10 | for (int i = 0; i < size; i++) 11 | arr1[i] = arr2[i]; 12 | } 13 | 14 | void print_line(int line) { 15 | int size = line + 1; 16 | unsigned long long prev[size] = {0}; 17 | unsigned long long now[size] = {0}; 18 | now[0] = 1; 19 | 20 | for (int i = 1; i < size; i++) { 21 | copy_arr(prev, now, size); 22 | // заполняем новую строку треугольника 23 | for (int x = 1; x < size; x++) 24 | now[x] = prev[x - 1] + prev[x]; 25 | } 26 | 27 | print(now, size); 28 | } -------------------------------------------------------------------------------- /Semester_3/Lab_17/dop/point.json: -------------------------------------------------------------------------------- 1 | { 2 | "columns": 3, 3 | "data": [ 4 | { 5 | "x": 1, 6 | "y": 2, 7 | "z": 3 8 | }, 9 | { 10 | "x": 4, 11 | "y": 5, 12 | "z": 6 13 | }, 14 | { 15 | "x": 7, 16 | "y": 8, 17 | "z": 9 18 | }, 19 | { 20 | "x": 10, 21 | "y": 11, 22 | "z": 12 23 | }, 24 | { 25 | "x": 13, 26 | "y": 14, 27 | "z": 15 28 | }, 29 | { 30 | "x": 16, 31 | "y": 17, 32 | "z": 18 33 | }, 34 | { 35 | "x": 19, 36 | "y": 20, 37 | "z": 21 38 | }, 39 | { 40 | "x": 22, 41 | "y": 23, 42 | "z": 24 43 | }, 44 | { 45 | "x": 25, 46 | "y": 26, 47 | "z": 27 48 | } 49 | ], 50 | "rows": 3 51 | } 52 | -------------------------------------------------------------------------------- /Variants/Lab_7/var_12/frand.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "frand.h" 5 | 6 | // инициализация генератора случайных чисел 7 | // чтобы при каждом запуске программы выводились разные 8 | // случайные последовательности 9 | void rand_init() { 10 | srand(time(NULL)); 11 | } 12 | 13 | // чтобы получить случайную величину с нормальным распределением, 14 | // применяем центральную предельную теорему 15 | // (ее суть заключается в нахождении среднего арифметического 16 | // нескольких случайных чисел) 17 | double frand(double n, int count) { 18 | double sum = 0; 19 | // находим среднее арифметическое 20 | for (int i = 0; i < count; i++) 21 | sum += rand_1 * n; // n - верхняя граница диапазона, 22 | // в котором генерируются случайные числа [0..n] 23 | return sum / count; 24 | } -------------------------------------------------------------------------------- /Exam/Semester_1/n5_1.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void main() { 4 | int int_arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; 5 | int arr_2d[2][2] = {{1, 2}, {3, 4}}; 6 | char char_arr[] = "hello world"; // строки заканчиваются числом 0 7 | 8 | int_arr[1] = 42; 9 | int_arr[15] = 42; // ошибка (выход за границу массива) 10 | // эта ошибка не улавливается компилятором 11 | 12 | for (int i = 0; i < 10; i++) 13 | printf("%d ", int_arr[i]); 14 | printf("\n"); 15 | 16 | for (int i = 0; char_arr[i] != 0; i++) 17 | printf("%c", char_arr[i]); 18 | printf("\n"); 19 | 20 | // ввод массива с клавиатуры 21 | int test_arr[10] = {0}; // зануление массива 22 | for (int i = 0; i < 10; i++) { 23 | scanf("%d", &test_arr[i]); 24 | } 25 | 26 | for (int i = 0; i < 10; i++) 27 | printf("%d ", test_arr[i]); 28 | } -------------------------------------------------------------------------------- /Variants/Lab_8/var_5/dop/main.cpp: -------------------------------------------------------------------------------- 1 | // Ввести длину массива натуральных чисел и диапазон его значений 2 | // Ввести массив. Вывести упорядоченный массив при помощи сортировки подсчётом 3 | // Сделать по экспоненциальному закону распределения 4 | 5 | #include "lab.h" 6 | 7 | int main() { 8 | int size = 0, koeff = 0, capacity = 1, razn = 0; 9 | printf("Enter the length of the array:\n"); 10 | scanf("%d", &size); 11 | 12 | while (capacity < size) capacity *= 2; 13 | int* mas = (int*) malloc(capacity * sizeof(int)); 14 | 15 | printf("Enter the exponential koeff:\n"); 16 | scanf("%d", &koeff); 17 | 18 | for (int i = 0; i < size; i++) 19 | mas[i] = (int) ran_expo(koeff); 20 | 21 | sort(size, mas); 22 | 23 | printf("\n\n"); 24 | for (int i = 0; i < size; i++) 25 | printf("%d ", mas[i]); 26 | 27 | free(mas); 28 | } -------------------------------------------------------------------------------- /Semester_3/Lab_18/dop/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.11) 2 | 3 | include(FetchContent) 4 | 5 | # Название проекта 6 | project(Lab_18_dop) 7 | 8 | # Скачиваем библиотеку 9 | FetchContent_Declare(json 10 | GIT_REPOSITORY https://github.com/nlohmann/json 11 | GIT_TAG v3.11.2 12 | ) 13 | 14 | # Добавляем библиотеку 15 | FetchContent_MakeAvailable(json) 16 | 17 | # Добавляем заголовочные файлы 18 | include_directories(include) 19 | 20 | # Создает исполняемый файл 21 | add_executable(Lab_18_dop main.cpp cache.cpp translate.cpp) 22 | 23 | # Скопировать файлы words.json и input.txt в папку сборки 24 | configure_file(words.json words.json COPYONLY) 25 | configure_file(input.txt input.txt COPYONLY) 26 | 27 | # Линковка программы с библиотекой 28 | target_link_libraries(Lab_18_dop PRIVATE nlohmann_json::nlohmann_json) -------------------------------------------------------------------------------- /Exam/Semester_1/n7_1.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // глобальные переменные 4 | int global_var = 42; 5 | int x, y, z; 6 | 7 | void sum() { 8 | static int static_var; // доступен только в этой функции 9 | static_var = 777; 10 | // не сбрасывает значение при повторном заходе в функцию 11 | x = y + z; 12 | // здесь доступны переменные x, y, z, global_var 13 | // но не доступна переменная main_var (она локальная) 14 | 15 | // printf("%d", main_var); - ошибка 16 | // потому что это локальная переменная в другой функции 17 | } 18 | 19 | void main() { 20 | int main_var = 618; 21 | x = 6; 22 | y = 1; 23 | z = 8; 24 | sum(); 25 | printf("%d %d %d ", x, y, z); 26 | printf("%d %d ", global_var, main_var); 27 | 28 | // printf("%d", static_var); 29 | // ошибка потому что это локальная переменная в другой функции 30 | } -------------------------------------------------------------------------------- /Turlikov/Report_2/report/n2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | static unsigned long long A[] = {0x00, 0x0d, 0x16, 0x1f}; 5 | 6 | unsigned long long count_ones(unsigned long long n) { 7 | unsigned long long w = 0; 8 | while (n > 0) { 9 | w += n & 1; 10 | n = n >> 1; 11 | } 12 | return w; 13 | } 14 | 15 | int min_hamming(unsigned long long* arr, int size) { 16 | int minim = size; 17 | for (unsigned long long a = 0; a < size; a++) { 18 | for (unsigned long long b = a + 1; b < size; b++) { 19 | if (arr[a] != arr[b]) { 20 | int hamm = count_ones(arr[a] ^ arr[b]); 21 | minim = hamm < minim ? hamm : minim; 22 | } 23 | } 24 | } 25 | return minim; 26 | } 27 | 28 | int main() { 29 | cout << "min hamming distance: %d\n" << min_hamming(A, 4); 30 | } 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /Semester_2/Lab_7/dop/rand.cpp: -------------------------------------------------------------------------------- 1 | #include "rand.h" 2 | 3 | // генерируем случайное число 4 | int gen() { 5 | static int f0 = 1, f1 = 1, f2 = 1, f = 0; 6 | f = (f0 + f1 + f2) % NUMS; 7 | f0 = f1; 8 | f1 = f2; 9 | f2 = f; 10 | return f; 11 | } 12 | 13 | // генерируем нормальное распределение 14 | // используется: Центральная предельная теорема 15 | int gen_normal(int n) { 16 | int sum = 0; 17 | for (int i = 0; i < n; i++) sum += gen(); 18 | return sum / n; 19 | } 20 | 21 | // красиво выводим на экран 22 | void pretty_print(int *arr, int n, int wide) { 23 | int max = 0; 24 | for (int i = 0; i < n; i++) 25 | if (arr[i] > max) max = arr[i]; 26 | int w = max / wide; 27 | for (int i = 0; i < n; i++) { 28 | printf("%-4d| ", i); 29 | for (int j = 0; j < arr[i] / w; j++) printf("#"); 30 | printf("\n"); 31 | } 32 | } -------------------------------------------------------------------------------- /Turlikov/Report_1/combinations/other_versions/andrey.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | long long factor(long long a) { 4 | if ((a == 1) || (a == 0)) 5 | return 1; 6 | else 7 | return (a * factor(a - 1)); 8 | } 9 | 10 | long long multipl(long long a, long long b) { 11 | long long z = 1; 12 | for (int i = a; i <= b; i++) 13 | z = z * i; 14 | return z; 15 | } 16 | 17 | long long C_n_k(int n, int k) { 18 | return ((long long)(multipl(k + 1, n) / factor(n - k))); 19 | } 20 | 21 | long long closest(long long a) { 22 | int s = 0; 23 | while (a != 0) { 24 | a = a >> 1; 25 | s++; 26 | } 27 | return s - 1; 28 | } 29 | 30 | void test() { 31 | long long a, a_end; 32 | scanf("%llu", &a); 33 | 34 | a_end = closest(a); 35 | for (int i = 0; i <= a_end; i++) 36 | printf("With %d '1' is %d\n", i, C_n_k(a_end, i)); 37 | } -------------------------------------------------------------------------------- /Variants/Lab_7/var_7/dtoa.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | char *dtoa(double num, int npos, int nfr) { 7 | // npos --- общее число знаков (включая запятую) 8 | // nfr --- число знаков после запятой 9 | 10 | long long inum = fabs(round(num * pow(10, nfr))); 11 | char *s = (char *)malloc((npos + 1) * sizeof(char)); 12 | for (int i = 0; i < npos; i++) s[i] = '0'; 13 | s[npos] = '\0'; 14 | 15 | if (inum == 0) { 16 | s[1] = '.'; 17 | return s; 18 | } 19 | 20 | if (num < 0) s[0] = '-'; 21 | long long n = inum, digit_count = 1; 22 | while (n /= 10) digit_count++; 23 | int size = digit_count + 1 + (nfr > 0) + (num < 0); 24 | for (long long i = 0, n = inum; n != 0; n /= 10) { 25 | s[size - 2 - i++] = 48 + n % 10; 26 | if (nfr > 0 && i == nfr) 27 | s[size - 2 - i++] = '.'; 28 | } 29 | 30 | return s; 31 | } -------------------------------------------------------------------------------- /Variants/Lab_8/var_5/main.cpp: -------------------------------------------------------------------------------- 1 | // Ввести длину массива натуральных чисел и диапазон его значений 2 | // (минимально возможное и максимально возможное значения). 3 | // Ввести массив. Вывести упорядоченный массив при помощи сортировки подсчётом... 4 | // сделать по экспоненциальному закону распределения 5 | 6 | #include "lab.h" 7 | 8 | void main() { 9 | int size = 0, min = 0, max = 0, capacity = 1, razn = 0; 10 | printf("Enter the length of the array:\n"); 11 | scanf("%d", &size); 12 | 13 | while (capacity < size) capacity *= 2; 14 | int* mas = (int*) malloc(capacity * sizeof(int)); 15 | 16 | printf("Enter the min & max elements:\n"); 17 | scanf("%d %d", &min, &max); 18 | 19 | for (int i = 0; i < size; i++) 20 | mas[i] = gen(min,max); 21 | 22 | sort(size, mas); 23 | 24 | printf("\n\n"); 25 | for (int i = 0; i < size; i++) 26 | printf("%d ", mas[i]); 27 | 28 | free(mas); 29 | } -------------------------------------------------------------------------------- /Variants/Lab_18/var_2/database.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Person { 9 | private: 10 | string name; 11 | string surname; 12 | int year = 0; 13 | bool gender = 0; // 1 - woman, 0 - man 14 | int passport = 0; 15 | 16 | public: 17 | Person(); 18 | Person(string name, string surname, int year, bool gender, int passport); 19 | friend ostream &operator<<(ostream &out, Person &p); 20 | bool operator==(const Person &p1); 21 | }; 22 | 23 | class Database { 24 | private: 25 | vector db; 26 | 27 | public: 28 | void load(const string &filename); 29 | void save(const string &filename); 30 | void add(const Person &p); 31 | void erase(const Person &p); 32 | friend ostream &operator<<(ostream &out, Database &d); 33 | friend ofstream &operator<<(ofstream &out, Database &d); 34 | }; -------------------------------------------------------------------------------- /Semester_2/Lab_11/base/main.cpp: -------------------------------------------------------------------------------- 1 | // Написать функцию 2 | // const char* strpbrk(const char *string, const char *strCharSet) 3 | // работающую так же, как библиотечная и тестирующую программу к ней 4 | 5 | #include 6 | #include 7 | 8 | #include "strpbrk.h" 9 | 10 | int len = 0; 11 | char *readstr() { 12 | len = 0; 13 | int capacity = 1; 14 | char *s = (char *)malloc(sizeof(char)); 15 | char c = getchar(); 16 | while (c != '\n') { 17 | s[(len)++] = c; 18 | if (len >= capacity) { 19 | capacity *= 2; 20 | s = (char *)realloc(s, capacity * sizeof(char)); 21 | } 22 | c = getchar(); 23 | } 24 | s[len] = 0; 25 | return s; 26 | } 27 | 28 | int main() { 29 | printf("Enter string: "); 30 | char *str = readstr(); 31 | printf("Enter allowed chars: "); 32 | char *chrs = readstr(); 33 | printf("The first character found: %c", *my_strpbrk(str, chrs)); 34 | } -------------------------------------------------------------------------------- /Semester_2/Lab_14/base/shape.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Point { 9 | public: 10 | double x, y; 11 | Point(double x = 0, double y = 0); 12 | friend ostream &operator<<(ostream &out, Point &p); 13 | }; 14 | 15 | class Shape { 16 | protected: 17 | Point pos; 18 | unsigned long id; 19 | 20 | public: 21 | Shape(Point pos = {0}); 22 | virtual void print(); 23 | unsigned long get_id(); 24 | unsigned long next_id(); 25 | }; 26 | 27 | class Circle : public Shape { 28 | protected: 29 | double r; 30 | string text; 31 | 32 | public: 33 | Circle(Point pos = {0}, double r = 0, string text = ""); 34 | virtual void print(); 35 | }; 36 | 37 | class Segment : public Shape { 38 | protected: 39 | Point start, end; 40 | 41 | public: 42 | Segment(Point start = {0}, Point end = {0}); 43 | virtual void print(); 44 | }; -------------------------------------------------------------------------------- /Variants/Lab_12/var_11/time.cpp: -------------------------------------------------------------------------------- 1 | #include "time.h" 2 | 3 | Time::Time(int hour, int minute, int second): 4 | _hour(hour), _minute(minute), _second(second) { 5 | } 6 | 7 | Time::Time(const char *time): 8 | _hour(0), _minute(0), _second(0) { 9 | sscanf(time, "%d:%d:%d", &_hour, &_minute, &_second); 10 | _hour %= 24; _minute %= 60; _second %= 60; 11 | } 12 | 13 | // сеттеры 14 | 15 | void Time::set_hour(int h) { 16 | _hour = h % 24; 17 | } 18 | 19 | void Time::set_minute(int m) { 20 | _minute = m % 60; 21 | } 22 | 23 | void Time::set_second(int s) { 24 | _second = s % 60; 25 | } 26 | 27 | // геттеры 28 | 29 | int Time::get_hour() { 30 | return _hour; 31 | } 32 | 33 | int Time::get_minute() { 34 | return _minute; 35 | } 36 | 37 | int Time::get_second() { 38 | return _second; 39 | } 40 | 41 | // вывод на экран 42 | 43 | void Time::print() { 44 | printf("%02d:%02d:%02d\n", _hour, _minute, _second); 45 | } -------------------------------------------------------------------------------- /Variants/Lab_6/var_11/main.c: -------------------------------------------------------------------------------- 1 | // Написать функцию, расщепляющую упорядоченный линейный список целых чисел 2 | // на два упорядоченных списка: простых и составных чисел 3 | 4 | #include 5 | #include "snippets.c" 6 | 7 | void main() { 8 | // открываем и считываем файл 9 | file *file = read_file("test.txt"); 10 | 11 | // инициализируем списки чисел 12 | list *numbers = init_list(); 13 | list *primes = init_list(); 14 | list *composites = init_list(); 15 | 16 | // парсим числа из файла и разделяем их 17 | parse_file(file, numbers); 18 | split_primes(numbers, primes, composites); 19 | 20 | // выводим на экран 21 | printf("\nnumbers:\n"); 22 | print_list(numbers); 23 | printf("\nprimes:\n"); 24 | print_list(primes); 25 | printf("\ncomposites:\n"); 26 | print_list(composites); 27 | 28 | // очищаем память 29 | destroy(numbers); 30 | destroy(primes); 31 | destroy(composites); 32 | } -------------------------------------------------------------------------------- /Semester_2/Lab_11/dop/main.cpp: -------------------------------------------------------------------------------- 1 | // Написать функцию 2 | // const char* strpbrk(const char *string, const char *strCharSet) 3 | // работающую так же, как библиотечная и тестирующую программу к ней 4 | 5 | // доп: написать strcmp 6 | 7 | #include 8 | #include 9 | 10 | #include "strcmp.h" 11 | 12 | int len = 0; 13 | char *readstr() { 14 | len = 0; 15 | int capacity = 1; 16 | char *s = (char *)malloc(sizeof(char)); 17 | char c = getchar(); 18 | while (c != '\n') { 19 | s[(len)++] = c; 20 | if (len >= capacity) { 21 | capacity *= 2; 22 | s = (char *)realloc(s, capacity * sizeof(char)); 23 | } 24 | c = getchar(); 25 | } 26 | s[len] = 0; 27 | return s; 28 | } 29 | 30 | int main() { 31 | printf("Enter string 1: "); 32 | char *str1 = readstr(); 33 | printf("Enter string 2: "); 34 | char *str2 = readstr(); 35 | printf("Strcmp result: %d", my_strcmp(str1, str2)); 36 | } -------------------------------------------------------------------------------- /Semester_2/Lab_8/dop/sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void swap(int *a, int *b) { 4 | *a += *b; 5 | *b = *a - *b; 6 | *a -= *b; 7 | } 8 | 9 | void sort(int *arr, int n) { 10 | for (int k = 1; k < n; k++) 11 | for (int i = k; i > 0 && arr[i - 1] > arr[i]; i--) 12 | swap(&arr[i - 1], &arr[i]); 13 | } 14 | 15 | void qsort(int *arr, int n) { 16 | int i = 0, j = n - 1; 17 | int mid = arr[n / 2]; 18 | 19 | do { 20 | while (arr[i] < mid) i++; 21 | while (arr[j] > mid) j--; 22 | 23 | if (i <= j) { 24 | int tmp = arr[i]; 25 | arr[i] = arr[j]; 26 | arr[j] = tmp; 27 | i++; 28 | j--; 29 | } 30 | 31 | } while (i <= j); 32 | 33 | if (j > 0) qsort(arr, j + 1); // левый кусок 34 | if (i < n) qsort(&arr[i], n - i); // правый кусок 35 | } 36 | 37 | void print_arr(int *arr, int n) { 38 | for (int i = 0; i < n; i++) printf("%d ", arr[i]); 39 | printf("\n"); 40 | } -------------------------------------------------------------------------------- /Semester_3/Lab_18/base/cache.cpp: -------------------------------------------------------------------------------- 1 | #include "cache.h" 2 | 3 | using namespace std; 4 | 5 | LfuCache::LfuCache(size_t size) : size(size) {} 6 | 7 | bool LfuCache::find_and_add(const std::string &address) { 8 | auto it = cache.find(address); 9 | if (it != cache.end()) { 10 | freq.erase(freq.find(it->second)); 11 | freq.insert({++it->second, address}); 12 | return true; 13 | } else { 14 | if (cache.size() == size) { 15 | auto it2 = freq.begin(); 16 | cache.erase(it2->second); 17 | freq.erase(it2); 18 | } 19 | cache.insert({address, 1}); 20 | freq.insert({1, address}); 21 | return false; 22 | } 23 | } 24 | 25 | std::ostream &operator<<(std::ostream &out, const LfuCache &cache) { 26 | for (auto it = cache.freq.begin(); it != cache.freq.end(); ++it) { 27 | out << it->second << " - " << it->first 28 | << (it == --cache.freq.end() ? "" : ", "); 29 | } 30 | return out; 31 | } -------------------------------------------------------------------------------- /Turlikov/Report_2/hamming.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | 4 | typedef unsigned long long uint64; 5 | typedef unsigned char uint8; 6 | 7 | static uint64 code_table[] = {0x00, 0x0d, 0x16, 0x1b /* 0x1f */}; 8 | 9 | uint64 count_ones(uint64 n) { 10 | uint64 w = 0; 11 | while (n > 0) { 12 | w += n & 1; 13 | n = n >> 1; 14 | } 15 | return w; 16 | } 17 | 18 | uint64 coder(uint64 m) { return code_table[m]; } 19 | uint64 channel(uint64 a, uint64 e) { return a ^ e; } 20 | uint64 hamming(uint64 a, uint64 b) { return count_ones(a ^ b); } 21 | 22 | uint64 decoder(uint64 m) { 23 | uint64 ind = 0, min = 5; 24 | for (uint64 i = 0; i < 4; i++) { 25 | uint64 d = hamming(m, code_table[i]); 26 | if (d < min) { 27 | min = d; 28 | ind = i; 29 | } 30 | } 31 | return ind; 32 | } 33 | 34 | void printf_bin(uint64 n) { 35 | for (uint64 i = 0; i < 5; i++) 36 | printf("%d", (n >> (4 - i)) & 1); 37 | } -------------------------------------------------------------------------------- /Semester_3/Lab_18/dop/translate.cpp: -------------------------------------------------------------------------------- 1 | #include "translate.h" 2 | 3 | using namespace std; 4 | 5 | Translate::Translate(const string& filename, int cache_size = 16) 6 | : cache(cache_size) { 7 | ifstream file(filename); 8 | nlohmann::json j; 9 | file >> j; 10 | 11 | for (auto& [key, value] : j.items()) { 12 | words.push_back({key, value}); 13 | } 14 | } 15 | 16 | string Translate::translate(const string& word) { 17 | string translation = cache.get(word); 18 | if (translation != "") { 19 | return translation; 20 | } 21 | 22 | for (auto& pair : words) { 23 | if (pair.first == word) { 24 | cache.add(word, pair.second); 25 | return pair.second; 26 | } 27 | } 28 | 29 | return "<>"; 30 | } 31 | 32 | void Translate::print_cache() { cache.print(); } 33 | 34 | void Translate::print_words() { 35 | for (auto& pair : words) { 36 | cout << pair.first << " - " << pair.second << endl; 37 | } 38 | } -------------------------------------------------------------------------------- /Variants/Lab_7/var_11/frand.cpp: -------------------------------------------------------------------------------- 1 | #include "frand.h" 2 | 3 | // центральная предельная теорема 4 | float normal_frand_n(int count, int n) { 5 | float sum = 0; 6 | // находим среднее арифметическое 7 | for (int i = 0; i < count; i++) 8 | sum += frand_n(n); 9 | return sum / count; 10 | } 11 | 12 | // индекс нужного интервала 13 | int round(float f, int N) { 14 | if (f > 0) { 15 | return (int) f + N; 16 | } else { 17 | return N + (int) f - 1; 18 | } 19 | } 20 | 21 | // красивый вывод на экран 22 | void pretty_print(int *arr, int N, int wide) { 23 | int max = 0; 24 | // вычисление коэффициента максимальной 25 | for (int i = 0; i < N * 2; i++) 26 | if (arr[i] > max) max = arr[i]; 27 | int w = max / wide; 28 | // выводим график на экран 29 | for (int i = 0; i < N * 2; i++) { 30 | printf("[%2d, %2d] %6d | ", i-N, i-N+1, arr[i]); 31 | for (int j = 0; j < arr[i] / w; j++) printf("#"); 32 | printf("\n"); 33 | } 34 | } -------------------------------------------------------------------------------- /Semester_2/Lab_9/base/fractions.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | struct fraction { 4 | long long koeff; 5 | long long divider; 6 | }; 7 | 8 | fraction *new_fraction(long long k, long long d); // {k, d} 9 | fraction *new_fraction(long long k); // {a, 1} 10 | fraction *new_fraction(); // {0, 1} 11 | 12 | long long gcd(long long a, long long b); 13 | void simplify_fraction(fraction *f); 14 | 15 | void set_fraction(fraction *f, long long k, long long d); // {k, d} 16 | void set_fraction(fraction *f, long long k); // {k, 1} 17 | void print_fraction(fraction *f); 18 | 19 | void sum_fractions(fraction *a, fraction *b); // a += b 20 | void sum_fractions(fraction *x, fraction *a, fraction *b); // x = a + b 21 | void multiply_fractions(fraction *f, fraction *a, fraction *b); // f = a * b 22 | void sum_multiply_fractions(fraction *f, fraction *a, 23 | fraction *b); // f += a * b -------------------------------------------------------------------------------- /Semester_2/Lab_9/dop/fractions.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | struct fraction { 4 | long long koeff; 5 | long long divider; 6 | }; 7 | 8 | fraction *new_fraction(long long k, long long d); // {k, d} 9 | fraction *new_fraction(long long k); // {a, 1} 10 | fraction *new_fraction(); // {0, 1} 11 | 12 | long long gcd(long long a, long long b); 13 | void simplify_fraction(fraction *f); 14 | 15 | void set_fraction(fraction *f, long long k, long long d); // {k, d} 16 | void set_fraction(fraction *f, long long k); // {k, 1} 17 | void print_fraction(fraction *f); 18 | 19 | void sum_fractions(fraction *a, fraction *b); // a += b 20 | void sum_fractions(fraction *x, fraction *a, fraction *b); // x = a + b 21 | void multiply_fractions(fraction *f, fraction *a, fraction *b); // f = a * b 22 | void sum_multiply_fractions(fraction *f, fraction *a, 23 | fraction *b); // f += a * b -------------------------------------------------------------------------------- /Semester_2/Lab_7/dop/main.cpp: -------------------------------------------------------------------------------- 1 | // Написать генератор псевдослучайных чисел по алгоритму 2 | // f(n) = f(n-1) + f(n-2) + f(n-3) mod 211 3 | // (начальные условия: f(0) = f(1) = f(2) = 1) 4 | // Подсчитать частоту каждого числа при выборке 100000 5 | 6 | // доп: центральная предельная теорема 7 | // с ее помощью получить нормальное распределение 8 | // полулучить Гауссовский колокол 9 | 10 | #include "rand.h" 11 | #define DOP 12 | 13 | #define ITER 100000 14 | #define WIDE 40 15 | 16 | // фактор сглаживания 17 | // чем больше, тем острее Гауссовский колокол 18 | #define DISTR_FACTOR 12 19 | 20 | int main() { 21 | int array[NUMS] = {0}; 22 | 23 | #ifndef DOP 24 | 25 | for (int i = 0; i < ITER; i++) array[gen()]++; 26 | printf("%-4s| %s\n----|-----\n", "num", "freq"); 27 | for (int i = 0; i < NUMS; i++) printf("%-4d| %d\n", i, array[i]); 28 | 29 | #else 30 | 31 | for (int i = 0; i < ITER; i++) array[gen_normal(DISTR_FACTOR)]++; 32 | pretty_print(array, NUMS, WIDE); 33 | 34 | #endif 35 | } -------------------------------------------------------------------------------- /Exam/Semester_1/n2_1.c: -------------------------------------------------------------------------------- 1 | void main() { 2 | // основные типы данных 3 | char a = -1; // 1 байт 4 | short b = -2; // 2 байта 5 | int c = -3; // 4 байта 6 | long d = -4; // 4 байта 7 | long long e = -5; // 8 байт 8 | 9 | unsigned char v = 6; // 1 байт без знака 10 | unsigned short w = 7; // 2 байта без знака 11 | unsigned int x = 8; // 4 байта без знака 12 | unsigned long y = 9; // 4 байта без знака 13 | unsigned long long z = 10; // 8 байт без знака 14 | 15 | float fl = 42.42; // 4 байта 16 | double db = 4242.42424242; // 8 байт 17 | 18 | // приведение типов данных 19 | char some_char = 42; 20 | int some_int = (int) some_char; 21 | 22 | some_int = 1234567; 23 | some_char = (char) some_int; // число обрежется до 8 младших битов 24 | 25 | int n = 3; 26 | int m = 5; 27 | double some_double_1 = n / m; // будет 0 так как мы делим intы 28 | double some_double_2 = ((double) n) / m; // теперь мы doube делим на int = double 29 | } -------------------------------------------------------------------------------- /Variants/Lab_7/var_12/main.cpp: -------------------------------------------------------------------------------- 1 | // Написать генератор псевдослучайных чисел, 2 | // равномерно распределенных на интервале [0., 3.5] (использовать rand()). 3 | // Подсчитать частоты попадания в каждый из интервалов длиной 0.1 при выборке 500000 4 | 5 | #include 6 | #include "frand.h" 7 | 8 | #define N 500000 // размер выборки (кол-во чисел) 9 | #define POWER 12 // коэффициент распределения 10 | // чем больше коэффициент - тем острее колокол 11 | #define INTERVALS 35 // количество интервалов 12 | 13 | int main() { 14 | rand_init(); 15 | // массив для каждого из интервалов 16 | int a[INTERVALS + 1] = {0}; 17 | 18 | // проходимся по всей выборке 19 | for (int i = 0; i < N; i++) { 20 | // генерируем случайное число 21 | double s = frand(3.5, POWER); 22 | // смотрим в какой интервал оно попало 23 | a[(int)(s * 10)] += 1; 24 | } 25 | 26 | // для каждого интервала выводим количество 27 | // чисел, попавших в него 28 | for (int i = 0; i < INTERVALS; i++) { 29 | printf("a[%d] = %d\n", i, a[i]); 30 | } 31 | } -------------------------------------------------------------------------------- /Exam/Semester_1/n6_1.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int global_var = 42; // глобальная переменная 4 | 5 | int sum(int a, int b) { 6 | int s = a + b; 7 | return s; 8 | } // переменная s определена только внутри функции sum 9 | 10 | void test_swap(int a, int b) { 11 | int temp = a; 12 | a = b; 13 | b = temp; 14 | } // это не сработает, тк. мы работаем с копиями переменных 15 | 16 | void swap(int* a, int* b) { 17 | int temp = *a; 18 | *a = *b; 19 | *b = temp; 20 | } // вот так работает правильно, мы передаем указатели 21 | 22 | void main() { 23 | // вот здесь переменная s не определена 24 | // s = 42; - приведет к ошибке 25 | int x = 42; 26 | int y = 618; 27 | 28 | int c = 0; 29 | c = sum(x, y); 30 | // c == 660 31 | 32 | test_swap(x, y); 33 | printf("%d %d\n", x, y); 34 | 35 | swap(&x, &y); 36 | printf("%d %d", x, y); 37 | } 38 | 39 | // бонус: функция swap без переменной temp 40 | // если вы читаете это за пару часов до экзамена то забейте 41 | void swap2(int* a, int* b) { 42 | *a += *b; *b = *a - *b; *a -= *b; 43 | } -------------------------------------------------------------------------------- /Semester_2/Lab_9/base/main.cpp: -------------------------------------------------------------------------------- 1 | // Ввести n и коэффициенты a1 - an 2 | // Вычислить и вывести коэффициенты многочлена 3 | // p(x) = (x - a1) * (x - a2) * ... * (x - an) 4 | // (написать функцию для умножения двух многочленов) 5 | 6 | #include 7 | #include 8 | 9 | #include "polynom.h" 10 | 11 | int main() { 12 | unsigned int n = 0; 13 | printf("Enter n (number of polynomial terms) = "); 14 | scanf("%u", &n); 15 | if (n < 1) { 16 | printf("n must be >= 1\n"); 17 | exit(1); 18 | } 19 | 20 | printf("Enter %d numbers: ", n); 21 | long long *arr = (long long *)malloc(n * sizeof(long long)); 22 | for (int i = 0; i < n; i++) scanf("%lld", &arr[i]); 23 | printf("\n"); 24 | print_koeffs(arr, n); 25 | 26 | polynom *p = new_binom(-arr[0]); 27 | if (n == 1) { 28 | print_polynom("\np(x) = ", p); 29 | exit(1); 30 | } 31 | 32 | polynom *p2 = new_binom(0); 33 | for (int i = 1; i < n; i++) { 34 | upd_binom(p2, -arr[i]); 35 | p = multiply(p, p2); 36 | } 37 | 38 | print_polynom("\np(x) = ", p); 39 | } -------------------------------------------------------------------------------- /Turlikov/Report_2/min_hamming/main.cpp: -------------------------------------------------------------------------------- 1 | #include "..\hamming.h" 2 | // #define DOP 3 | 4 | int min_hamming(uint64* arr, int size) { 5 | int minim = size; 6 | for (uint64 a = 0; a < size; a++) { 7 | for (uint64 b = a + 1; b < size; b++) { 8 | if (arr[a] != arr[b]) { 9 | int hamm = count_ones(arr[a] ^ arr[b]); 10 | minim = hamm < minim ? hamm : minim; 11 | } 12 | } 13 | } 14 | return minim; 15 | } 16 | 17 | int main() { 18 | printf( 19 | "min hamming distance: %d\n", 20 | min_hamming(code_table, 4) 21 | ); 22 | 23 | #ifdef DOP 24 | int max = 32; 25 | int count = 0; 26 | for (uint64 a = 0; a < max; a++) { 27 | for (uint64 b = a; b < max; b++) { 28 | if (a != b) { 29 | printf("\na: "); printf_bin(a); 30 | printf(" b: "); printf_bin(b); 31 | printf(" hamming: "); printf_bin(hamming(a, b)); 32 | printf(" dif: %d", hamming(a, b)); 33 | count += 1; 34 | } 35 | } 36 | } 37 | printf("\ncount: %d", count); 38 | #endif 39 | } -------------------------------------------------------------------------------- /Semester_2/Lab_14/dop/shape.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Point { 9 | public: 10 | double x, y; 11 | Point(double x = 0, double y = 0); 12 | friend ostream &operator<<(ostream &out, Point &p); 13 | }; 14 | 15 | class Shape { 16 | protected: 17 | Point pos; 18 | unsigned long id; 19 | 20 | public: 21 | Shape(Point pos = {0}); 22 | virtual void print(); 23 | unsigned long get_id(); 24 | unsigned long next_id(); 25 | virtual double get_contour_length(); 26 | bool operator==(Shape &s); 27 | }; 28 | 29 | class Circle : public Shape { 30 | protected: 31 | double r; 32 | string text; 33 | 34 | public: 35 | Circle(Point pos = {0}, double r = 0, string text = ""); 36 | virtual void print(); 37 | virtual double get_contour_length(); 38 | }; 39 | 40 | class Segment : public Shape { 41 | protected: 42 | Point start, end; 43 | 44 | public: 45 | Segment(Point start = {0}, Point end = {0}); 46 | virtual void print(); 47 | virtual double get_contour_length(); 48 | }; -------------------------------------------------------------------------------- /Turlikov/Report_2/report/n1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | typedef unsigned long long uint64; 4 | 5 | static uint64 A[] = {0x00, 0x0d, 0x16, 0x1f}; 6 | 7 | uint64 coder (uint64 m) { return A[m]; } 8 | uint64 channel (uint64 a, uint64 e) { return a ^ e; } 9 | uint64 hamming (uint64 a, uint64 b) { return count_ones(a ^ b); } 10 | 11 | uint64 count_ones(uint64 n) { 12 | uint64 w = 0; 13 | while (n > 0) { 14 | w += n & 1; 15 | n = n >> 1; 16 | } 17 | return w; 18 | } 19 | 20 | uint64 decoder(uint64 m) { 21 | uint64 ind = 0, min = 5; 22 | for (uint64 i = 0; i < 4; i++) { 23 | uint64 d = hamming(m, A[i]); 24 | if (d < min) { 25 | min = d; ind = i; 26 | } 27 | } 28 | return ind; 29 | } 30 | 31 | int main() { 32 | uint64 m, e, w, c, d; 33 | cin >> m >> e; 34 | w = coder(m); c = channel(w, e); d = decoder(c); 35 | cout << "m: " << m << endl; 36 | cout << "w: " << w << endl; 37 | cout << "e: " << e << endl; 38 | cout << "c: " << c << endl; 39 | cout << "d: " << d << endl; 40 | } 41 | 42 | 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /Semester_1/Lab_5/main.c: -------------------------------------------------------------------------------- 1 | // Ввести строку. Заменить знаки препинания на сокращения 2 | // ('.' - тчк, ',' - зпт, '?' - впр, ':' - дтч) 3 | 4 | #include 5 | #include 6 | #include "reducts.h" 7 | 8 | #define length(x) (sizeof(x) / sizeof((x)[0])) 9 | 10 | int len = 0; 11 | char *readstr() { 12 | len = 0; 13 | int capacity = 1; 14 | char *s = (char *)malloc(sizeof(char)); 15 | char c = getchar(); 16 | while (c != '\n') { 17 | s[(len)++] = c; 18 | if (len >= capacity) { 19 | capacity *= 2; 20 | s = (char *)realloc(s, capacity * sizeof(char)); 21 | } 22 | c = getchar(); 23 | } 24 | s[len] = '\0'; 25 | return s; 26 | } 27 | 28 | void main() { 29 | printf("Input string:\n"); 30 | char *str = readstr(); 31 | 32 | printf("\nString after replace:\n"); 33 | for (int i = 0; i < len; i++) { 34 | int flag = 1; 35 | for (int c = 0; c < W_COUNT; c++) { 36 | if (str[i] == punct[c]) { 37 | printf("%s", words[c]); 38 | flag = 0; 39 | } 40 | } 41 | if (flag) printf("%c", str[i]); 42 | } 43 | free(str); 44 | } -------------------------------------------------------------------------------- /Turlikov/Report_2/hamming_decoder/main.cpp: -------------------------------------------------------------------------------- 1 | #include "..\hamming.h" 2 | #define DEBUG 3 | 4 | int main() { 5 | uint8 arr[2][6] = {0}; 6 | 7 | for (uint8 n = 1; n < 6; n++) { 8 | printf("\nerrors count: %d\n", n); 9 | for (uint8 e = 0; e < 32; e++) { 10 | if (count_ones(e) == n) { 11 | uint8 temp = 0; 12 | for (uint8 m = 0; m < 4; m++) { 13 | temp += (m == decoder(channel(coder(m), e))); 14 | #ifdef DEBUG 15 | printf(" mess: "); printf_bin(m); 16 | printf(" code: "); printf_bin(coder(m)); 17 | printf(" err: "); printf_bin(e); 18 | printf(" chann: "); printf_bin(channel(coder(m), e)); 19 | printf(" dec: "); printf_bin(decoder(channel(coder(m), e))); 20 | if (m == decoder(channel(coder(m), e))) printf(" [WOW]"); 21 | printf("\n"); 22 | #endif 23 | } 24 | arr[0][n - 1] += (temp == 4); 25 | arr[1][n - 1] += 1; 26 | } 27 | } 28 | } 29 | 30 | printf("\n"); 31 | for (uint8 N = 1; N < 6; N++) 32 | printf("%d error(s): fixed %d / %d\n", N, arr[0][N - 1], arr[1][N - 1]); 33 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Denis Churilov 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Variants/Lab_5/var_11/main.c: -------------------------------------------------------------------------------- 1 | // Ввести строку и слово. 2 | // Вывести только те слова, начало которых совпадает с введенным словом. 3 | 4 | // Последовательно выделять слова из входной строки и формировать из них массив строк. 5 | // Допущений о максимальном количестве слов, максимальной длине одного слова делать нельзя. 6 | 7 | #include 8 | #include 9 | 10 | #define length(x) (sizeof(x) / sizeof((x)[0])) 11 | 12 | int len = 0; 13 | char *readstr() { 14 | len = 0; 15 | int capacity = 1; 16 | char *s = (char *)malloc(sizeof(char)); 17 | char c = getchar(); 18 | while (c != '\n') { 19 | s[(len)++] = c; 20 | if (len >= capacity) { 21 | capacity *= 2; 22 | s = (char *)realloc(s, capacity * sizeof(char)); 23 | } 24 | c = getchar(); 25 | } 26 | s[len] = '\0'; 27 | return s; 28 | } 29 | 30 | 31 | void main() { 32 | printf("Input string:\n"); 33 | char *str = readstr(); 34 | 35 | 36 | 37 | 38 | 39 | printf("\nStr:\n"); 40 | for (int i = 0; i < len; i++) {} 41 | 42 | printf("%s", str); 43 | free(str); 44 | } 45 | 46 | // hello world potato world test world world lol kek world rule the world test -------------------------------------------------------------------------------- /Semester_3/Lab_18/base/cache.h: -------------------------------------------------------------------------------- 1 | // Реализовать LFU кэш фиксированного размера (количество записей задается в 2 | // конструкторе) для адресов (адресом является строка, например, “AFFB”). 3 | // Согласно алгоритму LFU после исчерпания размера кэша в начале удаляются 4 | // записи, которые запрашивались реже всего. Удобной реализацией такого кэша 5 | // является map<адрес, число запросов адреса>. При реализации использовать 6 | // дополнительный multimap или priority_queue (т.е. всего 2 map) для быстрого 7 | // поиска адреса, который встречался наименьшее число раз. 8 | 9 | // методы: 10 | // LfuCache(size_t size) 11 | // bool find_and_add(const std::string &address); // возвращает true, если адрес 12 | // найден в кэше operator<< - для вывода на экран 13 | 14 | #pragma once 15 | 16 | #include 17 | #include 18 | #include 19 | #include 20 | 21 | class LfuCache { 22 | private: 23 | std::map cache; 24 | std::multimap freq; 25 | size_t size; 26 | 27 | public: 28 | LfuCache(size_t size); 29 | bool find_and_add(const std::string &address); 30 | friend std::ostream &operator<<(std::ostream &out, const LfuCache &cache); 31 | }; -------------------------------------------------------------------------------- /Semester_2/Lab_10/base/file.cpp: -------------------------------------------------------------------------------- 1 | #include "file.h" 2 | 3 | #include 4 | 5 | // форматируем файл с отступами 6 | void parse_file(const char *in, const char *out, int start, int end) { 7 | FILE *input = fopen(in, "rt"); 8 | FILE *output = fopen(out, "w"); 9 | if (input == NULL) return; 10 | 11 | int counter = 1; 12 | char c = fgetc(input); 13 | while (c != EOF) { 14 | while (counter < start) { 15 | fprintf(output, " "); 16 | counter++; 17 | } 18 | 19 | while (counter == start && c == ' ') c = fgetc(input); 20 | 21 | if (counter <= end) { 22 | fprintf(output, "%c", c); 23 | c = fgetc(input); 24 | counter++; 25 | } else { 26 | fprintf(output, "\n"); 27 | counter = 1; 28 | } 29 | } 30 | 31 | fclose(input); 32 | fclose(output); 33 | } 34 | 35 | // выводим файл 36 | void print_file(const char *path) { 37 | FILE *file = fopen(path, "rt"); 38 | if (file == NULL) { 39 | printf("failed to open file\n"); 40 | return; 41 | } 42 | 43 | printf("\n"); 44 | char c = fgetc(file); 45 | while (c != EOF) { 46 | printf("%c", c); 47 | c = fgetc(file); 48 | } 49 | 50 | printf("\n"); 51 | fclose(file); 52 | } -------------------------------------------------------------------------------- /Test/Meme/pointers.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void main () { 4 | int ptr = 42; 5 | int *ptrr = &ptr; 6 | int **ptrrr = &ptrr; 7 | int ***ptrrrr = &ptrrr; 8 | int ****ptrrrrr = &ptrrrr; 9 | int *****ptrrrrrr = &ptrrrrr; 10 | int ******ptrrrrrrr = &ptrrrrrr; 11 | int *******ptrrrrrrrr = &ptrrrrrrr; 12 | int ********ptrrrrrrrrr = &ptrrrrrrrr; 13 | int *********ptrrrrrrrrrr = &ptrrrrrrrrr; 14 | int **********ptrrrrrrrrrrr = &ptrrrrrrrrrr; 15 | int ***********ptrrrrrrrrrrrr = &ptrrrrrrrrrrr; 16 | int ************ptrrrrrrrrrrrrr = &ptrrrrrrrrrrrr; 17 | int *************ptrrrrrrrrrrrrrr = &ptrrrrrrrrrrrrr; 18 | int **************ptrrrrrrrrrrrrrrr = &ptrrrrrrrrrrrrrr; 19 | int ***************ptrrrrrrrrrrrrrrrr = &ptrrrrrrrrrrrrrrr; 20 | int ****************ptrrrrrrrrrrrrrrrrr = &ptrrrrrrrrrrrrrrrr; 21 | int *****************ptrrrrrrrrrrrrrrrrrr = &ptrrrrrrrrrrrrrrrrr; 22 | int ******************ptrrrrrrrrrrrrrrrrrrr = &ptrrrrrrrrrrrrrrrrrr; 23 | int *******************ptrrrrrrrrrrrrrrrrrrrr = &ptrrrrrrrrrrrrrrrrrrr; 24 | int ********************ptrrrrrrrrrrrrrrrrrrrrr = &ptrrrrrrrrrrrrrrrrrrrr; 25 | 26 | printf("Answer is: %d", ********************ptrrrrrrrrrrrrrrrrrrrrr); 27 | } -------------------------------------------------------------------------------- /Variants/Lab_9/var_12/main.cpp: -------------------------------------------------------------------------------- 1 | // Ввести целое число N. Вывести число, 2 | // полученное из введенного инверсией каждого 3 | // 4-го двоичного разряда (начиная с младших) 4 | 5 | // доп: определить, каждый какой бит инвертирован 6 | 7 | #include "lab.h" 8 | #define DOP 9 | 10 | #ifdef DOP 11 | 12 | int main() { 13 | // вводим сдвиг для инвертирования 14 | unsigned int offset; 15 | printf("offset: "); 16 | scanf("%u", &offset); 17 | 18 | // вводим исходное число 19 | unsigned int in; 20 | printf("input: "); 21 | scanf("%u", &in); 22 | printf("bin: "); 23 | print_bin(in); 24 | printf("\n\n"); 25 | 26 | // инвертируем биты числа 27 | unsigned int out = invert_every_nth(in, offset); 28 | printf("output: %u\nbin: ", out); 29 | print_bin(out); 30 | printf("\n\n"); 31 | 32 | // определяем разницу и сдвиг 33 | printf("dif: "); 34 | print_bin(in ^ out); 35 | printf("\noffset: %d\n", get_invert_offset(in, out)); 36 | } 37 | 38 | #else 39 | 40 | int main() { 41 | // вводим исходное число 42 | unsigned int N; 43 | scanf("%u", &N); 44 | 45 | // инвертируем каждый 4-й бит 46 | printf("%u", invert_4(N)); 47 | } 48 | 49 | #endif -------------------------------------------------------------------------------- /Semester_2/Lab_14/base/shape.cpp: -------------------------------------------------------------------------------- 1 | #include "shape.h" 2 | 3 | using namespace std; 4 | 5 | // class Point 6 | 7 | Point::Point(double x, double y) : x(x), y(y) {} 8 | 9 | ostream &operator<<(ostream &out, Point &p) { 10 | out << "(" << p.x << ", " << p.y << ")"; 11 | return out; 12 | } 13 | 14 | // class Shape 15 | 16 | Shape::Shape(Point pos) : id(next_id()), pos(pos) {} 17 | 18 | unsigned long Shape::next_id() { 19 | static unsigned long next_id = 0; 20 | return next_id++; 21 | } 22 | 23 | void Shape::print() { 24 | cout << "id: " << id << endl; 25 | cout << "pos: " << pos << endl; 26 | } 27 | 28 | unsigned long Shape::get_id() { return id; } 29 | 30 | // class Circle 31 | 32 | Circle::Circle(Point pos, double r, string text) 33 | : Shape(pos), r(r), text(text) {} 34 | 35 | void Circle::print() { 36 | cout << "type: Circle" << endl; 37 | Shape::print(); 38 | cout << "radius: " << r << endl; 39 | cout << "text: " << text << endl; 40 | } 41 | 42 | // class Segment 43 | 44 | Segment::Segment(Point start, Point end) 45 | : Shape(start), start(start), end(end) {} 46 | 47 | void Segment::print() { 48 | cout << "type: Segment" << endl; 49 | Shape::print(); 50 | cout << "start pos: " << start << endl; 51 | cout << "end pos: " << end << endl; 52 | } 53 | -------------------------------------------------------------------------------- /Variants/Lab_18/var_1/main.cpp: -------------------------------------------------------------------------------- 1 | // Реализовать записную книжку с поиском по телефону и по имени 2 | // Данные необходимо загружать из текстового файла 3 | 4 | // функции: 5 | // Notebook(const std::string& filename) - конструктор из файла 6 | // add(const std::string &name, unsigned phone) 7 | // erase(const std::string &name) 8 | // std::string& find(unsigned phone) 9 | // unsigned find(const std:string& name) 10 | // operator<< для вывода на экран 11 | // load(const std::string& filename) 12 | // save(const std::string& filename) 13 | 14 | // написать программу для тестирования функций класса 15 | 16 | #include 17 | #include 18 | 19 | #include "notebook.hpp" 20 | 21 | using namespace std; 22 | 23 | int main() { 24 | Notebook nb; 25 | 26 | try { 27 | nb.load("notebook.txt"); 28 | } catch (std::runtime_error& e) { 29 | cout << e.what() << endl; 30 | cout << "Creating new notebook:" << endl; 31 | nb.add("Ivan", 123456); 32 | nb.add("Petr", 654321); 33 | nb.add("Oleg", 214365); 34 | nb.add("Vlad", 987654); 35 | } 36 | 37 | cout << nb << endl; 38 | nb.save("notebook.txt"); 39 | 40 | nb.erase("Ivan"); 41 | cout << nb << endl; 42 | cout << nb.find(654321) << endl; 43 | cout << nb.find("Petr") << endl; 44 | return 0; 45 | } -------------------------------------------------------------------------------- /Semester_3/Lab_18/dop/main.cpp: -------------------------------------------------------------------------------- 1 | // Реализовать LFU кэш фиксированного размера (количество записей задается в 2 | // конструкторе) для адресов (адресом является строка, например, “AFFB”). 3 | // Согласно алгоритму LFU после исчерпания размера кэша в начале удаляются 4 | // записи, которые запрашивались реже всего. Удобной реализацией такого кэша 5 | // является map<адрес, число запросов адреса>. При реализации использовать 6 | // дополнительный multimap или priority_queue (т.е. всего 2 map) для быстрого 7 | // поиска адреса, который встречался наименьшее число раз. 8 | 9 | // написать тестирующую программу 10 | 11 | // доп: линкед лист со всеми словами для перевода, 12 | // текст переводится с помощью этих слов, слово сначала ищем в кеше а потом 13 | 14 | #include 15 | #include 16 | #include 17 | 18 | #include "translate.h" 19 | 20 | #define CACHE_SIZE 32 21 | 22 | using namespace std; 23 | 24 | int main() { 25 | Translate Trans("words.json", CACHE_SIZE); 26 | Trans.print_words(); 27 | cout << endl << "Start translation:" << endl; 28 | 29 | ifstream fin("input.txt"); 30 | string word; 31 | while (fin >> word) { 32 | cout << Trans.translate(word) << " "; 33 | } 34 | 35 | cout << endl << endl; 36 | Trans.print_cache(); 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /Semester_2/Lab_12/dop/main.cpp: -------------------------------------------------------------------------------- 1 | // Создайте класс HugeInt, который хранит в 40-элементном 2 | // массиве цифр целые числа разрядностью до 40 знаков 3 | // Разрядность указать в конструкторе 4 | 5 | // TODO: 6 | // Предусмотреть функции + - == < <= > >= и проверки на 0 7 | // Используйте приватные поля для данных 8 | // определите конструктор, который должен содержать значения по умолчанию 9 | // напишите методы установки и извлечения значений (set, get) 10 | // выполнения операций ввода и вывода значения объекта созданного класса 11 | // Напишите конструктор копий, оператор присваивания, деструктор 12 | // Напишите программу для тестирования вашего класса 13 | 14 | // доп: перегрузить операторы считывания и записи длинного числа 15 | // из текстового файла и в текстовый файл 16 | 17 | #include "HugeInt.h" 18 | 19 | using namespace std; 20 | 21 | int main() { 22 | ifstream input("input.txt"); 23 | 24 | HugeInt test(42); 25 | cout << "init 42: " << test << endl; 26 | 27 | input >> test; 28 | cout << "from file: " << test << endl; 29 | 30 | HugeInt test2; 31 | input >> test2; 32 | cout << "from file: " << test2 << endl; 33 | 34 | input.close(); 35 | 36 | ofstream output("output.txt"); 37 | output << test; 38 | output << endl << test2; 39 | 40 | output.close(); 41 | } 42 | -------------------------------------------------------------------------------- /Semester_2/Lab_10/dop/file.cpp: -------------------------------------------------------------------------------- 1 | #include "file.h" 2 | 3 | #include 4 | 5 | // форматируем файл с отступами 6 | void parse_file(const char *in, const char *out, int start, int end, 7 | bool no_whitespace) { 8 | FILE *input = fopen(in, "rt"); 9 | FILE *output = fopen(out, "w"); 10 | if (input == NULL) return; 11 | 12 | int counter = 1; 13 | char c = fgetc(input); 14 | while (c != EOF) { 15 | while (counter < start) { 16 | fprintf(output, " "); 17 | counter++; 18 | } 19 | 20 | while (counter == start && c == ' ') c = fgetc(input); 21 | 22 | if (counter <= end) { 23 | fprintf(output, "%c", c); 24 | do { 25 | c = fgetc(input); 26 | } while ((c == ' ' || c == '\t') && no_whitespace); 27 | counter++; 28 | } else { 29 | fprintf(output, "\n"); 30 | counter = 1; 31 | } 32 | } 33 | 34 | fclose(input); 35 | fclose(output); 36 | } 37 | 38 | // выводим файл 39 | void print_file(const char *path) { 40 | FILE *file = fopen(path, "rt"); 41 | if (file == NULL) { 42 | printf("failed to open file\n"); 43 | return; 44 | } 45 | 46 | printf("\n"); 47 | char c = fgetc(file); 48 | while (c != EOF) { 49 | printf("%c", c); 50 | c = fgetc(file); 51 | } 52 | 53 | printf("\n"); 54 | fclose(file); 55 | } -------------------------------------------------------------------------------- /Semester_2/Lab_9/dop/main.cpp: -------------------------------------------------------------------------------- 1 | // Ввести n и коэффициенты a1 - an 2 | // Вычислить и вывести коэффициенты многочлена 3 | // p(x) = (x - a1) * (x - a2) * ... * (x - an) 4 | // (написать функцию для умножения двух многочленов) 5 | 6 | // доп: нахождение k-той первообразной полученного полинома 7 | 8 | #include 9 | #include 10 | 11 | #include "polynom.h" 12 | 13 | int main() { 14 | unsigned int n = 0; 15 | printf("Enter n (number of polynomial terms) = "); 16 | scanf("%u", &n); 17 | if (n < 1) { 18 | printf("n must be >= 1\n"); 19 | exit(1); 20 | } 21 | 22 | printf("Enter %d numbers: ", n); 23 | long long *arr = (long long *)malloc(n * sizeof(long long)); 24 | for (int i = 0; i < n; i++) scanf("%lld", &arr[i]); 25 | printf("\n"); 26 | print_koeffs(arr, n); 27 | 28 | polynom *p = new_binom(-arr[0]); 29 | if (n == 1) { 30 | print_polynom("\np(x) = ", p); 31 | exit(1); 32 | } 33 | 34 | polynom *p2 = new_binom(0); 35 | for (int i = 1; i < n; i++) { 36 | upd_binom(p2, -arr[i]); 37 | p = multiply(p, p2); 38 | } 39 | 40 | print_polynom("\np(x) = ", p); 41 | 42 | printf("\nEnter d (integral degree) = "); 43 | scanf("%u", &n); 44 | if (!n) printf("d must be >= 0\n"); 45 | for (int i = 0; i < n; i++) integral(p, p); // p = ∫ p 46 | print_polynom("\ni(p) = ", p); 47 | } -------------------------------------------------------------------------------- /Semester_3/Lab_18/dop/cache.cpp: -------------------------------------------------------------------------------- 1 | #include "cache.h" 2 | 3 | using namespace std; 4 | 5 | LfuCache::LfuCache(size_t size) : size(size) {} 6 | 7 | string LfuCache::get(const string &str) { 8 | // if str is in cache, return value 9 | // else return empty string 10 | // if str is in cache, increase count 11 | auto it = cache.find(str); 12 | if (it != cache.end()) { 13 | auto it2 = freq.find(it->second.second); 14 | while (it2->second != str) it2++; // search for str in freq 15 | freq.erase(it2); 16 | freq.insert({++it->second.second, str}); 17 | return it->second.first; 18 | } 19 | return ""; 20 | } 21 | 22 | void LfuCache::add(const string &address, const string &value) { 23 | // add address to cache 24 | // if cache is full, delete least frequently used address 25 | if (cache.size() == size) { 26 | auto it2 = freq.begin(); 27 | cache.erase(it2->second); 28 | freq.erase(it2); 29 | } 30 | cache.insert({address, {value, 1}}); 31 | freq.insert({1, address}); 32 | } 33 | 34 | ostream &operator<<(ostream &out, const LfuCache &cache) { 35 | cout << "Freq:" << endl; 36 | for (auto it = cache.freq.begin(); it != cache.freq.end(); ++it) { 37 | out << it->second << " - " << it->first << " " << endl; 38 | } 39 | return out; 40 | } 41 | 42 | void LfuCache::print() { cout << *this << endl; } -------------------------------------------------------------------------------- /Variants/Lab_10/var_7/main.cpp: -------------------------------------------------------------------------------- 1 | // По символьным файлам с текстом (содержащим сокращения) 2 | // и с сокращениями создать новый файл, 3 | // где все сокращения заменены на соответствующие слова 4 | 5 | // файл с сокращениями имеет следующий формат: 6 | // в каждой строке по 2 слова, разделенных пробелом. 7 | // Cлова записываются в трехмерный массив символов 8 | // [["", ""], 9 | // ["", ""], 10 | // ["", ""]] 11 | 12 | #include "abbrev.h" 13 | 14 | int main() { 15 | FILE *input = fopen("input.txt", "r"); 16 | if (input == NULL) 17 | perror("Error opening file"); 18 | 19 | char *text = read_file(input); 20 | int text_len = strlen(text); 21 | fclose(input); 22 | 23 | FILE *abbrev = fopen("abbrev.txt", "r"); 24 | if (abbrev == NULL) 25 | perror("Error opening file"); 26 | 27 | int lines = get_lines(abbrev); 28 | char *** abbrevs = read_word_pairs(abbrev); 29 | fclose(abbrev); 30 | 31 | FILE *output = fopen("output.txt", "w"); 32 | if (output == NULL) 33 | perror("Error opening file"); 34 | 35 | for (int i = 0; text[i]; i++) { 36 | int a = find_substr(text + i, abbrevs, lines); 37 | if (a != -1) { 38 | fprintf(output, "%s", abbrevs[a][1]); 39 | i += strlen(abbrevs[a][0]) - 1; 40 | } else { 41 | fprintf(output, "%c", text[i]); 42 | } 43 | } 44 | 45 | fclose(output); 46 | } -------------------------------------------------------------------------------- /Turlikov/Report_2/report/n3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define FREE 0 4 | #define BAD 1 5 | #define USED 2 6 | 7 | typedef unsigned long long uint64; 8 | 9 | unsigned char count_ones(uint64 n) { 10 | unsigned char w = 0; 11 | while (n > 0) { 12 | w += n & 1; 13 | n = n >> 1; 14 | } 15 | return w; 16 | } 17 | 18 | bool has_free(uint64 *arr, int size) { 19 | for (uint64 i = 0; i < size; i++) 20 | if (arr[i] == FREE) return true; 21 | return false; 22 | } 23 | 24 | void printf_bin(uint64 n) { 25 | for (uint64 i = 0; i < 64; i++) 26 | printf("%d", (n >> (63 - i)) & 1); 27 | } 28 | 29 | int main() { 30 | uint64 n = 5, d = 3; 31 | uint64 size = 1 << n; 32 | uint64 next_free, count = 0; 33 | uint64 *marks = new uint64[size]; 34 | uint64 *table = new uint64[size]; 35 | for (uint64 i = 0; i < size; i++) marks[i] = table[i] = FREE; 36 | 37 | while (has_free(marks, size)) { 38 | for (next_free = 0; marks[next_free] != FREE; next_free++); 39 | table[count] = next_free; 40 | marks[table[count++]] = USED; 41 | 42 | for (uint64 i = 0; i < size; i++) 43 | if (marks[i] == FREE && count_ones(i ^ table[count - 1]) < d) 44 | marks[i] = BAD; 45 | } 46 | 47 | printf("code table:\n"); 48 | for (uint64 i = 0; i < count; i++){ 49 | printf_bin(table[i]); 50 | printf(" - %d\n",table[i]); 51 | } 52 | } 53 | 54 | 55 | -------------------------------------------------------------------------------- /Turlikov/Report_1/combinations/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #define VERSION 2 5 | // 0 - old version 6 | // 1 - new version 7 | // 2 - optimal solution 8 | 9 | #if VERSION == 0 10 | 11 | #include "binom_v0.h" 12 | 13 | int main() { 14 | for (int i = 0; i <= 8; i++) 15 | cout << c(8, i) << endl; 16 | } 17 | 18 | #elif VERSION == 1 19 | 20 | #include "binom_v1.h" 21 | 22 | int main() { 23 | cout << "c(9, 7) = " << c(9, 7) << endl; // 36 24 | cout << "c(6, 3) = " << c(6, 3) << endl; // 20 25 | cout << "c(10, 5) = " << c(10, 5) << endl; // 252 26 | cout << "c(0, 7) = " << c(0, 7) << endl; // 0 27 | cout << "c(0, 0) = " << c(0, 0) << endl; // 0 28 | cout << "c(9, 1) = " << c(9, 1) << endl; // 9 29 | cout << "c(7, 6) = " << c(7, 6) << endl; // 7 30 | cout << "c(18, 6) = " << c(18, 6) << endl; // 18564 31 | } 32 | 33 | #elif VERSION == 2 34 | 35 | #include "binom_optimal.h" 36 | 37 | int main() { 38 | uint64_t arr[5][3] = { 39 | {60, 30, 118264581564861424}, 40 | {61, 8, 2944827765}, 41 | {42, 21, 538257874440}, 42 | {65, 32, 3609714217008132870}, 43 | {99, 99, 1} 44 | }; 45 | 46 | for (int i = 0; i < 5; i++) 47 | cout << c(arr[i][0], arr[i][1]) << " = " << arr[i][2] << endl; 48 | } 49 | 50 | #else 51 | 52 | #error "incorrect version" 53 | 54 | #endif -------------------------------------------------------------------------------- /Exam/Semester_2/task_3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | class Vector { 6 | private: 7 | int *arr; 8 | size_t size; 9 | 10 | public: 11 | Vector(size_t size); 12 | Vector(Vector& v); 13 | ~Vector(); 14 | Vector& operator=(Vector& v); 15 | Vector& set(size_t index, int value); 16 | void print(); 17 | }; 18 | 19 | Vector::Vector(size_t size) { 20 | this->size = size; 21 | arr = new int[size]; 22 | } 23 | 24 | Vector::Vector(Vector& v) { 25 | this->size = v.size; 26 | arr = new int[size]; 27 | memcpy(arr, v.arr, sizeof(int) * size); 28 | } 29 | 30 | Vector& Vector::operator=(Vector& v) { 31 | if (&v == this) return *this; // присваивание самому себе 32 | this->size = v.size; 33 | delete[] arr; 34 | arr = new int[size]; 35 | memcpy(arr, v.arr, sizeof(int) * size); 36 | return *this; 37 | } 38 | 39 | Vector::~Vector() { 40 | delete[] arr; 41 | } 42 | 43 | Vector& Vector::set(size_t index, int value) { 44 | arr[index] = value; 45 | return *this; 46 | } 47 | 48 | void Vector::print() { 49 | for (size_t i = 0; i < size; i++) 50 | std::cout << arr[i] << " "; 51 | cout << endl; 52 | } 53 | 54 | int main() { 55 | Vector a(4); 56 | a.set(0, 0).set(1, 1).set(2, 42).set(3, 618).print(); 57 | 58 | Vector b(a); 59 | b.print(); 60 | 61 | a.set(0, 777).print(); 62 | b.print(); 63 | 64 | b = a; 65 | b.print(); 66 | } -------------------------------------------------------------------------------- /Variants/Lab_18/var_2/main.cpp: -------------------------------------------------------------------------------- 1 | // Реализовать базу данных о людях. Человек (вспомогательный класс Person) 2 | // описывается следующими полями: имя, фамилия, год рождения, пол, номер 3 | // паспорта. Рекомендуется перегрузить для класса Person оператор сравнения 4 | 5 | // load(const std::string& filename) 6 | // save(const std::string& filename) 7 | // operator<< для вывода на экран 8 | // add(const Person& p) 9 | // erase(const Person& p) 10 | 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | #include "database.h" 17 | 18 | using namespace std; 19 | 20 | int main(int argc, char const *argv[]) { 21 | Database db; 22 | db.add(Person("Rayan", "Gosling", 1980, 0, 420069)); 23 | db.add(Person("Angelina", "Jolie", 1975, 1, 420070)); 24 | db.add(Person("Bread", "Pitt", 1963, 0, 420071)); 25 | db.add(Person("Leonardo", "DiCaprio", 1974, 0, 420072)); 26 | db.add(Person("Scarlett", "Johansson", 1984, 1, 420073)); 27 | db.add(Person("Tom", "Cruise", 1962, 0, 420074)); 28 | db.add(Person("Jennifer", "Lawrence", 1990, 1, 420075)); 29 | db.add(Person("Emma", "Watson", 1990, 1, 420076)); 30 | cout << db << endl; 31 | 32 | cout << "After erase" << endl; 33 | db.erase(Person("Bread", "Pitt", 1963, 0, 420071)); 34 | cout << db << endl; 35 | 36 | cout << "After add" << endl; 37 | db.add(Person("Andrey", "Kruk", 1963, 1, 666)); 38 | cout << db; 39 | 40 | db.save("db.txt"); 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /Semester_3/Lab_18/base/main.cpp: -------------------------------------------------------------------------------- 1 | // Реализовать LFU кэш фиксированного размера (количество записей задается в 2 | // конструкторе) для адресов (адресом является строка, например, “AFFB”). 3 | // Согласно алгоритму LFU после исчерпания размера кэша в начале удаляются 4 | // записи, которые запрашивались реже всего. Удобной реализацией такого кэша 5 | // является map<адрес, число запросов адреса>. При реализации использовать 6 | // дополнительный multimap или priority_queue (т.е. всего 2 map) для быстрого 7 | // поиска адреса, который встречался наименьшее число раз. 8 | 9 | // написать тестирующую программу 10 | 11 | #include 12 | #include 13 | 14 | #include "cache.h" 15 | 16 | using namespace std; 17 | 18 | int main() { 19 | LfuCache cache(3); 20 | 21 | cout << "Try found AFFB: " 22 | << (cache.find_and_add("AFFB") ? "found" : "not found") << endl 23 | << "Cache: " << cache << endl; 24 | cout << "Try found AFFB: " 25 | << (cache.find_and_add("AFFB") ? "found" : "not found") << endl 26 | << "Cache: " << cache << endl; 27 | cout << "Try found AFF: " 28 | << (cache.find_and_add("AFF") ? "found" : "not found") << endl 29 | << "Cache: " << cache << endl; 30 | cout << "Try found AFB: " 31 | << (cache.find_and_add("AFB") ? "found" : "not found") << endl 32 | << "Cache: " << cache << endl; 33 | cout << "Try found AFB123: " 34 | << (cache.find_and_add("AFB123") ? "found" : "not found") << endl 35 | << "Cache: " << cache << endl; 36 | } 37 | -------------------------------------------------------------------------------- /Turlikov/Report_1/count_ones/v_long_array.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | // алгоритм нахождения количества единиц в двоичной записи числа 4 | // сложность: O(1), но используется много памяти на массив 5 | // (n & 255 - логическое умножение на маску 0b11111111) 6 | 7 | char arr[256] = {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 8 | 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 9 | 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 10 | 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 11 | 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 12 | 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 13 | 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 14 | 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 15 | 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 16 | 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 17 | 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 18 | 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 19 | 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 20 | 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 21 | 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 22 | 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8}; 23 | 24 | unsigned char count_ones (unsigned long long n) { 25 | unsigned char w = 0; 26 | while (n > 0) { 27 | w += arr[n & 255]; 28 | n = n >> 8; 29 | } 30 | return w; 31 | } 32 | -------------------------------------------------------------------------------- /Turlikov/Report_2/optimal_table/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define DEBUG 5 | 6 | #define FREE 0 7 | #define BAD 1 8 | #define USED 2 9 | 10 | typedef unsigned long long uint64; 11 | 12 | #ifdef DEBUG 13 | void debug(uint64 *arr, int size) { 14 | printf("[ "); 15 | for (uint64 i = 0; i < size; i++) 16 | printf("%d ", arr[i]); 17 | printf("]\n"); 18 | } 19 | #endif 20 | 21 | unsigned char count_ones(uint64 n) { 22 | unsigned char w = 0; 23 | while (n > 0) { 24 | w += n & 1; 25 | n = n >> 1; 26 | } 27 | return w; 28 | } 29 | 30 | bool has_free(uint64 *arr, int size) { 31 | for (uint64 i = 0; i < size; i++) 32 | if (arr[i] == FREE) return true; 33 | return false; 34 | } 35 | 36 | int main() { 37 | uint64 n = 5, d = 3; 38 | uint64 size = pow(2, n); 39 | uint64 next_free, count = 0; 40 | 41 | uint64 *marks = new uint64[size]; 42 | uint64 *table = new uint64[size]; 43 | for (uint64 i = 0; i < size; i++) 44 | marks[i] = table[i] = FREE; 45 | 46 | while (has_free(marks, size)) { 47 | for (next_free = 0; marks[next_free] != FREE; next_free++); 48 | table[count] = next_free; 49 | marks[table[count++]] = USED; 50 | 51 | for (uint64 i = 0; i < size; i++) 52 | if (marks[i] == FREE && count_ones(i ^ table[count - 1]) < d) 53 | marks[i] = BAD; 54 | 55 | #ifdef DEBUG 56 | debug(marks, size); 57 | #endif 58 | } 59 | 60 | printf("code table: "); 61 | for (uint64 i = 0; i < count; i++) 62 | printf("%d ", table[i]); 63 | } -------------------------------------------------------------------------------- /.github/workflows/cmake.yml: -------------------------------------------------------------------------------- 1 | name: CMake 2 | 3 | on: 4 | push: 5 | branches: [ "main" ] 6 | pull_request: 7 | branches: [ "main" ] 8 | 9 | env: 10 | # Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.) 11 | BUILD_TYPE: Release 12 | 13 | jobs: 14 | build: 15 | # The CMake configure and build commands are platform agnostic and should work equally well on Windows or Mac. 16 | # You can convert this to a matrix build if you need cross-platform coverage. 17 | # See: https://docs.github.com/en/free-pro-team@latest/actions/learn-github-actions/managing-complex-workflows#using-a-build-matrix 18 | runs-on: ubuntu-latest 19 | 20 | steps: 21 | - uses: actions/checkout@v3 22 | 23 | - name: Configure CMake 24 | # Configure CMake in a 'build' subdirectory. `CMAKE_BUILD_TYPE` is only required if you are using a single-configuration generator such as make. 25 | # See https://cmake.org/cmake/help/latest/variable/CMAKE_BUILD_TYPE.html?highlight=cmake_build_type 26 | run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} 27 | 28 | - name: Build 29 | # Build your program with the given configuration 30 | run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} 31 | 32 | - name: Test 33 | working-directory: ${{github.workspace}}/build 34 | # Execute tests defined by the CMake configuration. 35 | # See https://cmake.org/cmake/help/latest/manual/ctest.1.html for more detail 36 | run: ctest -C ${{env.BUILD_TYPE}} 37 | 38 | -------------------------------------------------------------------------------- /Semester_1/Lab_5/dop.c: -------------------------------------------------------------------------------- 1 | // Ввести строку. Заменить знаки препинания на сокращения 2 | // ('.' - тчк, ',' - зпт, '?' - впр, ':' - дтч) 3 | 4 | // доп: обратная задача, заменить сокращения на символы 5 | // * учитывать любой регистр 6 | 7 | #include 8 | #include 9 | 10 | #include "reducts.h" 11 | 12 | char lower(int c) { return c > 64 && c < 91 ? c + 32 : c; } 13 | 14 | int len = 0; 15 | char *readstr() { 16 | len = 0; 17 | int capacity = 1; 18 | char *s = (char *)malloc(sizeof(char)); 19 | char c = getchar(); 20 | while (c != '\n') { 21 | s[(len)++] = c; 22 | if (len >= capacity) { 23 | capacity *= 2; 24 | s = (char *)realloc(s, capacity * sizeof(char)); 25 | } 26 | c = getchar(); 27 | } 28 | s[len] = '\0'; 29 | return s; 30 | } 31 | 32 | int lenght(const char *s) { 33 | int count = 0; 34 | while (*s++ != '\0') count++; 35 | return count; 36 | } 37 | 38 | void main() { 39 | printf("Input string:\n"); 40 | char *str = readstr(); 41 | 42 | printf("\nString after replace:\n"); 43 | 44 | for (int i = 0; i < len; i++) { 45 | int ch_flag = 1; 46 | for (int w = 0; w < W_COUNT; w++) { 47 | int flag = 0; 48 | for (int c = 0; c < lenght(words[w]); c++) { 49 | if (lower(str[i + c]) == lower(words[w][c])) flag++; 50 | } 51 | if (flag == lenght(words[w])) { 52 | printf("%c", punct[w]); 53 | i += lenght(words[w]) - 1; 54 | ch_flag = 0; 55 | break; 56 | } 57 | } 58 | if (ch_flag) printf("%c", str[i]); 59 | } 60 | free(str); 61 | } -------------------------------------------------------------------------------- /Semester_3/Lab_18/dop/include/cache.h: -------------------------------------------------------------------------------- 1 | // Реализовать LFU кэш фиксированного размера (количество записей задается в 2 | // конструкторе) для адресов (адресом является строка, например, “AFFB”). 3 | // Согласно алгоритму LFU после исчерпания размера кэша в начале удаляются 4 | // записи, которые запрашивались реже всего. Удобной реализацией такого кэша 5 | // является map<адрес, число запросов адреса>. При реализации использовать 6 | // дополнительный multimap или priority_queue (т.е. всего 2 map) для быстрого 7 | // поиска адреса, который встречался наименьшее число раз. 8 | 9 | // Если же все элементы в кэше имеют одинаковый счётчик, то в этом случае 10 | // вытеснение осуществляется по методу FIFO: первым вошёл - первым вышел 11 | // https://bimlibik.github.io/posts/cache-algorithms/#least-frequently-used---lfu-наименее-часто-используемый 12 | 13 | // методы: 14 | // LfuCache(size_t size) 15 | // bool find_and_add(const string &address); // возвращает true, если адрес 16 | // найден в кэше operator<< - для вывода на экран 17 | 18 | #pragma once 19 | 20 | #include 21 | #include 22 | #include 23 | #include 24 | 25 | class LfuCache { 26 | private: 27 | // {key, {value, count}} 28 | std::map> cache; 29 | std::multimap freq; 30 | size_t size; 31 | 32 | public: 33 | LfuCache(size_t size); 34 | std::string get(const std::string &str); 35 | void add(const std::string &address, const std::string &value); 36 | friend std::ostream &operator<<(std::ostream &out, const LfuCache &cache); 37 | void print(); 38 | }; -------------------------------------------------------------------------------- /Semester_2/Lab_8/dop/main.cpp: -------------------------------------------------------------------------------- 1 | // Сортировка вставками: пусть первые k элементов упорядочены по возрастанию 2 | // Берется (k+1)-ый элемент и размещается среди первых k так, 3 | // чтобы упорядоченными оказались k+1 элементов. 4 | // Этот метод применяется при k от 1 до n-1 5 | 6 | // доп: реализовать алгоритм быстрой сортировки 7 | // и сравнить скорость их выполнения 8 | 9 | #include 10 | #include 11 | 12 | #include "sort.h" 13 | 14 | using namespace std; 15 | #define N 50000 // кол-во элементов 16 | #define OUTPUT // нужно ли принтовать массив 17 | 18 | int main() { 19 | int arr[N] = {0}, temp[N] = {0}; 20 | for (int i = 0; i < N; i++) arr[i] = rand() % (N * 10); 21 | 22 | #ifdef OUTPUT 23 | printf("%-11s", "original:"); 24 | print_arr(arr, N); 25 | #endif 26 | 27 | // измряем время сортировки вставками 28 | for (int i = 0; i < N; i++) temp[i] = arr[i]; 29 | auto begin = chrono::steady_clock::now(); 30 | sort(arr, N); // сортировка вставками 31 | auto end = chrono::steady_clock::now(); 32 | auto time = chrono::duration_cast(end - begin); 33 | printf("Sort time elapsed: %ld ms\n", time.count()); 34 | 35 | // измряем время быстрой сортировки 36 | for (int i = 0; i < N; i++) temp[i] = arr[i]; 37 | begin = chrono::steady_clock::now(); 38 | qsort(arr, N); // быстрая сортировка 39 | end = chrono::steady_clock::now(); 40 | time = chrono::duration_cast(end - begin); 41 | printf("qSort time elapsed: %ld ms\n", time.count()); 42 | 43 | #ifdef OUTPUT 44 | printf("%-11s", "sorted:"); 45 | print_arr(arr, N); 46 | #endif 47 | } -------------------------------------------------------------------------------- /Semester_2/Lab_14/dop/shape.cpp: -------------------------------------------------------------------------------- 1 | #include "shape.h" 2 | 3 | #include "math.h" 4 | 5 | #define M_2PI 6.283185307179586232 6 | 7 | using namespace std; 8 | 9 | // class Point 10 | 11 | Point::Point(double x, double y) : x(x), y(y) {} 12 | 13 | ostream &operator<<(ostream &out, Point &p) { 14 | out << "(" << p.x << ", " << p.y << ")"; 15 | return out; 16 | } 17 | 18 | // class Shape 19 | 20 | Shape::Shape(Point pos) : id(next_id()), pos(pos) {} 21 | 22 | unsigned long Shape::next_id() { 23 | static unsigned long next_id = 0; 24 | return next_id++; 25 | } 26 | 27 | void Shape::print() { 28 | cout << "id: " << id << endl; 29 | cout << "pos: " << pos << endl; 30 | } 31 | 32 | unsigned long Shape::get_id() { return id; } 33 | 34 | double Shape::get_contour_length() { return 0; } 35 | 36 | bool Shape::operator==(Shape &s) { 37 | return get_contour_length() == s.get_contour_length(); 38 | } 39 | 40 | // class Circle 41 | 42 | Circle::Circle(Point pos, double r, string text) 43 | : Shape(pos), r(r), text(text) {} 44 | 45 | void Circle::print() { 46 | cout << "type: Circle" << endl; 47 | Shape::print(); 48 | cout << "radius: " << r << endl; 49 | cout << "text: " << text << endl; 50 | } 51 | 52 | double Circle::get_contour_length() { return M_2PI * r; } 53 | 54 | // class Segment 55 | 56 | Segment::Segment(Point start, Point end) 57 | : Shape(start), start(start), end(end) {} 58 | 59 | void Segment::print() { 60 | cout << "type: Segment" << endl; 61 | Shape::print(); 62 | cout << "start pos: " << start << endl; 63 | cout << "end pos: " << end << endl; 64 | } 65 | 66 | double Segment::get_contour_length() { 67 | return sqrt(pow(end.x - start.x, 2) + pow(end.y - start.y, 2)); 68 | } -------------------------------------------------------------------------------- /Variants/Lab_9/var_12/lab.cpp: -------------------------------------------------------------------------------- 1 | #include "lab.h" 2 | 3 | // инвертирует каждый четвертый бит числа 4 | unsigned int invert_4(unsigned int N) { 5 | unsigned int mask = 0b1000; // начальная маска 6 | for (int i = 0; i < 8; i++) { // 8 раз т.к. uint = 4 байта 7 | N = N ^ mask; // инвертируем нужный бит с помощью маски 8 | mask = mask << 4; // смещаем маску на следующий четвертый бит 9 | } 10 | return N; 11 | } 12 | 13 | // инвертирует каждый N-ый бит числа (32 bit) 14 | unsigned int invert_every_nth(unsigned int N, unsigned int bit) { 15 | if (bit > 32) return N; // сразу выводим, т.к. нет смысла 16 | unsigned int mask = 1 << (bit - 1); // начальная маска 17 | while (mask > 0) { // пока не сдвинули бит маски за ее границу 18 | N = N ^ mask; // инвертируем нужный бит с помощью маски 19 | if ((int) mask < 0) break; // если достигли старшего бита - выходим 20 | mask = mask << bit; // сдвигаем маску на N бит влево 21 | } 22 | return N; 23 | } 24 | 25 | // определяет, каждый какой бит инвертирован 26 | unsigned int get_invert_offset(unsigned int a, unsigned int b) { 27 | unsigned int diff = a ^ b; // определяем побитовую разницу 28 | for (int i = 0; i < 32; i++) // проходимся по всем битам 29 | if ((diff >> i) & 1) return i + 1; // если в разнице нашли единицу - возвращаем индекс 30 | return 0; // а тут ничего не нашли 31 | } 32 | 33 | // красивый вывод двоичного числа на экран 34 | void print_bin(unsigned int N) { 35 | // проходим по всем битам в обратном порядке 36 | for (int i = 31; i > -1; i--) 37 | printf("%d", (N >> i) & 1); 38 | } -------------------------------------------------------------------------------- /Variants/Lab_4/var_17/main.c: -------------------------------------------------------------------------------- 1 | // Ввести строку и слово, удалить из строки все слова, 2 | // которые лексикографически меньше, чем введенное слово 3 | 4 | #include 5 | #include 6 | 7 | #define WORDS_LIMIT 30 8 | #define WORDS_LEN 30 9 | #define STR_LIMIT (WORDS_LEN + 1) * WORDS_LIMIT 10 | 11 | #define len(x) (sizeof(x) / sizeof((x)[0])) 12 | 13 | int strlen(char *str) { 14 | int count = 0; 15 | for (int i = 0; str[i] != '\0'; i++) count++; 16 | return count; 17 | } 18 | 19 | int strcmp(const char *s1, const char *s2) { 20 | unsigned char c1, c2; 21 | while ((c1 = *s1++) == (c2 = *s2++)) 22 | if (c1 == '\0') 23 | return 0; 24 | return c1 - c2; 25 | } 26 | 27 | int is_char(char c) { 28 | return ((65<=c && c<=90) 29 | || (97<=c && c<=122) 30 | || (128<=c && c<=175) 31 | || (224<=c && c<=239)); } 32 | 33 | int main (int argc, char *argv[]) { 34 | char words[WORDS_LIMIT][WORDS_LEN + 1] = {0}; 35 | char str[STR_LIMIT] = {0}; 36 | char comp_word[WORDS_LEN] = {0}; 37 | 38 | printf("Enter a string:\n"); 39 | fgets(str, STR_LIMIT, stdin); 40 | 41 | printf("\nEnter word:\n"); 42 | fgets(comp_word, WORDS_LEN, stdin); 43 | comp_word[strlen(comp_word)-1] = '\0'; // ставим конец слова вместо переноса строки 44 | 45 | printf("\nWords:\n"); 46 | 47 | int word = 0, k = 0; 48 | for (int i = 0; i <= len(str); i++) 49 | if (str[i] == ' ' || str[i] == '\0' || str[i] == '\n') { 50 | words[word][k] = '\0'; 51 | if (str[i] != '\n') word++; else break; 52 | k = 0; 53 | } else if (is_char(str[i])) { words[word][k] = str[i]; k++; } 54 | 55 | for (int w = 0; w <= word; w++) { 56 | if (strcmp(words[w], comp_word) < 0) 57 | printf("%s\n", words[w]); 58 | } 59 | } -------------------------------------------------------------------------------- /Variants/Lab_4/var_7/main.c: -------------------------------------------------------------------------------- 1 | // Ввести строку 2 | // Вывести различные слова вместе с количеством их появления в строке 3 | 4 | #include 5 | #include 6 | 7 | #define WORDS_LIMIT 50 8 | #define WORDS_LEN 30 9 | #define STR_LIMIT (WORDS_LEN + 1) * WORDS_LIMIT 10 | 11 | #define ceil(x) ((x-(int)(x)) > 0 ? (int)(x+1) : (int)(x)) 12 | #define len(x) (sizeof(x) / sizeof((x)[0])) 13 | 14 | int is_char(char c) { 15 | return ((65<=c && c<=90) 16 | || (97<=c && c<=122) 17 | || (128<=c && c<=175) 18 | || (224<=c && c<=239)) ? 1 : 0; } 19 | 20 | int strcmp(char s1[], char s2[]) { // аналог функции strcmp в string.h 21 | for (int i = 0; ; i++) { 22 | if (s1[i] != s2[i]) return 1; // строки не совпадают 23 | if (s1[i] == '\0') return 0; // строки совпадают 24 | } } 25 | 26 | void strcopy(char *dest, const char *src) { // аналог функции strcpy в string.h 27 | char *p = dest; 28 | do *p++ = *src; // колпируем каждый символ из src в dest 29 | while (*src++); 30 | } 31 | 32 | void main() { 33 | char words[WORDS_LIMIT][WORDS_LEN + 1] = {0}; 34 | char str[STR_LIMIT] = {0}; 35 | 36 | printf("Enter a string:\n"); 37 | fgets(str, STR_LIMIT, stdin); 38 | printf("\nOutput:\n"); 39 | 40 | int length = 0, k = 0; 41 | for (int i = 0; i <= len(str); i++) 42 | if (str[i] == ' ' || str[i] == '\0' || str[i] == '\n') { 43 | words[length][k] = '\0'; 44 | if (str[i] != '\n') length++; else break; 45 | k = 0; 46 | } else if (is_char(str[i])) { words[length][k] = str[i]; k++; } 47 | 48 | for (int i = 0; i <= ceil(length / 2); i++) { 49 | printf("%s ", words[i]); 50 | if(strcmp(words[i], words[length - i]) != 0) { 51 | printf("%s ", words[length - i]); 52 | } 53 | } 54 | } -------------------------------------------------------------------------------- /Semester_2/Lab_14/base/list.cpp: -------------------------------------------------------------------------------- 1 | #include "list.h" 2 | 3 | #include "shape.h" 4 | 5 | using namespace std; 6 | 7 | // class Node 8 | 9 | Node::Node(Shape* s, Node* next) : shape(s), next(next) {} 10 | 11 | // class FigureList 12 | 13 | FigureList::FigureList() { 14 | head = NULL; 15 | size = 0; 16 | } 17 | 18 | void FigureList::push_front(Shape* s) { 19 | Node* temp = new Node(s); 20 | if (size) { 21 | temp->next = head; 22 | head = temp; 23 | } else { 24 | head = temp; 25 | } 26 | size++; 27 | } 28 | 29 | void FigureList::push_back(Shape* s) { 30 | Node* temp = new Node(s); 31 | if (size) { 32 | Node* last = head; 33 | while (last->next) last = last->next; 34 | last->next = temp; 35 | } else { 36 | head = temp; 37 | } 38 | size++; 39 | } 40 | 41 | Shape& FigureList::get(int id) { 42 | Node* curr = head; 43 | while (curr) { 44 | if (curr->shape->get_id() == id) return *(curr->shape); 45 | curr = curr->next; 46 | } 47 | return *(curr->shape); 48 | } 49 | 50 | void FigureList::erase(int id) { 51 | Node *curr = head, *prev = NULL; 52 | while (curr) { 53 | if (curr->shape->get_id() == id) { 54 | if (curr == head) { // первый элемент 55 | head = head->next; 56 | } else if (curr->next) { // элемент посередине 57 | prev->next = curr->next; 58 | } else { // последний элемент 59 | prev->next = NULL; 60 | } 61 | delete curr->shape; 62 | delete curr; 63 | size--; 64 | return; 65 | } 66 | prev = curr; 67 | curr = curr->next; 68 | } 69 | } 70 | 71 | void FigureList::print_all() { 72 | Node* curr = head; 73 | int i = 1; 74 | while (curr) { 75 | cout << endl << "item: " << i++ << endl; 76 | curr->shape->print(); 77 | curr = curr->next; 78 | } 79 | } -------------------------------------------------------------------------------- /Semester_2/Lab_14/dop/list.cpp: -------------------------------------------------------------------------------- 1 | #include "list.h" 2 | 3 | #include "shape.h" 4 | 5 | using namespace std; 6 | 7 | // class Node 8 | 9 | Node::Node(Shape* s, Node* next) : shape(s), next(next) {} 10 | 11 | // class FigureList 12 | 13 | FigureList::FigureList() { 14 | head = NULL; 15 | size = 0; 16 | } 17 | 18 | void FigureList::push_front(Shape* s) { 19 | Node* temp = new Node(s); 20 | if (size) { 21 | temp->next = head; 22 | head = temp; 23 | } else { 24 | head = temp; 25 | } 26 | size++; 27 | } 28 | 29 | void FigureList::push_back(Shape* s) { 30 | Node* temp = new Node(s); 31 | if (size) { 32 | Node* last = head; 33 | while (last->next) last = last->next; 34 | last->next = temp; 35 | } else { 36 | head = temp; 37 | } 38 | size++; 39 | } 40 | 41 | Shape& FigureList::get(int id) { 42 | Node* curr = head; 43 | while (curr) { 44 | if (curr->shape->get_id() == id) return *(curr->shape); 45 | curr = curr->next; 46 | } 47 | return *(curr->shape); 48 | } 49 | 50 | void FigureList::erase(int id) { 51 | Node *curr = head, *prev = NULL; 52 | while (curr) { 53 | if (curr->shape->get_id() == id) { 54 | if (curr == head) { // первый элемент 55 | head = head->next; 56 | } else if (curr->next) { // элемент посередине 57 | prev->next = curr->next; 58 | } else { // последний элемент 59 | prev->next = NULL; 60 | } 61 | delete curr->shape; 62 | delete curr; 63 | size--; 64 | return; 65 | } 66 | prev = curr; 67 | curr = curr->next; 68 | } 69 | } 70 | 71 | void FigureList::print_all() { 72 | Node* curr = head; 73 | int i = 1; 74 | while (curr) { 75 | cout << endl << "item: " << i++ << endl; 76 | curr->shape->print(); 77 | curr = curr->next; 78 | } 79 | } -------------------------------------------------------------------------------- /Variants/Lab_12/var_12/matrix.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | unsigned int get_size(vector > arr); 8 | 9 | class Matrix { 10 | private: 11 | vector > arr; 12 | 13 | public: 14 | // конструтроры (не лего) 15 | 16 | Matrix(unsigned int size = 1, double def = 0); 17 | Matrix(vector > temp); 18 | 19 | // сеттеры 20 | 21 | Matrix& set(unsigned int x, unsigned int y, double value); 22 | Matrix& set(vector > temp); 23 | Matrix& set(Matrix& m); 24 | 25 | // геттеры 26 | 27 | double get(unsigned int x, unsigned int y); 28 | const unsigned int size(); 29 | const double determinant(); 30 | 31 | void print(); 32 | 33 | // преобразования 34 | 35 | Matrix transpose(); 36 | Matrix inverse(); 37 | Matrix minor(int i, int j); 38 | Matrix minor_matrix(); 39 | Matrix algebraic_additions(); 40 | 41 | // операторы 42 | 43 | Matrix& operator+=(const Matrix& x); // сложение с матрицей 44 | Matrix& operator-=(const Matrix& x); // вычитание матрицы 45 | Matrix& operator*=(const Matrix& x); // умножение на матрицу 46 | Matrix& operator*=(const double& x); // умножение на скаляр 47 | Matrix& operator/=(const Matrix& x); // деление на матрицу 48 | Matrix& operator/=(const double& x); // деление на скаляр 49 | 50 | friend Matrix operator-(const Matrix &m); // унарный минус 51 | friend Matrix operator+(Matrix a, const Matrix &b); 52 | friend Matrix operator-(Matrix a, const Matrix &b); 53 | friend Matrix operator*(Matrix a, const Matrix &b); 54 | friend Matrix operator*(Matrix a, const double &b); 55 | friend Matrix operator/(Matrix a, const Matrix &b); 56 | friend Matrix operator/(Matrix a, const double &b); 57 | }; -------------------------------------------------------------------------------- /Semester_3/Lab_18/dop/include/translate.h: -------------------------------------------------------------------------------- 1 | // Реализовать LFU кэш фиксированного размера (количество записей задается в 2 | // конструкторе) для адресов (адресом является строка, например, “AFFB”). 3 | // Согласно алгоритму LFU после исчерпания размера кэша в начале удаляются 4 | // записи, которые запрашивались реже всего. Удобной реализацией такого кэша 5 | // является map<адрес, число запросов адреса>. При реализации использовать 6 | // дополнительный multimap или priority_queue (т.е. всего 2 map) для быстрого 7 | // поиска адреса, который встречался наименьшее число раз. 8 | 9 | // написать тестирующую программу 10 | 11 | // доп: линкед лист со всеми словами для перевода, 12 | // текст переводится с помощью этих слов, слово сначала ищем в кеше а потом 13 | 14 | // алгоритм: 15 | // 1. считываем словарь 16 | // - сохраняем в линкед лист в виде пар слово-перевод 17 | // - (поиск по линкед листу долгий) 18 | // 2. считываем текст 19 | // - считываем пословно, сразу переводя 20 | // 3. перевод текста 21 | // - ищем слово в кеше 22 | // - если находим, то берем перевод из кеша и увеличиваем счетчик 23 | // - если не находим, то ищем в линкед листе 24 | // - если находим, то берем перевод и добавляем в кеш 25 | // - если не находим, то выводим null 26 | 27 | #pragma once 28 | 29 | #include 30 | #include 31 | #include 32 | #include 33 | 34 | #include "cache.h" 35 | 36 | class Translate { 37 | private: 38 | LfuCache cache; 39 | std::list> words; 40 | 41 | public: 42 | // constructor from ison file with words and translations 43 | Translate(const std::string& filename, int cache_size); 44 | 45 | // translate word 46 | std::string translate(const std::string& word); 47 | 48 | // print cache 49 | void print_cache(); 50 | 51 | // print words 52 | void print_words(); 53 | }; -------------------------------------------------------------------------------- /Variants/Lab_17/var_1/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "vector.h" 3 | 4 | using namespace std; 5 | 6 | struct Point { 7 | int x; 8 | int y; 9 | int z; 10 | 11 | friend std::ostream& operator<<(std::ostream& os, const Point& p) { 12 | os << "(" << p.x << ", " << p.y << ", " << p.z << ")"; 13 | return os; 14 | } 15 | }; 16 | 17 | int main() { 18 | Vector v(5, 0); 19 | v.push_back(1); 20 | v.push_back(2); 21 | v.push_back(3); 22 | v.push_back(4); 23 | v.push_back(5); 24 | v.push_back(6); 25 | v.push_back(7); 26 | v.push_back(8); 27 | v.push_back(9); 28 | cout << v << endl; 29 | 30 | Vector v2(2, {0, 0, 0}); 31 | v2.push_back({1, 1, 1}); 32 | v2.push_back({2, 2, 2}); 33 | v2.push_back({3, 3, 3}); 34 | v2.push_back({4, 4, 4}); 35 | v2.push_back({5, 5, 5}); 36 | cout << v2 << endl << endl; 37 | 38 | // test erase & at 39 | cout << "v[7] = " << v.at(7) << endl; 40 | 41 | v.erase(7); 42 | cout << "after erase v[7] = " << v.at(7) << endl; 43 | cout << v << endl << endl; 44 | 45 | // test insert 46 | v.insert(7, 42); 47 | cout << "after insert v[7] = " << v.at(7) << endl; 48 | cout << v << endl << endl; 49 | 50 | // test exceptions 51 | try { 52 | cout << "try to get v.at(100)" << endl; 53 | cout << v.at(100) << endl; 54 | } catch (const std::out_of_range& e) { 55 | cout << "Exception: " << e.what() << endl; 56 | } 57 | 58 | cout << endl; 59 | 60 | try { 61 | cout << "try to v.insert(100, 5)" << endl; 62 | v.insert(100, 5); 63 | } catch (const std::out_of_range& e) { 64 | cout << "Exception: " << e.what() << endl; 65 | } 66 | 67 | cout << endl; 68 | 69 | try { 70 | cout << "try to v.erase(100)" << endl; 71 | v.erase(100); 72 | } catch (const std::out_of_range& e) { 73 | cout << "Exception: " << e.what() << endl; 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /Semester_2/Lab_6/base/snippets.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct file; 5 | struct node; 6 | struct list; 7 | struct word; 8 | 9 | // конфиги 10 | #define NORMAL 0 11 | #define REVERSE 1 12 | 13 | #define ALPHABET 0 14 | #define LENGTH 1 15 | #define VOWELS 2 16 | #define CONSNTS 3 17 | 18 | #define EXIT 0 19 | #define HELP 1 20 | #define REMOVE 2 21 | #define INSERT 3 22 | #define SORT 4 23 | #define SORTx2 5 24 | #define PRINT 9 25 | 26 | int file_size(FILE *file); 27 | file *read_file(const char *path); 28 | void init(list *list); 29 | void destroy_word(word *word); 30 | void destroy_node(node *node); 31 | void destroy(list *list); 32 | char *read_str(); 33 | int strlen(char *str); 34 | int vowels_count(char *str); 35 | void upd_word(word *w); 36 | struct word *make_word(char *str, int capacity); 37 | char lower(int ch); 38 | void push_back(list *list, char *str, int capacity); 39 | void merge_lists(list *source, list *destination); 40 | struct word *get_word(list *list, int index); 41 | struct node *get_node(list *list, int index); 42 | void print_list(list *list); 43 | int is_char(int ch); 44 | int strcmp(char *s1, char *s2); 45 | void edit_word(list *list, int index, char *str, int cap); 46 | void swap_nodes(node *n1, node *n2); 47 | void parse_str(char *temp, size_t size, list *list); 48 | list *parse_file(file *file); 49 | int compare_words(word *w1, word *w2, int order); 50 | void insert(list *list, node *curr, char *str); 51 | int find_word(list *list, char *str, int offset, int order); 52 | void remove_node(list *list, int index); 53 | void remove_nodes(list *list, int start, int end); 54 | int need_swap(word *w1, word *w2, int sort_type, int reverse); 55 | void sort_list(list *list, int sort_type, int reverse); 56 | void double_sort(list *list, int sort_1, int sort_2, int order); 57 | void double_sort_2(list *list, int sort_1, int sort_2, int order); -------------------------------------------------------------------------------- /Exam/Semester_3/ferz.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include 5 | 6 | using namespace std; 7 | bool check(int** desk, int n, int i, int j) { 8 | int k, tmp_i1, tmp_i2, tmp_j; 9 | 10 | for (k = 0; k < j; k++) { 11 | if (desk[i][k] == 1) return 0; 12 | } 13 | tmp_i1 = i - 1; 14 | tmp_j = j - 1; 15 | 16 | while (tmp_i1 >= 0 && tmp_j >= 0) { 17 | if (desk[tmp_i1][tmp_j] == 1) return 0; 18 | tmp_i1--; 19 | tmp_j--; 20 | } 21 | tmp_i2 = i + 1; 22 | tmp_j = j - 1; 23 | while (tmp_i2 < n && tmp_j >= 0) { 24 | if (desk[tmp_i2][tmp_j] == 1) return 0; 25 | tmp_i2++; 26 | tmp_j--; 27 | } 28 | return 1; 29 | } 30 | int pherz(int** desk, int* index, int j, int n) { 31 | int counter = 0; 32 | if (j >= n) { 33 | // for(int k = 0; k < n; k++) 34 | // cout << index[k]; 35 | // cout << endl; 36 | // for(int i = 0; i < n; i++){ 37 | // for(int j = 0; j < n; j++){ 38 | // cout << desk[i][j]; 39 | // } 40 | // cout << endl; 41 | // } 42 | // cout << endl; 43 | return 1; 44 | } else { 45 | for (int i = 0; i < n; i++) { 46 | if (check(desk, n, i, j)) { 47 | desk[i][j] = 1; 48 | index[j] = i; 49 | counter += pherz(desk, index, j + 1, n); 50 | desk[i][j] = 0; 51 | index[j] = 0; 52 | } 53 | } 54 | return counter; 55 | } 56 | } 57 | int main() { 58 | int** desk; 59 | int* index; 60 | 61 | int n, i, j; 62 | cout << "n = "; 63 | cin >> n; 64 | index = new int[n]; 65 | desk = new int*[n]; 66 | for (i = 0; i < n; i++) { 67 | desk[i] = new int[n]; 68 | for (j = 0; j < n; j++) { 69 | desk[i][j] = 0; 70 | index[j] = 0; 71 | } 72 | } 73 | cout << "Amount = " << pherz(desk, index, 0, n) << endl; 74 | for (i = 0; i < n; i++) delete[] desk[i]; 75 | delete desk; 76 | delete index; 77 | } 78 | -------------------------------------------------------------------------------- /Semester_2/Lab_6/dop/snippets.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct file; 5 | struct node; 6 | struct list; 7 | struct word; 8 | 9 | // конфиги 10 | #define NORMAL 0 11 | #define REVERSE 1 12 | 13 | #define ALPHABET 0 14 | #define LENGTH 1 15 | #define VOWELS 2 16 | #define CONSNTS 3 17 | 18 | #define EXIT 0 19 | #define HELP 1 20 | #define REMOVE 2 21 | #define INSERT 3 22 | #define SORT 4 23 | #define SORTx2 5 24 | #define PRINT 9 25 | 26 | int file_size(FILE *file); 27 | file *read_file(const char *path); 28 | void init(list *list); 29 | void destroy_word(word *word); 30 | void destroy_node(node *node); 31 | void destroy(list *list); 32 | char *read_str(); 33 | int strlen(char *str); 34 | int vowels_count(char *str); 35 | void upd_word(word *w); 36 | struct word *make_word(char *str, int capacity); 37 | char lower(int ch); 38 | void push_back(list *list, char *str, int capacity); 39 | void merge_lists(list *source, list *destination); 40 | struct word *get_word(list *list, int index); 41 | struct node *get_node(list *list, int index); 42 | void print_list(list *list); 43 | int is_char(int ch); 44 | int strcmp(char *s1, char *s2); 45 | void edit_word(list *list, int index, char *str, int cap); 46 | void swap_nodes(node *n1, node *n2); 47 | void parse_str(char *temp, size_t size, list *list); 48 | list *parse_file(file *file); 49 | int compare_words(word *w1, word *w2, int order); 50 | void insert(list *list, node *curr, char *str); 51 | int find_word(list *list, char *str, int offset, int order); 52 | void remove_node(list *list, int index); 53 | void remove_nodes(list *list, int start, int end); 54 | int need_swap(word *w1, word *w2, int sort_type, int reverse); 55 | void sort_list(list *list, int sort_type, int reverse); 56 | void double_sort(list *list, int sort_1, int sort_2, int order); 57 | void double_sort_2(list *list, int sort_1, int sort_2, int order); 58 | // void remove_duplicates(list *list); -------------------------------------------------------------------------------- /Semester_1/Lab_4/main.c: -------------------------------------------------------------------------------- 1 | // Ввести строку, вывести различные слова 2 | // вместе с количеством их появления в строке 3 | 4 | #include 5 | #include 6 | 7 | #define WORDS_LIMIT 50 8 | #define WORDS_LEN 30 9 | #define STR_LIMIT (WORDS_LEN + 1) * WORDS_LIMIT 10 | 11 | #define len(x) (sizeof(x) / sizeof((x)[0])) 12 | 13 | int is_char(char c) { 14 | return ((65 <= c && c <= 90) || (97 <= c && c <= 122) || 15 | (128 <= c && c <= 175) || (224 <= c && c <= 239)); 16 | } 17 | 18 | int strcmp(char s1[], char s2[]) { // аналог функции strcmp в string.h 19 | for (int i = 0;; i++) { 20 | if (s1[i] != s2[i]) return 1; // строки не совпадают 21 | if (s1[i] == '\0') return 0; // строки совпадают 22 | } 23 | } 24 | 25 | void strcopy(char *dest, const char *src) { // аналог функции strcpy в string.h 26 | char *p = dest; 27 | do *p++ = *src; // колпируем каждый символ из src в dest 28 | while (*src++); 29 | } 30 | 31 | void main() { 32 | char words[WORDS_LIMIT][WORDS_LEN + 1] = {0}; 33 | char str[STR_LIMIT] = {0}; 34 | 35 | printf("Enter a string:\n"); 36 | fgets(str, STR_LIMIT, stdin); 37 | printf("\nWords:\n--------\n"); 38 | 39 | int word = 0, k = 0; 40 | for (int i = 0; i <= len(str); i++) 41 | if (str[i] == ' ' || str[i] == '\0' || str[i] == '\n') { 42 | words[word][k] = '\0'; 43 | if (str[i] != '\n') 44 | word++; 45 | else 46 | break; 47 | k = 0; 48 | } else if (is_char(str[i])) { 49 | words[word][k] = str[i]; 50 | k++; 51 | } 52 | 53 | int flag = 0; 54 | for (int w = 0; w <= word + 1; w++) { 55 | int count = 1; 56 | for (int i = 0; i <= word + 1; i++) 57 | if (strcmp(words[i], words[w]) == 0 && w != i && 58 | strcmp(words[i], "\0") != 0) { 59 | strcopy(words[i], "\0"); 60 | count++; 61 | } 62 | if (strcmp(words[w], "\0") != 0) printf("%s - %d times\n", words[w], count); 63 | } 64 | } -------------------------------------------------------------------------------- /Variants/Lab_6/var_9/main.c: -------------------------------------------------------------------------------- 1 | // Написать программу составления двоичного дерева слов по символьному файлу 2 | // и функцию определения глубины дерева 3 | 4 | #include 5 | #include // нельзя 6 | #include // нельзя 7 | #include 8 | 9 | #define MAXWORD 100 10 | 11 | typedef struct tnode { // узел дерева 12 | char* word; // указатель на строку (слово) 13 | int count; // число вхождений 14 | struct tnode* left; // левый потомок 15 | struct tnode* right; // правый потомок 16 | } tnode; 17 | 18 | // Функция добавления узла к дереву 19 | struct tnode* addtree(struct tnode* p, char* w) { 20 | int cond; 21 | if (p == NULL) { 22 | p = (struct tnode*)malloc(sizeof(struct tnode)); 23 | p->word = _strdup(w); 24 | p->count = 1; 25 | p->left = p->right = NULL; 26 | } 27 | else if ((cond = strcmp(w, p->word)) == 0) 28 | p->count++; 29 | else if (cond < 0) 30 | p->left = addtree(p->left, w); 31 | else 32 | p->right = addtree(p->right, w); 33 | return p; 34 | } 35 | 36 | // Функция удаления поддерева 37 | void freemem(tnode* tree) { 38 | if (tree != NULL) { 39 | freemem(tree->left); 40 | freemem(tree->right); 41 | free(tree->word); 42 | free(tree); 43 | } 44 | } 45 | 46 | // Функция вывода дерева 47 | void treeprint(struct tnode* p) { 48 | if (p != NULL) { 49 | treeprint(p->left); 50 | printf("%s", p->word); 51 | if (p->count > 1) { 52 | printf("\t - %d times\n", p->count); 53 | } else { 54 | printf("\n"); 55 | } 56 | treeprint(p->right); 57 | } 58 | } 59 | 60 | 61 | int main() { 62 | struct tnode* root; 63 | char word[MAXWORD]; 64 | root = NULL; 65 | do { 66 | scanf("%s", word, MAXWORD); 67 | if (isalpha(word[0])) 68 | root = addtree(root, word); 69 | } while (word[0] != '0'); // условие выхода – ввод символа '0' 70 | treeprint(root); 71 | freemem(root); 72 | getchar(); getchar(); 73 | return 0; 74 | } -------------------------------------------------------------------------------- /Practice/Lab_15/extended/bmp.hpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | class BitMap { 6 | public: 7 | struct __attribute__((__packed__)) BitMapFileHeader { 8 | uint16_t Type; // (2) Сигнатура "BM" 9 | uint32_t Size; // (4) Размер файла 10 | uint16_t Reserv1; // (2) Зарезервировано 11 | uint16_t Reserv2; // (2) Зарезервировано 12 | uint32_t Offset; // (4) Смещение изображения 13 | }; 14 | 15 | struct __attribute__((__packed__)) BitMapInfoHeader { 16 | uint32_t Size; // (4) Длина заголовка 17 | uint32_t Width; // (4) Ширина изображения, точки 18 | uint32_t Height; // (4) Высота изображения, точки 19 | uint16_t Planes; // (2) Число плоскостей 20 | uint16_t BitCount; // (2) Глубина цвета, бит на точку 21 | uint32_t Compress; // (4) Тип компрессии 22 | uint32_t SizeImage; // (4) Размер изображения, байт 23 | uint32_t XpelsPerM; // (4) Горизонтальное разрешение 24 | uint32_t YpelsPerM; // (4) Вертикальное разрешение 25 | uint32_t Colors; // (4) Число используемых цветов 26 | uint32_t Palette; // (4) Число основных цветов 27 | }; 28 | 29 | struct __attribute__((__packed__)) BGR { 30 | uint8_t Blue; // (1) Синий 31 | uint8_t Green; // (1) Зеленый 32 | uint8_t Red; // (1) Красный 33 | }; 34 | 35 | enum RotateType { 36 | Rotate90, 37 | Rotate180, 38 | Rotate270, 39 | }; 40 | 41 | enum FlipType { 42 | FlipHorizontal, 43 | FlipVertical, 44 | FlipBoth, 45 | }; 46 | 47 | BitMap(); 48 | ~BitMap(); 49 | 50 | BitMap(const char* filename); 51 | void Load(const char* filename); 52 | void Save(const char* filename); 53 | 54 | void Print(uint8_t threshold = 127, bool invert = false, char symbol = '#'); 55 | 56 | void Rotate(RotateType rotate_type); 57 | void Flip(FlipType flip_type); 58 | 59 | private: 60 | BitMapFileHeader file_header_; 61 | BitMapInfoHeader info_header_; 62 | BGR* data_; 63 | }; 64 | -------------------------------------------------------------------------------- /Semester_1/Lab_3/main.c: -------------------------------------------------------------------------------- 1 | // Написать функцию, которая вставляет в массив элемент 2 | // с заданным индексом и заданным значением 3 | // Лишний элемент должен пропасть 4 | 5 | #include 6 | #include 7 | #include 8 | 9 | #define len(x) (sizeof(x) / sizeof((x)[0])) 10 | int size; 11 | 12 | #define ARR_INIT 2 13 | // 0 - ввод массива пользователем 14 | // 1 - генерация массива {0 .. N-1} 15 | // 2 - генерация случайного массива 16 | 17 | void insert(int size, int* arr, int index, int value) { 18 | if (index >= 0 && index < size) { 19 | for (int i = size - 1; i > index; i--) arr[i] = arr[i - 1]; 20 | arr[index] = value; 21 | } else { 22 | printf("Index out of range\n"); 23 | exit(EXIT_FAILURE); 24 | } 25 | } 26 | 27 | void arr_init(int length, int* arr) { 28 | switch (ARR_INIT) { 29 | case 0: 30 | printf("Enter %d integers:\n", length); 31 | for (int i = 0; i < length; i++) scanf("%d", &arr[i]); 32 | printf("\n"); 33 | break; 34 | case 1: 35 | for (int i = 0; i < size; i++) arr[i] = i; 36 | break; 37 | case 2: 38 | srand(time(NULL)); // инициализируем генератор случайных чисел 39 | for (int i = 0; i < size; i++) arr[i] = rand() % 100; 40 | break; 41 | default: 42 | printf("Invalid Configuration\nChange ARR_INIT to correct"); 43 | exit(EXIT_FAILURE); 44 | } 45 | } 46 | 47 | void main() { 48 | printf("Input array size: "); 49 | scanf("%d", &size); 50 | printf("\n"); 51 | 52 | int arr[size]; 53 | arr_init(len(arr), arr); // инициализируем массив 54 | 55 | printf("Original array:\n[ "); 56 | for (int i = 0; i < size; i++) printf("%d ", arr[i]); 57 | 58 | int id = 0, val = 0; 59 | printf("]\n\nEnter Index and Value to insert: "); 60 | scanf("%d %d", &id, &val); 61 | 62 | insert(len(arr), arr, id, val); // используем функцию 63 | 64 | printf("\nArray after insert:\n[ "); 65 | for (int i = 0; i < size; i++) printf("%d ", arr[i]); 66 | printf("]\n"); 67 | } -------------------------------------------------------------------------------- /Semester_1/Lab_2/main.c: -------------------------------------------------------------------------------- 1 | // Ввести строку, проверить нет ли повторяющихся слов 2 | // Вывести их если они есть 3 | // Можно считать, что все слова имеют длину ровно 3 символа 4 | 5 | #include 6 | #include 7 | 8 | #define WORDS_LIMIT 50 9 | #define WORDS_LEN 3 10 | #define STR_LIMIT (WORDS_LEN + 1) * WORDS_LIMIT 11 | 12 | #define len(x) (sizeof(x) / sizeof((x)[0])) 13 | 14 | int strcmp(char s1[], char s2[]) { // аналог функции strcmp в string.h 15 | for (int i = 0;; i++) { 16 | if (s1[i] != s2[i]) return 1; // строки не совпадают 17 | if (s1[i] == '\0') return 0; // строки совпадают 18 | } 19 | } 20 | 21 | void strcopy(char *dest, const char *src) { // аналог функции strcpy в string.h 22 | char *p = dest; 23 | do *p++ = *src; // колпируем каждый символ из src в dest 24 | while (*src++); 25 | } 26 | 27 | void main() { 28 | char words[WORDS_LIMIT][WORDS_LEN + 1] = {0}; 29 | char str[STR_LIMIT] = {0}; 30 | 31 | printf("Enter string of 3-letter words:\n"); 32 | fgets(str, STR_LIMIT, stdin); 33 | printf("\n"); 34 | 35 | int word = 0, k = 0; 36 | for (int i = 0; i <= len(str); i++) { // тут юзать getchar() 37 | if (str[i] == ' ' || str[i] == '\0' || str[i] == '\n') { 38 | words[word][k] = '\0'; 39 | if (str[i] != '\n') 40 | word++; 41 | else 42 | break; 43 | k = 0; 44 | } else { 45 | words[word][k] = str[i]; 46 | k++; 47 | } 48 | } 49 | 50 | printf("Dublicates: "); 51 | int flag = 0; 52 | for (int w = 0; w <= word + 1; w++) { 53 | int count = 1; 54 | for (int i = 0; i <= word + 1; i++) 55 | if (strcmp(words[i], words[w]) == 0 && strcmp(words[i], "\0") != 0 && 56 | w != i) { 57 | strcopy(words[i], "\0"); 58 | count++; 59 | } 60 | if (count > 1) { 61 | if (!flag) { 62 | flag = 1; 63 | printf("\n"); 64 | } 65 | printf("%s - %d times\n", words[w], count); 66 | } 67 | } 68 | 69 | if (!flag) printf("not found :(\n"); 70 | } -------------------------------------------------------------------------------- /Variants/Lab_17/var_1/dop/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "vector.h" 4 | 5 | 6 | using namespace std; 7 | 8 | struct Point { 9 | int x; 10 | int y; 11 | int z; 12 | 13 | friend std::ostream& operator<<(std::ostream& os, const Point& p) { 14 | os << "(" << p.x << ", " << p.y << ", " << p.z << ")"; 15 | return os; 16 | } 17 | }; 18 | 19 | int main() { 20 | Vector v(5, 0); 21 | for (int i = 0; i < 10; i++) v.push_back(i); 22 | cout << v << endl; 23 | 24 | Vector v2(2, {0, 0, 0}); 25 | for (int i = 0; i < 10; i++) v2.push_back({i, i, i}); 26 | cout << v2 << endl << endl; 27 | 28 | // test erase & at 29 | cout << "v[7] = " << v.at(7) << endl; 30 | 31 | v.erase(7); 32 | cout << "after erase v[7] = " << v.at(7) << endl; 33 | cout << v << endl << endl; 34 | 35 | // test insert 36 | v.insert(7, 42); 37 | cout << "after insert v[7] = " << v.at(7) << endl; 38 | cout << v << endl << endl; 39 | 40 | // test exceptions 41 | try { 42 | cout << "try to get v.at(100)" << endl; 43 | cout << v.at(100) << endl; 44 | } catch (const std::out_of_range& e) { 45 | cout << "Exception: " << e.what() << endl; 46 | } 47 | 48 | cout << endl; 49 | 50 | try { 51 | cout << "try to v.insert(100, 5)" << endl; 52 | v.insert(100, 5); 53 | } catch (const std::out_of_range& e) { 54 | cout << "Exception: " << e.what() << endl; 55 | } 56 | 57 | cout << endl; 58 | 59 | try { 60 | cout << "try to v.erase(100)" << endl; 61 | v.erase(100); 62 | } catch (const std::out_of_range& e) { 63 | cout << "Exception: " << e.what() << endl; 64 | } 65 | 66 | // test dop (+ and -) 67 | 68 | Vector BIBA(1, 0); 69 | Vector BOBA(1, 0); 70 | 71 | for (int i = 0; i < 10; i++) { 72 | BIBA.push_back(i); 73 | BOBA.push_back(9 - i); 74 | } 75 | 76 | cout << BIBA << endl << BOBA << endl; 77 | 78 | Vector ABOBA = BIBA + BOBA; 79 | cout << ABOBA << endl; 80 | 81 | Vector AMOGUS = BIBA - BOBA; 82 | cout << AMOGUS << endl; 83 | } 84 | -------------------------------------------------------------------------------- /Semester_2/Lab_12/base/HugeInt.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | using namespace std; 10 | 11 | class HugeInt { 12 | public: 13 | HugeInt(string str = "0", int digits_count = 40); 14 | HugeInt(const HugeInt &temp, bool invert = false); 15 | HugeInt(long long n); 16 | 17 | void set(string str); 18 | bool is_zero(); 19 | bool has_minus(); 20 | string to_str(); 21 | void remove_leading_zeros(); 22 | 23 | HugeInt &operator=(const HugeInt &temp); 24 | HugeInt &operator=(const long long &temp); 25 | HugeInt &operator=(const string &str); 26 | 27 | friend istream &operator>>(istream &in, HugeInt &a); 28 | friend ostream &operator<<(ostream &out, const HugeInt &a); 29 | 30 | friend bool operator==(const HugeInt &a, const HugeInt &b); 31 | friend bool operator!=(const HugeInt &a, const HugeInt &b); 32 | 33 | friend bool operator>(const HugeInt &a, const HugeInt &b); 34 | friend bool operator>=(const HugeInt &a, const HugeInt &b); 35 | 36 | friend bool operator<(const HugeInt &a, const HugeInt &b); 37 | friend bool operator<=(const HugeInt &a, const HugeInt &b); 38 | 39 | // friend HugeInt operator+(const HugeInt &a, const HugeInt &b); 40 | // friend HugeInt operator-(const HugeInt &a, const HugeInt &b); 41 | 42 | const HugeInt operator-(); 43 | 44 | friend HugeInt operator+(HugeInt a, const HugeInt &b); 45 | // friend HugeInt operator+(HugeInt &a, HugeInt &b); 46 | friend HugeInt operator+(const HugeInt &a, long long value); 47 | friend HugeInt operator+(long long value, const HugeInt &a); 48 | 49 | friend HugeInt operator-(HugeInt left, const HugeInt &right); 50 | // friend HugeInt operator-(HugeInt &a, HugeInt &b); 51 | friend HugeInt operator-(const HugeInt &a, long long value); 52 | friend HugeInt operator-(long long value, const HugeInt &a); 53 | 54 | private: 55 | vector array; 56 | unsigned int digit_count; 57 | unsigned int capacity; 58 | bool minus = false; 59 | }; -------------------------------------------------------------------------------- /Turlikov/Report_1/count_ones/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "v_small_array.h" 3 | 4 | using namespace std; 5 | 6 | #define MODE 2 7 | // 0 - default test 8 | // 1 - speed test 9 | // 2 - statistics 10 | 11 | #if MODE == 0 12 | 13 | int main () { 14 | unsigned int n_32 = 0; 15 | unsigned long long n_64 = 0; 16 | cout << "zero 32: " << count_ones(n_32) << endl; 17 | cout << "zero 64: " << count_ones(n_64) << endl; 18 | 19 | n_32 = 0xffffffff; // 4294967295 (2^32) 20 | n_64 = 0xffffffffffffffff; // 1844674407370955161 (2^64) 21 | cout << "test 32: " << count_ones(n_32) << endl; 22 | cout << "test 64: " << count_ones(n_64) << endl; 23 | 24 | n_32 = 42424242; 25 | n_64 = 4242424242424242; 26 | cout << "rand 32: " << count_ones(n_32) << endl; 27 | cout << "rand 64: " << count_ones(n_64) << endl; 28 | } 29 | 30 | #elif MODE == 1 31 | 32 | #include 33 | #define ITERS 32 34 | 35 | int main () { 36 | unsigned long long iters = 1; 37 | 38 | for (int i = 1; i < ITERS; i++) { 39 | iters *= 2; 40 | unsigned int temp = 0; 41 | auto begin = chrono::steady_clock::now(); 42 | 43 | for (unsigned long i = 0; i < iters; i++) 44 | temp = count_ones(i); 45 | 46 | auto end = chrono::steady_clock::now(); 47 | auto time = chrono::duration_cast(end - begin); 48 | 49 | cout << "Elapsed time for (" << iters << " iterations): " 50 | << time.count() << " ms, [" 51 | << (double)time.count() / (double)iters << " ms/iter]" << endl; 52 | } 53 | } 54 | 55 | #elif MODE == 2 56 | 57 | int main() { 58 | int n; 59 | cin >> n; 60 | int stats[n + 1] = {0}; 61 | 62 | unsigned long long power = 1; 63 | for (int i = 0; i < n; i++) 64 | power *= 2; 65 | 66 | for (unsigned long long i = 0; i < power; i++) 67 | stats[count_ones(i)]++; 68 | 69 | for (int i = 0; i <= n; i++) 70 | cout << "with " << i << " ones: " << stats[i] << endl; 71 | } 72 | 73 | #else 74 | 75 | #pragma message "Incorrect configuration" 76 | 77 | #endif -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # `SUAI` C++ Labs 2 | 3 | A repository for learning Git, C/C++ and CMake in SUAI 4 | 5 | [![CMake](https://github.com/cyberpotat42/SUAI-Labs/actions/workflows/cmake.yml/badge.svg)](https://github.com/cyberpotat42/SUAI-Labs/actions/workflows/cmake.yml) 6 | [![CodeQL](https://github.com/cyberpotat42/SUAI-Labs/actions/workflows/codeql.yml/badge.svg)](https://github.com/cyberpotat42/SUAI-Labs/actions/workflows/codeql.yml) 7 | 8 | ## Useful links 9 | 10 | Tasks for laboratory works: [Google Docs](https://docs.google.com/document/d/1xrpJrEPfF8pt5H5FsIfXumKFvwkoEy_wYpgZskR7_lA/) 11 | My formatted Lab tasks: [TASKS.md](TASKS.md) 12 | Formatted reports: [Google Drive](https://drive.google.com/drive/folders/1gj9lEsKWZlvJXa8zt8tXn1vKMhPW0Kju) 13 | 14 | ## Build 15 | 16 | ### Requirements 17 | 18 | - C++17 compiler (GCC, Clang, MSVC) 19 | - CMake 3.12+ (3.20+ recommended) 20 | 21 | Tested on: 22 | 23 | - GCC 12.2.0 (MinGW-w64, Windows 10) 24 | - GCC 9.4.0 (Ubuntu 20.04, WSL2) 25 | 26 | Some labs may require additional libraries / tools: 27 | 28 | - [nlohmann/json](https://github.com/nlohmann/json) (for Lab 17 dop) 29 | - [Graphviz](https://graphviz.org/) (for Lab 20 dop) 30 | 31 | ### Build steps 32 | 33 | 1. Clone the repository 34 | 35 | ```bash 36 | git clone https://github.com/cypotat/cpplabs.git 37 | ``` 38 | 39 | 2. Create a build directory 40 | 41 | ```bash 42 | mkdir build 43 | cd build 44 | ``` 45 | 46 | 3. Generate build files 47 | 48 | ```bash 49 | cmake .. 50 | ``` 51 | 52 | 4. Build the project 53 | 54 | ```bash 55 | cmake --build . 56 | ``` 57 | 58 | If you want to build a specific lab, you can specify the target name 59 | 60 | ```bash 61 | cmake --build . --target Lab_20_dop 62 | ``` 63 | 64 | If you want to build a debug version, you can specify the build type 65 | 66 | ```bash 67 | cmake --build . --config Debug 68 | ``` 69 | 70 | ## Time spent on labs 71 | 72 | [![wakatime](https://wakatime.com/badge/user/44ab2413-c50e-4335-a9cd-7990b8ed9c8b/project/40f4ff13-1639-42ba-a9dd-a503aca9302c.svg)](https://wakatime.com/@CyberPotat42) 73 | -------------------------------------------------------------------------------- /Semester_1/Lab_2/dop.c: -------------------------------------------------------------------------------- 1 | // Ввести строку, проверить нет ли повторяющихся слов 2 | // Вывести их если они есть 3 | // Можно считать, что все слова имеют длину ровно 3 символа 4 | 5 | // Вывести исходную строку без тех слов, которые встречались больше 1 раза 6 | 7 | #include 8 | #include 9 | 10 | #define WORDS_LIMIT 50 11 | #define WORDS_LEN 3 12 | #define STR_LIMIT (WORDS_LEN + 1) * WORDS_LIMIT 13 | 14 | #define len(x) (sizeof(x) / sizeof((x)[0])) 15 | 16 | int strcmp(char s1[], char s2[]) { // аналог функции strcmp в string.h 17 | for (int i = 0;; i++) { 18 | if (s1[i] != s2[i]) return 1; // строки не совпадают 19 | if (s1[i] == '\0') return 0; // строки совпадают 20 | } 21 | } 22 | 23 | void strcopy(char *dest, const char *src) { // аналог функции strcpy в string.h 24 | char *p = dest; 25 | do *p++ = *src; // колпируем каждый символ из src в dest 26 | while (*src++); 27 | } 28 | 29 | void main() { 30 | char words[WORDS_LIMIT][WORDS_LEN + 1] = {0}; 31 | char str[STR_LIMIT] = {0}; 32 | 33 | printf("Enter string of 3-letter words:\n"); 34 | fgets(str, STR_LIMIT, stdin); 35 | printf("\n"); 36 | 37 | int word = 0, k = 0; 38 | for (int i = 0; i <= len(str); i++) 39 | if (str[i] == ' ' || str[i] == '\0' || str[i] == '\n') { 40 | words[word][k] = '\0'; 41 | if (str[i] != '\n') 42 | word++; 43 | else 44 | break; 45 | k = 0; 46 | } else { 47 | words[word][k] = str[i]; 48 | k++; 49 | } 50 | 51 | printf("Without duplicates: "); 52 | for (int w = 0; w <= word + 1; w++) { 53 | int count = 1; 54 | for (int i = 0; i <= word + 1; i++) 55 | if (strcmp(words[i], words[w]) == 0 && strcmp(words[i], "\0") != 0 && 56 | w != i) { 57 | strcopy(words[i], "\0"); 58 | count++; 59 | } 60 | if (count > 1) strcopy(words[w], "\0"); 61 | } 62 | 63 | int flag = 0; 64 | for (int i = 0; i <= word; i++) 65 | if (strcmp(words[i], "\0") != 0) { 66 | printf("%s ", words[i]); 67 | flag = 1; 68 | } 69 | 70 | if (!flag) printf("*all words has duplicates :|\n"); 71 | } -------------------------------------------------------------------------------- /Variants/Lab_4/var_7/dop.c: -------------------------------------------------------------------------------- 1 | // Ввести строку 2 | // Вывести различные слова вместе с количеством их появления в строке 3 | 4 | #include 5 | #include 6 | 7 | #define WORDS_LIMIT 30 8 | #define WORDS_LEN 30 9 | #define STR_LIMIT (WORDS_LEN + 1) * WORDS_LIMIT 10 | 11 | #define len(x) (sizeof(x) / sizeof((x)[0])) 12 | 13 | int strlen(char *str) { 14 | int count = 0; 15 | for (int i = 0; str[i] != '\0'; i++) count++; 16 | return count; 17 | } 18 | 19 | int is_char(char c) { 20 | return ((65<=c && c<=90) 21 | || (97<=c && c<=122) 22 | || (128<=c && c<=175) 23 | || (224<=c && c<=239)); } 24 | 25 | int str_cmp(char s1[], char s2[], int shift) { // аналог функции strcmp в string.h 26 | for (int i = 0; s1[i] != '\0'; i++) { 27 | if (s1[i] != s2[i + shift]) return 1; // строки не совпадают 28 | if (s1[i] == '\0') return 0; // строки совпадают 29 | } } 30 | 31 | void strcopy(char *dest, const char *src) { // аналог функции strcpy в string.h 32 | char *p = dest; 33 | do *p++ = *src; // колпируем каждый символ из src в dest 34 | while (*src++); 35 | } 36 | 37 | void main() { 38 | char words[WORDS_LIMIT][WORDS_LEN + 1] = {0}; 39 | char str[STR_LIMIT] = {0}; 40 | char comp_word[WORDS_LEN] = {0}; 41 | 42 | printf("Enter a string:\n"); 43 | fgets(str, STR_LIMIT, stdin); 44 | 45 | printf("\nEnter word:\n"); 46 | fgets(comp_word, WORDS_LEN, stdin); 47 | comp_word[strlen(comp_word)-1] = '\0'; // ставим конец слова вместо переноса строки 48 | 49 | printf("\nWords:\n--------\n"); 50 | 51 | int word = 0, k = 0; 52 | for (int i = 0; i <= len(str); i++) 53 | if (str[i] == ' ' || str[i] == '\0' || str[i] == '\n') { 54 | words[word][k] = '\0'; 55 | if (str[i] != '\n') word++; else break; 56 | k = 0; 57 | } else if (is_char(str[i])) { words[word][k] = str[i]; k++; } 58 | 59 | for (int w = 0; w <= word; w++) { 60 | if ((strlen(words[w]) - strlen(comp_word)) % 2 == 0) { 61 | int shift = (strlen(words[w]) - strlen(comp_word)) / 2; 62 | if (str_cmp(comp_word, words[w], shift) == 0) 63 | printf("%s\n", words[w]); 64 | } 65 | } 66 | } -------------------------------------------------------------------------------- /Semester_1/Lab_6/dop.c: -------------------------------------------------------------------------------- 1 | // По символьному файлу составить два линейных списка слов, 2 | // упорядоченных по алфавиту и по количеству гласных букв 3 | // вывести оба списка 4 | 5 | // доп: сделать управление функциями 6 | // (0 - выход из цикла, 1 - удаление элемента, 2 - вставка элемента) 7 | 8 | #include "snippets.h" 9 | 10 | void main() { 11 | file *file = read_file("input/test.txt"); 12 | list *words = parse_file(file); 13 | 14 | int running = 1; 15 | while (running) { 16 | int option, id, id2, order; 17 | printf("Enter option >> "); 18 | scanf("%d", &option); 19 | 20 | switch (option) { 21 | case HELP: // working! 22 | printf("\nAvailable commands:\n"); 23 | printf( 24 | "0 - EXIT\n1 - HELP\n2 - REMOVE\n3 - INSERT\n4 - SORT\n5 - " 25 | "SORTx2\n9 - PRINT\n\n"); 26 | break; 27 | 28 | case EXIT: // working! 29 | running = 0; 30 | break; 31 | 32 | case REMOVE: // working! 33 | printf("Enter node index to delete: "); 34 | scanf("%d", &id); 35 | remove_node(words, id); 36 | break; 37 | 38 | case INSERT: // working! 39 | printf("Enter index: "); 40 | scanf("%d", &id); 41 | printf("Enter word: "); 42 | char *str = read_str(); 43 | node *curr = get_node(words, id); 44 | insert(words, curr, str); 45 | break; 46 | 47 | case SORT: // working! 48 | printf("Enter sort type and order: "); // see type in snippets 49 | scanf("%d %d", &id, &order); 50 | sort_list(words, id, order); 51 | break; 52 | 53 | case SORTx2: // working! 54 | printf("Enter sort types and order: "); 55 | scanf("%d %d %d", &id, &id2, &order); 56 | double_sort(words, id, id2, order); 57 | break; 58 | 59 | case PRINT: // working! 60 | print_list(words); 61 | break; 62 | 63 | default: 64 | printf("Unknown command: %d !!!\n", option); 65 | printf("Enter 1 to get help\n"); 66 | break; 67 | } 68 | } 69 | 70 | destroy(words); 71 | } -------------------------------------------------------------------------------- /Semester_2/Lab_9/dop/fractions.cpp: -------------------------------------------------------------------------------- 1 | #include "fractions.h" 2 | 3 | #include 4 | #include 5 | 6 | long long gcd(long long a, long long b) { 7 | if (a == 0) return (b > 0) ? b : -b; 8 | return gcd(b % a, a); 9 | } 10 | 11 | void simplify_fraction(fraction *f) { 12 | long long factor = gcd(f->koeff, f->divider); 13 | f->koeff /= factor; 14 | f->divider /= factor; 15 | } 16 | 17 | fraction *new_fraction() { 18 | fraction *temp = (fraction *)malloc(sizeof(fraction)); 19 | temp->koeff = 0; 20 | temp->divider = 1; 21 | return temp; 22 | } 23 | 24 | fraction *new_fraction(long long a) { 25 | fraction *temp = (fraction *)malloc(sizeof(fraction)); 26 | temp->koeff = a; 27 | temp->divider = 1; 28 | return temp; 29 | } 30 | 31 | fraction *new_fraction(long long k, long long d) { 32 | fraction *temp = (fraction *)malloc(sizeof(fraction)); 33 | temp->koeff = k; 34 | temp->divider = (d == 0) ? 1 : d; 35 | simplify_fraction(temp); 36 | return temp; 37 | } 38 | 39 | void set_fraction(fraction *f, long long k, long long d) { 40 | f->koeff = k; 41 | f->divider = (d == 0) ? 1 : d; 42 | simplify_fraction(f); 43 | } 44 | 45 | void set_fraction(fraction *f, long long k) { 46 | f->koeff = k; 47 | f->divider = 1; 48 | } 49 | 50 | void sum_fractions(fraction *x, fraction *a, fraction *b) { 51 | x->divider = a->divider * b->divider; 52 | x->koeff = a->koeff * b->divider + b->koeff * a->divider; 53 | simplify_fraction(x); 54 | } 55 | 56 | void sum_fractions(fraction *a, fraction *b) { 57 | long long ak = a->koeff, ad = a->divider; 58 | a->divider = ad * b->divider; 59 | a->koeff = ak * b->divider + b->koeff * ad; 60 | simplify_fraction(a); 61 | } 62 | 63 | void multiply_fractions(fraction *f, fraction *a, fraction *b) { 64 | f->koeff = a->koeff * b->koeff; 65 | f->divider = a->divider * b->divider; 66 | simplify_fraction(f); 67 | } 68 | 69 | void sum_multiply_fractions(fraction *f, fraction *a, fraction *b) { 70 | fraction temp; 71 | multiply_fractions(&temp, a, b); 72 | sum_fractions(f, &temp); 73 | } 74 | 75 | void print_fraction(fraction *f) { 76 | printf("%lld / %lld\n", f->koeff, f->divider); 77 | } -------------------------------------------------------------------------------- /Semester_2/Lab_9/base/fractions.cpp: -------------------------------------------------------------------------------- 1 | #include "fractions.h" 2 | 3 | #include 4 | #include 5 | 6 | long long gcd(long long a, long long b) { 7 | if (a == 0) return (b > 0) ? b : -b; 8 | return gcd(b % a, a); 9 | } 10 | 11 | void simplify_fraction(fraction *f) { 12 | long long factor = gcd(f->koeff, f->divider); 13 | f->koeff /= factor; 14 | f->divider /= factor; 15 | } 16 | 17 | fraction *new_fraction() { 18 | fraction *temp = (fraction *)malloc(sizeof(fraction)); 19 | temp->koeff = 0; 20 | temp->divider = 1; 21 | return temp; 22 | } 23 | 24 | fraction *new_fraction(long long a) { 25 | fraction *temp = (fraction *)malloc(sizeof(fraction)); 26 | temp->koeff = a; 27 | temp->divider = 1; 28 | return temp; 29 | } 30 | 31 | fraction *new_fraction(long long k, long long d) { 32 | fraction *temp = (fraction *)malloc(sizeof(fraction)); 33 | temp->koeff = k; 34 | temp->divider = (d == 0) ? 1 : d; 35 | simplify_fraction(temp); 36 | return temp; 37 | } 38 | 39 | void set_fraction(fraction *f, long long k, long long d) { 40 | f->koeff = k; 41 | f->divider = (d == 0) ? 1 : d; 42 | simplify_fraction(f); 43 | } 44 | 45 | void set_fraction(fraction *f, long long k) { 46 | f->koeff = k; 47 | f->divider = 1; 48 | } 49 | 50 | void sum_fractions(fraction *x, fraction *a, fraction *b) { 51 | x->divider = a->divider * b->divider; 52 | x->koeff = a->koeff * b->divider + b->koeff * a->divider; 53 | simplify_fraction(x); 54 | } 55 | 56 | void sum_fractions(fraction *a, fraction *b) { 57 | long long ak = a->koeff, ad = a->divider; 58 | a->divider = ad * b->divider; 59 | a->koeff = ak * b->divider + b->koeff * ad; 60 | simplify_fraction(a); 61 | } 62 | 63 | void multiply_fractions(fraction *f, fraction *a, fraction *b) { 64 | f->koeff = a->koeff * b->koeff; 65 | f->divider = a->divider * b->divider; 66 | simplify_fraction(f); 67 | } 68 | 69 | void sum_multiply_fractions(fraction *f, fraction *a, fraction *b) { 70 | fraction temp; 71 | multiply_fractions(&temp, a, b); 72 | sum_fractions(f, &temp); 73 | } 74 | 75 | void print_fraction(fraction *f) { 76 | printf("%lld / %lld\n", f->koeff, f->divider); 77 | } -------------------------------------------------------------------------------- /Variants/Lab_18/var_2/database.cpp: -------------------------------------------------------------------------------- 1 | #include "database.h" 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | using namespace std; 9 | 10 | // Person 11 | 12 | Person::Person() 13 | : name("Rayan"), 14 | surname("Gosling"), 15 | year(1980), 16 | gender(0), 17 | passport(420069){}; 18 | 19 | Person::Person(string name, string surname, int year, bool gender, 20 | int passport) { 21 | this->name = name; 22 | this->surname = surname; 23 | this->year = year; 24 | this->gender = gender; 25 | this->passport = passport; 26 | } 27 | 28 | ostream &operator<<(ostream &out, Person &p) { 29 | out << p.name << " " << p.surname << " " << p.year << " " << p.gender << " " 30 | << p.passport << endl; 31 | return out; 32 | } 33 | 34 | bool Person::operator==(const Person &p1) { 35 | return (this->name == p1.name) && (this->surname == p1.surname) && 36 | (this->year == p1.year) && (this->gender == p1.gender) && 37 | (this->passport == p1.passport); 38 | } 39 | 40 | // Database 41 | 42 | void Database::load(const string &filename) { 43 | ifstream fin(filename); 44 | while (!fin.eof()) { 45 | string name, surname; 46 | int year, passport; 47 | bool gender; 48 | fin >> name >> surname >> year >> gender >> passport; 49 | db.push_back(Person(name, surname, year, gender, passport)); 50 | } 51 | } 52 | 53 | void Database::save(const string &filename) { 54 | ofstream fout(filename); 55 | for (int i = 0; i < db.size(); i++) { 56 | fout << db[i]; 57 | } 58 | } 59 | 60 | void Database::add(const Person &p) { db.push_back(p); } 61 | 62 | ofstream &operator<<(ofstream &out, Database &d) { 63 | for (int i = 0; i < d.db.size(); i++) { 64 | out << d.db[i]; 65 | } 66 | return out; 67 | } 68 | 69 | void Database::erase(const Person &p) { 70 | for (int i = 0; i < db.size(); i++) { 71 | if (db[i] == p) { 72 | db.erase(db.begin() + i); 73 | } 74 | } 75 | } 76 | 77 | ostream &operator<<(ostream &out, Database &d) { 78 | for (int i = 0; i < d.db.size(); i++) { 79 | out << d.db[i]; 80 | } 81 | return out; 82 | } 83 | -------------------------------------------------------------------------------- /Semester_2/Lab_12/dop/HugeInt.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | using namespace std; 10 | 11 | class HugeInt { 12 | public: 13 | HugeInt(string str = "0", int digits_count = 40); 14 | HugeInt(const HugeInt &temp, bool invert = false); 15 | HugeInt(long long n); 16 | 17 | void set(string str); 18 | bool is_zero(); 19 | bool has_minus(); 20 | string to_str(); 21 | void remove_leading_zeros(); 22 | 23 | HugeInt &operator=(const HugeInt &temp); 24 | HugeInt &operator=(const long long &temp); 25 | HugeInt &operator=(const string &str); 26 | 27 | friend istream &operator>>(istream &in, HugeInt &a); 28 | friend ifstream &operator>>(ifstream &in, HugeInt &a); 29 | 30 | friend ostream &operator<<(ostream &out, const HugeInt &a); 31 | friend ofstream &operator<<(ofstream &out, HugeInt &a); 32 | 33 | friend bool operator==(const HugeInt &a, const HugeInt &b); 34 | friend bool operator!=(const HugeInt &a, const HugeInt &b); 35 | 36 | friend bool operator>(const HugeInt &a, const HugeInt &b); 37 | friend bool operator>=(const HugeInt &a, const HugeInt &b); 38 | 39 | friend bool operator<(const HugeInt &a, const HugeInt &b); 40 | friend bool operator<=(const HugeInt &a, const HugeInt &b); 41 | 42 | // friend HugeInt operator+(const HugeInt &a, const HugeInt &b); 43 | // friend HugeInt operator-(const HugeInt &a, const HugeInt &b); 44 | 45 | const HugeInt operator-(); 46 | 47 | friend HugeInt operator+(HugeInt a, const HugeInt &b); 48 | // friend HugeInt operator+(HugeInt &a, HugeInt &b); 49 | friend HugeInt operator+(const HugeInt &a, long long value); 50 | friend HugeInt operator+(long long value, const HugeInt &a); 51 | 52 | friend HugeInt operator-(HugeInt left, const HugeInt &right); 53 | // friend HugeInt operator-(HugeInt &a, HugeInt &b); 54 | friend HugeInt operator-(const HugeInt &a, long long value); 55 | friend HugeInt operator-(long long value, const HugeInt &a); 56 | 57 | private: 58 | vector array; 59 | unsigned int digit_count; 60 | unsigned int capacity; 61 | bool minus = false; 62 | }; -------------------------------------------------------------------------------- /Semester_1/Lab_3/dop.c: -------------------------------------------------------------------------------- 1 | // Написать функцию, которая вставляет в массив элемент 2 | // с заданным индексом и заданным значением 3 | // Лишний элемент должен пропасть 4 | 5 | // доп: Написать функцию, которая вставляет в массив 0 после максимального 6 | // элемента, размер массива должен увеличиться 7 | 8 | #include 9 | #include 10 | #include 11 | 12 | #define len(x) (sizeof(x) / sizeof((x)[0])) 13 | int size; // глобальная переменная 14 | 15 | #define ARR_INIT 0 16 | // 0 - ввод массива пользователем 17 | // 1 - генерация массива {0 .. N-1} 18 | // 2 - генерация случайного массива 19 | 20 | void insert(int size, int* arr, int index, int value) { 21 | if (index >= 0 && index < size) { 22 | for (int i = size - 1; i > index; i--) arr[i] = arr[i - 1]; 23 | arr[index] = value; 24 | } else { 25 | printf("Index out of range\n"); 26 | exit(EXIT_FAILURE); 27 | } 28 | } 29 | 30 | void arr_init(int length, int* arr) { 31 | switch (ARR_INIT) { 32 | case 0: 33 | printf("Enter %d integers:\n", length); 34 | for (int i = 0; i < length; i++) scanf("%d", &arr[i]); 35 | printf("\n"); 36 | break; 37 | case 1: 38 | for (int i = 0; i < size; i++) arr[i] = i; 39 | break; 40 | case 2: 41 | srand(time(NULL)); // инициализируем генератор случайных чисел 42 | for (int i = 0; i < size; i++) arr[i] = rand() % 100; 43 | break; 44 | default: 45 | printf("Invalid Configuration\nChange ARR_INIT to correct"); 46 | exit(EXIT_FAILURE); 47 | } 48 | } 49 | 50 | void main() { 51 | printf("Input array size: "); 52 | scanf("%d", &size); 53 | printf("\n"); 54 | 55 | int arr[size]; 56 | arr_init(len(arr), arr); // инициализируем массив 57 | 58 | printf("Original array:\n[ "); 59 | for (int i = 0; i < size; i++) printf("%d ", arr[i]); 60 | printf("]\n"); 61 | 62 | int max = 0; 63 | for (int i = 0; i < size; i++) 64 | if (arr[i] > max) max = arr[i]; 65 | 66 | printf("\nArray after insert:\n[ "); 67 | for (int i = 0; i < size; i++) 68 | if (arr[i] == max) 69 | printf("%d 0 ", arr[i]); 70 | else 71 | printf("%d ", arr[i]); 72 | printf("]\n"); 73 | } -------------------------------------------------------------------------------- /Semester_2/Lab_6/dop/main.cpp: -------------------------------------------------------------------------------- 1 | // По символьному файлу составить два линейных списка слов, 2 | // упорядоченных по алфавиту и по количеству гласных букв 3 | // вывести оба списка 4 | 5 | // доп: сделать управление функциями 6 | // (0 - выход из цикла, 1 - удаление элемента, 2 - вставка элемента) 7 | 8 | #include "snippets.h" 9 | 10 | int main() { 11 | file *file = read_file("input.txt"); 12 | list *words = parse_file(file); 13 | 14 | int running = 1; 15 | while (running) { 16 | int option, id, id2, order; 17 | char *str; 18 | node *curr; 19 | 20 | printf("Enter option >> "); 21 | scanf("%d", &option); 22 | 23 | switch (option) { 24 | case HELP: // working! 25 | printf("\nAvailable commands:\n"); 26 | printf( 27 | "0 - EXIT\n1 - HELP\n2 - REMOVE\n3 - INSERT\n4 - SORT\n5 - " 28 | "SORTx2\n9 - PRINT\n\n"); 29 | break; 30 | 31 | case EXIT: // working! 32 | running = 0; 33 | break; 34 | 35 | case REMOVE: // working! 36 | printf("Enter node index to delete: "); 37 | scanf("%d", &id); 38 | remove_node(words, id); 39 | break; 40 | 41 | case INSERT: // working! 42 | printf("Enter index: "); 43 | scanf("%d", &id); 44 | printf("Enter word: "); 45 | str = read_str(); 46 | curr = get_node(words, id); 47 | insert(words, curr, str); 48 | break; 49 | 50 | case SORT: // working! 51 | printf("Enter sort type and order: "); // see type in snippets 52 | scanf("%d %d", &id, &order); 53 | sort_list(words, id, order); 54 | break; 55 | 56 | case SORTx2: // working! 57 | printf("Enter sort types and order: "); 58 | scanf("%d %d %d", &id, &id2, &order); 59 | double_sort(words, id, id2, order); 60 | break; 61 | 62 | case PRINT: // working! 63 | print_list(words); 64 | break; 65 | 66 | default: 67 | printf("Unknown command: %d !!!\n", option); 68 | printf("Enter 1 to get help\n"); 69 | break; 70 | } 71 | } 72 | 73 | destroy(words); 74 | } -------------------------------------------------------------------------------- /Semester_3/Lab_18/dop/input.txt: -------------------------------------------------------------------------------- 1 | somebody once told me the world is gonna roll me 2 | i aint the sharpest tool in the shed 3 | she was looking kind of dumb with her finger and her thumb 4 | in the shape of an l on her forehead 5 | well the years start coming and they dont stop coming 6 | fed to the rules and i hit the ground running 7 | didnt make sense not to live for fun 8 | your brain gets smart but your head gets dumb 9 | so much to do so much to see 10 | so whats wrong with taking the back streets 11 | youll never know if you dont go 12 | youll never shine if you dont glow 13 | hey now youre an all-star get your game on go play 14 | hey now youre a rock star get the show on get paid 15 | and all that glitters is gold 16 | only shooting stars break the mold 17 | its a cool place and they say it gets colder 18 | youre bundled up now wait til you get older 19 | but the meteor men beg to differ 20 | judging by the hole in the satellite picture 21 | the ice we skate is getting pretty thin 22 | the waters getting warm so you might as well swim 23 | my worlds on fire how about yours 24 | thats the way i like it and ill never get bored 25 | hey now youre an all-star get your game on go play 26 | hey now youre a rock star get the show on get paid 27 | all that glitters is gold 28 | only shooting stars break the mold 29 | hey now youre an all-star get your game on go play 30 | hey now youre a rock star get the show on get paid 31 | and all that glitters is gold 32 | only shooting stars 33 | somebody once asked could i spare some change for gas 34 | i need to get myself away from this place 35 | i said yup what a concept 36 | i could use a little fuel myself 37 | and we could all use a little change 38 | well the years start coming and they dont stop coming 39 | fed to the rules and i hit the ground running 40 | didnt make sense not to live for fun 41 | your brain gets smart but your head gets dumb 42 | so much to do so much to see 43 | so whats wrong with taking the back streets? 44 | youll never know if you dont go go 45 | youll never shine if you dont glow 46 | hey now youre an all-star get your game on go play 47 | hey now youre a rock star get the show on get paid 48 | and all that glitters is gold 49 | only shooting stars break the mold 50 | and all that glitters is gold 51 | only shooting stars break the mold -------------------------------------------------------------------------------- /Variants/Lab_9/var_11/sequence.cpp: -------------------------------------------------------------------------------- 1 | #include "sequence.h" 2 | 3 | // подсчет количества значащих бит в числе 4 | int count_bits(unsigned long long N) { 5 | int i = 2, bits = 1; 6 | // определяем минимальную но достаточную.. 7 | // степень двойки (= кол-во бит) 8 | while (N >= i) { 9 | // увеличиваем количество бит 10 | bits += 1; 11 | // максимально возможное число при данном 12 | // количестве бит теперь в 2 раза больше 13 | i *= 2; 14 | } 15 | return bits; 16 | } 17 | 18 | // конвертация uint64 в массив бит 19 | char *dtoab(unsigned long long N) { 20 | // определяем количество бит в числе 21 | int len = count_bits(N); 22 | // создаем массив для хранения бит 23 | char *arr = (char *)malloc((len + 1) * sizeof(char)); 24 | 25 | // записываем биты в массив (в правильном порядке) 26 | // слева направо, от старшего бита к младшему 27 | for (int i = 0; i < len; i++) { 28 | // записываем бит как char ('0' / '1') 29 | arr[len - i - 1] = '0' + (N & 1); 30 | // сдвигаем чтобы получить следующий бит 31 | N = N >> 1; 32 | } 33 | // добавляем в конец \0 и выходим 34 | arr[len] = 0; 35 | return arr; 36 | } 37 | 38 | // нахождение длины максимальной 39 | // последовательности из единиц 40 | int count_max_ones(unsigned long long N) { 41 | // преобразуем число в двоичную строку 42 | char *str = dtoab(N); 43 | int max = 0, current = 0; 44 | 45 | // проходимся по всем битам числа 46 | for (int i = 0; str[i] != 0; i++) { 47 | current = str[i] == '1' ? current + 1 : 0; 48 | // обновляем максимальную длину 49 | max = current > max ? current : max; 50 | } 51 | return max; 52 | } 53 | 54 | // нахождение количества серий 55 | // из единиц длинной больше 2 56 | int count_ones_series(unsigned long long N) { 57 | // преобразуем число в двоичную строку 58 | char *str = dtoab(N); 59 | int count = 0, current = 0; 60 | 61 | // проходим по всем битам числа 62 | for (int i = 0; str[i] != 0; i++) { 63 | if (str[i] == '1') { 64 | current++; 65 | } else { 66 | // увеличиваем счетчик если последовательность > 2 67 | if (current > 2) count++; 68 | // обнуляем счетчик 69 | current = 0; 70 | } 71 | } 72 | // не забываем про младшие биты 73 | if (current > 2) count++; 74 | return count; 75 | } -------------------------------------------------------------------------------- /Semester_1/Lab_4/dop.c: -------------------------------------------------------------------------------- 1 | // Ввести строку, вывести различные слова 2 | // вместе с количеством их появления в строке 3 | 4 | // доп: Вывести их по алфавиту 5 | 6 | #include 7 | #include 8 | 9 | #define WORDS_LIMIT 50 10 | #define WORDS_LEN 30 11 | #define STR_LIMIT (WORDS_LEN + 1) * WORDS_LIMIT 12 | 13 | #define len(x) (sizeof(x) / sizeof((x)[0])) 14 | 15 | int strcmp(const char *s1, const char *s2) { 16 | unsigned char c1, c2; 17 | while ((c1 = *s1++) == (c2 = *s2++)) 18 | if (c1 == '\0') return 0; 19 | return c1 - c2; 20 | } 21 | 22 | void strcopy(char *dest, const char *src) { 23 | char *p = dest; 24 | do *p++ = *src; 25 | while (*src++); 26 | } 27 | 28 | void main() { 29 | char words[WORDS_LIMIT][WORDS_LEN + 1] = {'\0'}; 30 | char str[STR_LIMIT] = {'\0'}; 31 | 32 | printf("Enter a string:\n"); 33 | fgets(str, STR_LIMIT, stdin); 34 | printf("\nWords:\n--------\n"); 35 | 36 | // splitting into words 37 | int word = 0, k = 0; 38 | for (int i = 0; i <= len(str); i++) 39 | if (str[i] == ' ' || str[i] == '\0' || str[i] == '\n') { 40 | words[word][k] = '\0'; 41 | word++; 42 | k = 0; 43 | if (str[i] == '\n') break; 44 | } else { 45 | words[word][k] = str[i]; 46 | k++; 47 | } 48 | 49 | // counting words 50 | int curr_w = 0, flag = 0; 51 | int counts[word]; 52 | for (int w = 0; w < word; w++) { 53 | int count = 1; 54 | for (int i = 0; i < word; i++) 55 | if (strcmp(words[i], words[w]) == 0 && w != i && 56 | strcmp(words[i], "\0") != 0) { 57 | strcopy(words[i], "\0"); 58 | count++; 59 | } 60 | if (strcmp(words[w], "\0") != 0) counts[curr_w] = count; 61 | curr_w++; 62 | } 63 | 64 | // sorting arrays 65 | char temp[WORDS_LEN]; 66 | int t = 0; 67 | for (int i = 0; i <= curr_w; i++) 68 | for (int j = i + 1; j <= curr_w; j++) 69 | if (strcmp(words[i], words[j]) > 0) { 70 | strcopy(temp, words[i]); 71 | strcopy(words[i], words[j]); 72 | strcopy(words[j], temp); 73 | t = counts[i]; 74 | counts[i] = counts[j]; 75 | counts[j] = t; 76 | } 77 | 78 | for (int i = 0; i <= curr_w; i++) 79 | if (strcmp(words[i], "\0") != 0) 80 | printf("%s - %d times\n", words[i], counts[i]); 81 | } -------------------------------------------------------------------------------- /Variants/Lab_5/var_9/dop.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define S 100 5 | #define W 10 6 | 7 | int strCompare(char *s1, char *s2) 8 | { 9 | while ((*s1 == *s2) && (*s1 != 0)) 10 | { 11 | s1++; 12 | s2++; 13 | } 14 | return *s1 - *s2; 15 | } 16 | 17 | void delN(char *s) // удаляем перенос строки в конце слова 18 | { 19 | int i = 0; 20 | while ((s[i] != '\n') && (s[i] != 0)) 21 | i++; 22 | s[i] = 0; // заменяем на символ конца строки 23 | } 24 | 25 | 26 | int main() 27 | { 28 | printf("Enter first word: "); 29 | char firstWord[W] = {0}; 30 | fgets(firstWord, W, stdin); 31 | delN(firstWord); 32 | 33 | int lenW1 = 0; 34 | while (firstWord[lenW1] != 0) 35 | lenW1++; 36 | 37 | printf("\n"); 38 | 39 | printf("Enter second word: "); 40 | char secondWord[W] = {0}; 41 | fgets(secondWord, W, stdin); 42 | delN(secondWord); 43 | 44 | int lenW2 = 0; 45 | while (secondWord[lenW2] != 0) 46 | lenW2++; 47 | 48 | printf("\n"); 49 | 50 | printf("Enter string: "); 51 | char str[S] = {0}; 52 | fgets(str, S, stdin); 53 | delN(str); 54 | 55 | int lenStr = 0; 56 | while (str[lenStr] != 0) 57 | lenStr++; 58 | 59 | int wordsCount = 0; 60 | char **words = (char **)malloc(sizeof(char *) * (wordsCount + 1)); 61 | 62 | int tmp = 0; 63 | words[wordsCount] = (char *)malloc(sizeof(char) * (tmp + 1)); 64 | for (int i = 0; i < lenStr; i++) 65 | { 66 | if (str[i] != ' ') 67 | { 68 | words[wordsCount][tmp] = str[i]; 69 | tmp++; 70 | char *temp = words[wordsCount]; 71 | temp = (char *)realloc(temp, sizeof(char) * (tmp + 1)); 72 | words[wordsCount] = temp; 73 | 74 | if (i == lenStr - 1) 75 | goto endwords; 76 | } 77 | else if (str[i] == ' ') 78 | { 79 | endwords: 80 | words[wordsCount][tmp] = 0; 81 | tmp = 0; 82 | char *temp_word = words[wordsCount]; 83 | wordsCount++; 84 | words = (char **)realloc(words, sizeof(char *) * (wordsCount + 1)); 85 | words[wordsCount] = (char *)malloc(sizeof(char) * (tmp + 1)); 86 | } 87 | } 88 | 89 | for (int i = 0; i < wordsCount; i++) 90 | { 91 | printf("%s ", words[i]); 92 | if (strCompare(words[i], firstWord) == 0) 93 | printf("%s ", secondWord); 94 | } 95 | 96 | return 0; 97 | } -------------------------------------------------------------------------------- /Variants/Lab_10/var_7/input.txt: -------------------------------------------------------------------------------- 1 | Somebody once told me the world is gonna roll me 2 | I ain't the sharpest tool in the shed 3 | She was looking kind of dumb with her finger and her thumb 4 | In the shape of an "L" on her forehead 5 | Well the years start coming and they don't stop coming 6 | Fed to the rules and I hit the ground running 7 | Didn't make sense not to live for fun 8 | Your brain gets smart but your head gets dumb 9 | So much to do, so much to see 10 | So what's wrong with taking the back streets? 11 | You'll never know if you don't go 12 | You'll never shine if you don't glow 13 | Hey now, you're an all-star, get your game on, go play 14 | Hey now, you're a rock star, get the show on, get paid 15 | And all that glitters is gold 16 | Only shooting stars break the mold 17 | It's a cool place and they say it gets colder 18 | You're bundled up now, wait 'til you get older 19 | But the meteor men beg to differ 20 | Judging by the hole in the satellite picture 21 | The ice we skate is getting pretty thin 22 | The water's getting warm so you might as well swim 23 | My world's on fire, how about yours? 24 | That's the way I like it and I'll never get bored 25 | Hey now, you're an all-star, get your game on, go play 26 | Hey now, you're a rock star, get the show on, get paid 27 | All that glitters is gold 28 | Only shooting stars break the mold 29 | Hey now, you're an all-star, get your game on, go play 30 | Hey now, you're a rock star, get the show, on get paid 31 | And all that glitters is gold 32 | Only shooting stars 33 | Somebody once asked could I spare some change for gas? 34 | I need to get myself away from this place 35 | I said, "Yup" what a concept 36 | I could use a little fuel myself 37 | And we could all use a little change 38 | Well, the years start coming and they don't stop coming 39 | Fed to the rules and I hit the ground running 40 | Didn't make sense not to live for fun 41 | Your brain gets smart but your head gets dumb 42 | So much to do, so much to see 43 | So what's wrong with taking the back streets? 44 | You'll never know if you don't go (go!) 45 | You'll never shine if you don't glow 46 | Hey now, you're an all-star, get your game on, go play 47 | Hey now, you're a rock star, get the show on, get paid 48 | And all that glitters is gold 49 | Only shooting stars break the mold 50 | And all that glitters is gold 51 | Only shooting stars break the mold -------------------------------------------------------------------------------- /Variants/Lab_10/var_7/output.txt: -------------------------------------------------------------------------------- 1 | Shrek once told me the world is gonna fuck me 2 | You ain't the sharpest tool in the shed 3 | Fiona was looking kind of dumb with her finger and her thumb 4 | Youn the shape of an LOL on her forehead 5 | Well the years start coming and they don't stop coming 6 | Fed to the rules and You hit the ground running 7 | Didn't make sense not to live for fun 8 | Your brain gets smart but your head gets dumb 9 | So much to do, so much to see 10 | So what's wrong with taking the back streets? 11 | You'll always know if you don't go 12 | You'll always shine if you don't glow 13 | Hey now, you're an all-star, get your game on, go play 14 | Hey now, you're a rock star, get the show on, get paid 15 | And all that glitters is gold 16 | Only shooting guns break the mold 17 | Yout's a cool place and they say it gets colder 18 | You're bundled up now, wait 'til you get older 19 | But the meteor men beg to differ 20 | Judging by the hole in the satellite picture 21 | The ice we skate is getting pretty thin 22 | The water's getting warm so you might as well swim 23 | My world's on fire, how about yours? 24 | That's the way You like it and You'll always get bored 25 | Hey now, you're an all-star, get your game on, go play 26 | Hey now, you're a rock star, get the show on, get paid 27 | All that glitters is gold 28 | Only shooting guns break the mold 29 | Hey now, you're an all-star, get your game on, go play 30 | Hey now, you're a rock star, get the show, on get paid 31 | And all that glitters is gold 32 | Only shooting guns 33 | Shrek once asked could You spare some change for gas? 34 | You need to get myself away from this place 35 | You said, "Yup" what a concept 36 | You could use a little fuel myself 37 | And we could all use a little change 38 | Well, the years start coming and they don't stop coming 39 | Fed to the rules and You hit the ground running 40 | Didn't make sense not to live for fun 41 | Your brain gets smart but your head gets dumb 42 | So much to do, so much to see 43 | So what's wrong with taking the back streets? 44 | You'll always know if you don't go (go!) 45 | You'll always shine if you don't glow 46 | Hey now, you're an all-star, get your game on, go play 47 | Hey now, you're a rock star, get the show on, get paid 48 | And all that glitters is gold 49 | Only shooting guns break the mold 50 | And all that glitters is gold 51 | Only shooting guns break the mold --------------------------------------------------------------------------------