From 83ca1d73d598be7c64cb66d7184e494ec0e471c1 Mon Sep 17 00:00:00 2001 From: Nicolay Petrov Date: Tue, 25 Nov 2025 23:04:50 +0500 Subject: [PATCH 01/34] add (solution): add char_changer task --- 01_week/tasks/addition/addition.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/01_week/tasks/addition/addition.cpp b/01_week/tasks/addition/addition.cpp index 92872802..2263454b 100644 --- a/01_week/tasks/addition/addition.cpp +++ b/01_week/tasks/addition/addition.cpp @@ -3,5 +3,5 @@ int64_t Addition(int a, int b) { - throw std::runtime_error{"Not implemented"}; + return a+b; } \ No newline at end of file From a133a8db19726a404646a95ae73a69ca4f73bef2 Mon Sep 17 00:00:00 2001 From: Nicolay Petrov Date: Tue, 25 Nov 2025 23:07:31 +0500 Subject: [PATCH 02/34] add (solution): add char_changer task --- 01_week/tasks/char_changer/char_changer.cpp | 52 ++++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/01_week/tasks/char_changer/char_changer.cpp b/01_week/tasks/char_changer/char_changer.cpp index 3a7344d9..115c5a08 100644 --- a/01_week/tasks/char_changer/char_changer.cpp +++ b/01_week/tasks/char_changer/char_changer.cpp @@ -3,5 +3,55 @@ size_t CharChanger(char array[], size_t size, char delimiter = ' ') { - throw std::runtime_error{"Not implemented"}; + if (size == 0) return 0; + + char* pread = array; + char* pwrite = array; + + while (*pread != '\0' && (pread - array) < static_cast(size - 1)) { + char tek_char = *pread; + int repeat_count = 1; + + // Ограничиваем подсчет повторений границами массива + while (repeat_count < static_cast(size - (pread - array)) && + pread[repeat_count] == tek_char) { + repeat_count++; + } + + if (tek_char == ' ') { + *pwrite = delimiter; + pwrite++; + pread += repeat_count; + continue; + } + + char temp; + if (std::isdigit(tek_char)) { + temp = '*'; + } else if (std::isupper(tek_char)) { + temp = tek_char; + } else if (std::islower(tek_char)) { + temp = std::toupper(tek_char); + } else { + temp = '_'; + } + + *pwrite = temp; + pwrite++; + + if (repeat_count > 1) { + if (repeat_count >= 10) { + *pwrite = '0'; + pwrite++; + } else { + *pwrite = '0' + repeat_count; + pwrite++; + } + } + + pread += repeat_count; + } + + *pwrite = '\0'; + return pwrite - array; } From 8c8b1df7b978646fce8001a9bc0ba2458d5453b0 Mon Sep 17 00:00:00 2001 From: Nicolay Petrov Date: Wed, 26 Nov 2025 20:19:56 +0500 Subject: [PATCH 03/34] add (solution): add addition2 task --- 01_week/tasks/addition/addition.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/01_week/tasks/addition/addition.cpp b/01_week/tasks/addition/addition.cpp index 2263454b..05ffd7d1 100644 --- a/01_week/tasks/addition/addition.cpp +++ b/01_week/tasks/addition/addition.cpp @@ -3,5 +3,5 @@ int64_t Addition(int a, int b) { - return a+b; + return static_cast(a) + static_cast(b); } \ No newline at end of file From ae14a5a60032b24478d092a4b81e1212976015be Mon Sep 17 00:00:00 2001 From: Nicolay Petrov Date: Wed, 26 Nov 2025 20:24:19 +0500 Subject: [PATCH 04/34] add (solution): add check_flags task --- 01_week/tasks/check_flags/check_flags.cpp | 25 +++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/01_week/tasks/check_flags/check_flags.cpp b/01_week/tasks/check_flags/check_flags.cpp index 75e7c652..93e28372 100644 --- a/01_week/tasks/check_flags/check_flags.cpp +++ b/01_week/tasks/check_flags/check_flags.cpp @@ -1,6 +1,6 @@ #include #include - +#include enum class CheckFlags : uint8_t { NONE = 0, @@ -14,5 +14,26 @@ enum class CheckFlags : uint8_t { }; void PrintCheckFlags(CheckFlags flags) { - throw std::runtime_error{"Not implemented"}; + uint8_t value = static_cast(flags); + + // Проверяем, что значение находится в допустимом диапазоне + if (value > static_cast(CheckFlags::ALL)) { + return; // значение вне диапазона - ничего не выводим + } + + if (value == 0) { + std::cout << "[]"; // нет флагов - выводим [] + return; + } + + std::cout << "["; + + if (value & 1) std::cout << "TIME"; + if (value & 2) std::cout << (value & 1 ? ",DATE" : "DATE"); + if (value & 4) std::cout << (value & 3 ? ",USER" : "USER"); + if (value & 8) std::cout << (value & 7 ? ",CERT" : "CERT"); + if (value & 16) std::cout << (value & 15 ? ",KEYS" : "KEYS"); + if (value & 32) std::cout << (value & 31 ? ",DEST" : "DEST"); + + std::cout << "]"; } From 4c4bbdf868e9e88cf519a3be1dec74cd091dfb8b Mon Sep 17 00:00:00 2001 From: Nicolay Petrov Date: Wed, 26 Nov 2025 20:27:18 +0500 Subject: [PATCH 05/34] add (solution): add length_lit task --- 01_week/tasks/length_lit/length_lit.cpp | 47 +++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/01_week/tasks/length_lit/length_lit.cpp b/01_week/tasks/length_lit/length_lit.cpp index e69de29b..c8a43c2c 100644 --- a/01_week/tasks/length_lit/length_lit.cpp +++ b/01_week/tasks/length_lit/length_lit.cpp @@ -0,0 +1,47 @@ +constexpr double operator""_ft_to_m(long double feet) { + return feet * 0.3048; +} + +constexpr double operator""_in_to_m(long double inches) { + return inches * 0.0254; +} + +constexpr double operator""_cm_to_m(long double centimeters) { + return centimeters * 0.01; +} + +constexpr double operator""_m_to_ft(long double meters) { + return meters / 0.3048; +} + +constexpr double operator""_m_to_in(long double meters) { + return meters / 0.0254; +} + +constexpr double operator""_m_to_cm(long double meters) { + return meters / 0.01; +} + +constexpr double operator""_ft_to_cm(long double feet) { + return operator""_m_to_cm(operator""_ft_to_m(feet)); +} + +constexpr double operator""_ft_to_in(long double feet) { + return operator""_m_to_in(operator""_ft_to_m(feet)); +} + +constexpr double operator""_in_to_ft(long double inches) { + return operator""_m_to_ft(operator""_in_to_m(inches)); +} + +constexpr double operator""_in_to_cm(long double inches) { + return operator""_m_to_cm(operator""_in_to_m(inches)); +} + +constexpr double operator""_cm_to_ft(long double centimeters) { + return operator""_m_to_ft(operator""_cm_to_m(centimeters)); +} + +constexpr double operator""_cm_to_in(long double centimeters) { + return operator""_m_to_in(operator""_cm_to_m(centimeters)); +} \ No newline at end of file From 58157065da2f6d47f8e051084b7e5ad2984b976d Mon Sep 17 00:00:00 2001 From: Nicolay Petrov Date: Wed, 26 Nov 2025 20:58:40 +0500 Subject: [PATCH 06/34] add (solution): add print_bits task --- 01_week/tasks/print_bits/print_bits.cpp | 29 ++++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/01_week/tasks/print_bits/print_bits.cpp b/01_week/tasks/print_bits/print_bits.cpp index a48a43c1..aeade587 100644 --- a/01_week/tasks/print_bits/print_bits.cpp +++ b/01_week/tasks/print_bits/print_bits.cpp @@ -1,7 +1,30 @@ -#include #include - +#include +#include void PrintBits(long long value, size_t bytes) { - throw std::runtime_error{"Not implemented"}; + if (bytes < 1 || bytes > 8) { + return; + } + + std::cout << "0b"; + + size_t total_bits = bytes * 8; + size_t bits_printed = 0; + + // Проходим по всем битам от старшего к младшему + for (int byte = bytes - 1; byte >= 0; --byte) { + for (int bit = 7; bit >= 0; --bit) { + // Получаем текущий бит (сдвигаем и маскируем) + long long current_bit = (value >> (byte * 8 + bit)) & 1; + std::cout << current_bit; + bits_printed++; + + if (bits_printed % 4 == 0 && bits_printed < total_bits) { + std::cout << "'"; + } + } + } + + std::cout << std::endl; } From 6201fcfe2063347fa20d3c4bd1e4cb91b22bb267 Mon Sep 17 00:00:00 2001 From: Nicolay Petrov Date: Wed, 26 Nov 2025 21:07:45 +0500 Subject: [PATCH 07/34] add (solution): add rms task --- 01_week/tasks/rms/rms.cpp | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/01_week/tasks/rms/rms.cpp b/01_week/tasks/rms/rms.cpp index 6882f0a9..d288a27b 100644 --- a/01_week/tasks/rms/rms.cpp +++ b/01_week/tasks/rms/rms.cpp @@ -1,7 +1,21 @@ -#include #include - +#include +#include double CalculateRMS(double values[], size_t size) { - throw std::runtime_error{"Not implemented"}; + if (size == 0) { + return 0.0; + } + + // Вычисление суммы квадратов элементов + double sum1 = 0.0; + for (size_t i = 0; i < size; ++i) { + sum1 += values[i] * values[i]; + } + + // Вычисление среднеквадратического значения + double squares = sum1 / size; + double rms = std::sqrt(squares); + + return rms; } \ No newline at end of file From 4620677d30dcb85b06e8102b0847da6d99a070bd Mon Sep 17 00:00:00 2001 From: Nicolay Petrov Date: Wed, 26 Nov 2025 21:14:10 +0500 Subject: [PATCH 08/34] add rms2 task --- 01_week/tasks/rms/rms.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/01_week/tasks/rms/rms.cpp b/01_week/tasks/rms/rms.cpp index d288a27b..53cd0f84 100644 --- a/01_week/tasks/rms/rms.cpp +++ b/01_week/tasks/rms/rms.cpp @@ -3,7 +3,7 @@ #include double CalculateRMS(double values[], size_t size) { - if (size == 0) { + if (size == 0 || values == nullptr) { return 0.0; } From b73b9b830135834d5021a7d98dc3b446a29f1cb1 Mon Sep 17 00:00:00 2001 From: Nicolay Petrov Date: Wed, 26 Nov 2025 21:31:41 +0500 Subject: [PATCH 09/34] add quadratic task --- 01_week/tasks/quadratic/quadratic.cpp | 58 ++++++++++++++++++++++++++- 1 file changed, 56 insertions(+), 2 deletions(-) diff --git a/01_week/tasks/quadratic/quadratic.cpp b/01_week/tasks/quadratic/quadratic.cpp index abf7d632..5d1a60fb 100644 --- a/01_week/tasks/quadratic/quadratic.cpp +++ b/01_week/tasks/quadratic/quadratic.cpp @@ -1,6 +1,60 @@ +#include +#include +#include #include - void SolveQuadratic(int a, int b, int c) { - throw std::runtime_error{"Not implemented"}; + // a,b,c=0 + if (a == 0 && b == 0 && c == 0) { + std::cout << "infinite solutions"; + return; + } + + // a=0 + if (a == 0) { + if (b == 0) { + // c=0 + if (c == 0) { + std::cout << "infinite solutions"; + } else { + std::cout << "no solutions"; + } + } else { + // b*x+c=0 + double x = -static_cast(c) / b; + // Обработка случая -0.0 + if (std::abs(x) < 1e-10) x = 0.0; + std::cout << std::setprecision(6) << x; + } + return; + } + + // Вычисление D + double discriminant = static_cast(b) * b - 4.0 * a * c; + + if (discriminant < 0) { + // D<0 + std::cout << "no solutions"; + } else if (discriminant == 0) { + // D=0 + double x = -static_cast(b) / (2.0 * a); + // Обработка случая -0.0 + if (std::abs(x) < 1e-10) x = 0.0; + std::cout << std::setprecision(6) << x; + } else { + // D>0 + double sqrt_d = std::sqrt(discriminant); + double x1 = (-b - sqrt_d) / (2.0 * a); + double x2 = (-b + sqrt_d) / (2.0 * a); + + // Обработка случая -0.0 для обоих корней + if (std::abs(x1) < 1e-10) x1 = 0.0; + if (std::abs(x2) < 1e-10) x2 = 0.0; + + if (x1 > x2) { + std::swap(x1, x2); + } + + std::cout << std::setprecision(6) << x1 << " " << x2; + } } \ No newline at end of file From 9930417c612095dd514402d1d6d7dd7ea71c4ac5 Mon Sep 17 00:00:00 2001 From: Nicolay Petrov Date: Wed, 3 Dec 2025 18:00:01 +0500 Subject: [PATCH 10/34] add (solution): add func_array task --- 02_week/tasks/func_array/func_array.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/02_week/tasks/func_array/func_array.cpp b/02_week/tasks/func_array/func_array.cpp index b327e68d..a0ea8816 100644 --- a/02_week/tasks/func_array/func_array.cpp +++ b/02_week/tasks/func_array/func_array.cpp @@ -1,6 +1,10 @@ #include -double ApplyOperations(double a, double b /* other arguments */) { - throw std::runtime_error{"Not implemented"}; +double ApplyOperations(double a, double b, double (*ops[])(double,double), size_t size) { + double sum = 0.0; + for (size_t i = 0; i < size; ++i){ + sum += ops[i](a,b); + } + return sum; } \ No newline at end of file From 53e1f09062e622fb5b13126ef3910cf2a749cc89 Mon Sep 17 00:00:00 2001 From: Nicolay Petrov Date: Wed, 3 Dec 2025 18:28:25 +0500 Subject: [PATCH 11/34] add (solution): add func_array1 task --- 02_week/tasks/func_array/func_array.cpp | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/02_week/tasks/func_array/func_array.cpp b/02_week/tasks/func_array/func_array.cpp index a0ea8816..556d2a35 100644 --- a/02_week/tasks/func_array/func_array.cpp +++ b/02_week/tasks/func_array/func_array.cpp @@ -1,10 +1,17 @@ #include -double ApplyOperations(double a, double b, double (*ops[])(double,double), size_t size) { +double ApplyOperations(double a, double b, double (**ops)(double, double), size_t size) { + if (ops == nullptr || size == 0) { + return 0.0; + } + double sum = 0.0; - for (size_t i = 0; i < size; ++i){ - sum += ops[i](a,b); - } + for (size_t i = 0; i < size; ++i) { + if (ops[i] != nullptr) { + sum += ops[i](a, b); + } + } + return sum; } \ No newline at end of file From df4918ead855ec449ff8805f2423e737d93f36e5 Mon Sep 17 00:00:00 2001 From: Nicolay Petrov Date: Fri, 5 Dec 2025 16:16:58 +0500 Subject: [PATCH 12/34] add (solution): add swap_ptr task --- 02_week/tasks/swap_ptr/swap_ptr.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/02_week/tasks/swap_ptr/swap_ptr.cpp b/02_week/tasks/swap_ptr/swap_ptr.cpp index 93db625d..b8470e52 100644 --- a/02_week/tasks/swap_ptr/swap_ptr.cpp +++ b/02_week/tasks/swap_ptr/swap_ptr.cpp @@ -1,6 +1,9 @@ #include - -void SwapPtr(/* write arguments here */) { - throw std::runtime_error{"Not implemented"}; +// Шаблонная функция для обмена значений любых типов +template +void SwapPtr(T*& a, T*& b) { + T* temp = a; + a = b; + b = temp; } \ No newline at end of file From 72c0db71393b1b0342d59d2f7c6aadba854f3b13 Mon Sep 17 00:00:00 2001 From: Nicolay Petrov Date: Fri, 5 Dec 2025 22:25:17 +0500 Subject: [PATCH 13/34] add (solution): add longest task --- 02_week/tasks/longest/longest.cpp | 52 +++++++++++++++++++++++++++++-- 1 file changed, 50 insertions(+), 2 deletions(-) diff --git a/02_week/tasks/longest/longest.cpp b/02_week/tasks/longest/longest.cpp index 04b3c354..2b9e8357 100644 --- a/02_week/tasks/longest/longest.cpp +++ b/02_week/tasks/longest/longest.cpp @@ -1,6 +1,54 @@ #include +// Общая подфункция через const char* +const char* FindLongestSubsequenceImpl(const char* p1, const char* p2, size_t& count) { + if (p1 == nullptr || p2 == nullptr) { + count = 0; + return nullptr; + } + + if (p1 > p2) { + count = 0; + return nullptr; + } + + if (p1 == p2) { + count = 0; + return nullptr; + } + + const char* pp1 = p1; + const char* max_p = nullptr; + size_t c = 1; + size_t max_c = 0; + + while (pp1 != p2) { + if (pp1 + 1 != p2 && *pp1 == *(pp1 + 1)) { + ++c; + } else { + if (c > max_c) { + max_c = c; + max_p = pp1 - c + 1; + } + c = 1; + } + ++pp1; + } + + if (c > max_c) { + max_c = c; + max_p = pp1 - c; + } + + count = max_c; + return max_p; +} + +// Перегрузка функций для сhar и const char +const char* FindLongestSubsequence(const char* p1, const char* p2, size_t& count) { + return FindLongestSubsequenceImpl(p1, p2, count); +} -/* return_type */ FindLongestSubsequence(/* ptr_type */ begin, /* ptr_type */ end, /* type */ count) { - throw std::runtime_error{"Not implemented"}; +char* FindLongestSubsequence(char* p1, char* p2, size_t& count) { + return const_cast(FindLongestSubsequenceImpl(p1, p2, count)); } From 0ea827ecdc5593709dd671397dcf511688f2a32d Mon Sep 17 00:00:00 2001 From: Nicolay Petrov Date: Tue, 9 Dec 2025 00:23:49 +0500 Subject: [PATCH 14/34] add (solution): add pretty_array task --- 02_week/tasks/pretty_array/pretty_array.cpp | 40 +++++++++++++++++++-- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/02_week/tasks/pretty_array/pretty_array.cpp b/02_week/tasks/pretty_array/pretty_array.cpp index 48eab341..b15c91d2 100644 --- a/02_week/tasks/pretty_array/pretty_array.cpp +++ b/02_week/tasks/pretty_array/pretty_array.cpp @@ -1,6 +1,42 @@ #include +#include -void PrintArray(/* write arguments here */) { - throw std::runtime_error{"Not implemented"}; + +void PrintArray(const int* begin, const int* end, size_t limit = 0) { + // Направление + bool rev = end < begin; + + size_t size = 0; + if (!rev) { + size = end - begin; + } else { + size = begin - end; + } + + if (size == 0) { + std::cout << "[]" << std::endl; + return; + } + + + std::cout << "["; + for (size_t i = 0; i < size; ++i) { + if (!rev) { + std::cout << begin[i]; + } else { + std::cout << *(begin - i); + } + + // Ограничитель + if (i < size - 1) { + if (limit > 0 && (i + 1) % limit == 0) { + std::cout << ", ..." << std::endl << " "; + } else { + std::cout << ", "; + } + } + } + + std::cout << "]" << std::endl; } \ No newline at end of file From fdb1b70ce1ae9bd2c092f3cba9159ffc5ca0ccfc Mon Sep 17 00:00:00 2001 From: Nicolay Petrov Date: Tue, 9 Dec 2025 20:11:20 +0500 Subject: [PATCH 15/34] add (solution): add last_of_us task --- 02_week/tasks/last_of_us/last_of_us.cpp | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/02_week/tasks/last_of_us/last_of_us.cpp b/02_week/tasks/last_of_us/last_of_us.cpp index c7bf1a25..2ce52a19 100644 --- a/02_week/tasks/last_of_us/last_of_us.cpp +++ b/02_week/tasks/last_of_us/last_of_us.cpp @@ -1,6 +1,17 @@ #include -/* return_type */ FindLastElement(/* ptr_type */ begin, /* ptr_type */ end, /* func_type */ predicate) { - throw std::runtime_error{"Not implemented"}; + const int* FindLastElement(const int* begin, const int* end, bool (*predicate)(int)) { + if (begin > end || begin == end || end == nullptr || begin == nullptr) { + return end; + } + const int* p_pred = end; + + for (size_t i = 1; (end-i) != (begin-1); ++i) { + if (predicate(*(end-i))) { + p_pred = end-i; + return p_pred; + } + } + return p_pred; } \ No newline at end of file From f04d35e44be3f767f07872b398b1a3cd619278b1 Mon Sep 17 00:00:00 2001 From: Nicolay Petrov Date: Tue, 9 Dec 2025 21:56:34 +0500 Subject: [PATCH 16/34] add (solution): add little_big task --- 02_week/tasks/little_big/little_big.cpp | 48 +++++++++++++++++++++---- 1 file changed, 42 insertions(+), 6 deletions(-) diff --git a/02_week/tasks/little_big/little_big.cpp b/02_week/tasks/little_big/little_big.cpp index abe24379..f9e078b8 100644 --- a/02_week/tasks/little_big/little_big.cpp +++ b/02_week/tasks/little_big/little_big.cpp @@ -1,10 +1,46 @@ -#include +#include +#include +#include - -void PrintMemory(int /* write arguments here */) { - throw std::runtime_error{"Not implemented"}; +void PrintMemory(int value, bool invert = false) { + //memcpy копирует байты из числа в массив + unsigned char bytes[sizeof(int)]; + std::memcpy(bytes, &value, sizeof(int)); + + std::cout << "0x" << std::uppercase << std::hex; + + if (!invert) { + for (size_t i = 0; i < sizeof(int); ++i) { + unsigned int byte_value = bytes[i]; + std::cout << std::setw(2) << std::setfill('0') << byte_value; + } + } else { + for (int i = sizeof(int) - 1; i >= 0; --i) { + unsigned int byte_value = bytes[i]; + std::cout << std::setw(2) << std::setfill('0') << byte_value; + } + } + + std::cout << std::endl; } -void PrintMemory(double /* write arguments here */) { - throw std::runtime_error{"Not implemented"}; +void PrintMemory(double value, bool invert = false) { + unsigned char bytes[sizeof(double)]; + std::memcpy(bytes, &value, sizeof(double)); + + std::cout << "0x" << std::uppercase << std::hex; + + if (!invert) { + for (size_t i = 0; i < sizeof(double); ++i) { + unsigned int byte_value = bytes[i]; + std::cout << std::setw(2) << std::setfill('0') << byte_value; + } + } else { + for (int i = sizeof(double) - 1; i >= 0; --i) { + unsigned int byte_value = bytes[i]; + std::cout << std::setw(2) << std::setfill('0') << byte_value; + } + } + + std::cout << std::endl; } \ No newline at end of file From 728bdb1fc0428a9cf4ad0593a03b2fc23df2c48c Mon Sep 17 00:00:00 2001 From: Nicolay Petrov Date: Wed, 17 Dec 2025 16:28:00 +0500 Subject: [PATCH 17/34] add (solution): add proverka task --- 03_week/tasks/data_stats/data_stats.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/03_week/tasks/data_stats/data_stats.cpp b/03_week/tasks/data_stats/data_stats.cpp index b941c211..7ae7d7d8 100644 --- a/03_week/tasks/data_stats/data_stats.cpp +++ b/03_week/tasks/data_stats/data_stats.cpp @@ -6,6 +6,6 @@ struct DataStats { double sd = 0.0; }; -/* return_type */ CalculateDataStats(/* args */) { +double CalculateDataStats(/* args */) { throw std::runtime_error{"Not implemented"}; } From 6693bc7ec0b457a1539059e83060ef4d93740954 Mon Sep 17 00:00:00 2001 From: Nicolay Petrov Date: Wed, 17 Dec 2025 18:28:12 +0500 Subject: [PATCH 18/34] add (solution): add data_stats task --- 03_week/tasks/data_stats/data_stats.cpp | 29 +++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/03_week/tasks/data_stats/data_stats.cpp b/03_week/tasks/data_stats/data_stats.cpp index 7ae7d7d8..8da0d84b 100644 --- a/03_week/tasks/data_stats/data_stats.cpp +++ b/03_week/tasks/data_stats/data_stats.cpp @@ -1,4 +1,6 @@ #include +#include +#include struct DataStats { @@ -6,6 +8,29 @@ struct DataStats { double sd = 0.0; }; -double CalculateDataStats(/* args */) { - throw std::runtime_error{"Not implemented"}; +DataStats CalculateDataStats(const std::vector& vec) { + if (vec.empty()) { + return DataStats{0.0, 0.0}; + } + + long double sum = 0.0; + long double sum_sq = 0.0; + + for (int x : vec) { + long double ld_x = static_cast(x); + sum += ld_x; + sum_sq += ld_x * ld_x; + } + + long double avg = sum / vec.size(); + long double variance = (sum_sq / vec.size()) - (avg * avg); + + // Защита от ошибок округления + if (variance < 0.0) { + variance = 0.0; + } + + double sd = static_cast(std::sqrt(variance)); + + return DataStats{static_cast(avg), sd}; } From a91e20f960f0cf6e5933edcc610149563e66ed4c Mon Sep 17 00:00:00 2001 From: Nicolay Petrov Date: Wed, 17 Dec 2025 22:18:14 +0500 Subject: [PATCH 19/34] add (solution): add easy_compare task --- 03_week/tasks/easy_compare/easy_compare.cpp | 65 +++++++++++++++++++-- 1 file changed, 61 insertions(+), 4 deletions(-) diff --git a/03_week/tasks/easy_compare/easy_compare.cpp b/03_week/tasks/easy_compare/easy_compare.cpp index dd5cb7f6..08e86c13 100644 --- a/03_week/tasks/easy_compare/easy_compare.cpp +++ b/03_week/tasks/easy_compare/easy_compare.cpp @@ -2,9 +2,9 @@ struct Date { - unsigned year; - unsigned month; - unsigned day; + unsigned year = 0; + unsigned month = 0; + unsigned day = 0; }; struct StudentInfo { @@ -13,4 +13,61 @@ struct StudentInfo { int score; unsigned course; Date birth_date; -}; \ No newline at end of file +}; +// +bool operator < (const Date& lhs, const Date& rhs){ + return std::tie(lhs.year, lhs.month, lhs.day) < std::tie(rhs.year, rhs.month, rhs.day); +} +bool operator == (const Date& lhs, const Date& rhs){ + return std::tie(lhs.year, lhs.month, lhs.day) == std::tie(rhs.year, rhs.month, rhs.day); +} +bool operator!=(const Date& lhs, const Date& rhs) { + return !(lhs == rhs); +} + +bool operator<=(const Date& lhs, const Date& rhs) { + return (lhs < rhs) || (lhs == rhs); +} + +bool operator>(const Date& lhs, const Date& rhs) { + return !(lhs <= rhs); +} + +bool operator>=(const Date& lhs, const Date& rhs) { + return !(lhs < rhs); +} +// +bool operator == (const StudentInfo& lhs, const StudentInfo& rhs){ + return std::tie(lhs.mark, lhs.score) == std::tie(rhs.mark, rhs.score); +} + +bool operator<(const StudentInfo& lhs, const StudentInfo& rhs) { + if (lhs.mark != rhs.mark) { + return rhs.mark < lhs.mark; + } + + if (lhs.score != rhs.score) { + return rhs.score > lhs.score; + } + + if (lhs.course != rhs.course) { + return lhs.course > rhs.course; + } + + return lhs.birth_date < rhs.birth_date; +} +bool operator!=(const StudentInfo& lhs, const StudentInfo& rhs) { + return !(lhs == rhs); +} + +bool operator<=(const StudentInfo& lhs, const StudentInfo& rhs) { + return (lhs < rhs) || (lhs == rhs); +} + +bool operator>(const StudentInfo& lhs, const StudentInfo& rhs) { + return !(lhs <= rhs); +} + +bool operator>=(const StudentInfo& lhs, const StudentInfo& rhs) { + return !(lhs < rhs); +} \ No newline at end of file From e4133b82481f9ee683f9f8581865b24c6e10af79 Mon Sep 17 00:00:00 2001 From: Nicolay Petrov Date: Thu, 18 Dec 2025 10:16:16 +0500 Subject: [PATCH 20/34] add (solution): add enum_operators task --- .../tasks/enum_operators/enum_operators.cpp | 90 ++++++++++++++++--- 1 file changed, 80 insertions(+), 10 deletions(-) diff --git a/03_week/tasks/enum_operators/enum_operators.cpp b/03_week/tasks/enum_operators/enum_operators.cpp index a539be38..ef44ddf3 100644 --- a/03_week/tasks/enum_operators/enum_operators.cpp +++ b/03_week/tasks/enum_operators/enum_operators.cpp @@ -1,5 +1,8 @@ +#include #include #include +#include +#include enum class CheckFlags : uint8_t { NONE = 0, @@ -12,22 +15,89 @@ enum class CheckFlags : uint8_t { ALL = TIME | DATE | USER | CERT | KEYS | DEST }; -/* return_type */ operator|(/* args */) { - throw std::runtime_error{"Not implemented"}; +// Вспомогательная функция для санитизации флагов (убирает флаги вне диапазона) +inline constexpr CheckFlags sanitize(CheckFlags flags) { + return static_cast(static_cast(flags) & + static_cast(CheckFlags::ALL)); } -/* return_type */ operator&(/* args */) { - throw std::runtime_error{"Not implemented"}; +// Побитовое ИЛИ +constexpr CheckFlags operator|(CheckFlags lhs, CheckFlags rhs) { + return sanitize(static_cast( + static_cast(sanitize(lhs)) | + static_cast(sanitize(rhs)))); } -/* return_type */ operator^(/* args */) { - throw std::runtime_error{"Not implemented"}; +// Побитовое И (возвращает bool согласно условию) +constexpr bool operator&(CheckFlags lhs, CheckFlags rhs) { + lhs = sanitize(lhs); + rhs = sanitize(rhs); + + // Если любой из операндов NONE, возвращаем false + if (lhs == CheckFlags::NONE || rhs == CheckFlags::NONE) { + return false; + } + + // Проверяем, что один операнд является подмножеством другого + uint8_t l = static_cast(lhs); + uint8_t r = static_cast(rhs); + uint8_t intersection = l & r; + + // Возвращаем true, если все флаги lhs содержатся в rhs + // ИЛИ все флаги rhs содержатся в lhs + return intersection == l || intersection == r; } -/* return_type */ operator~(/* args */) { - throw std::runtime_error{"Not implemented"}; +// Исключающее ИЛИ +constexpr CheckFlags operator^(CheckFlags lhs, CheckFlags rhs) { + return sanitize(static_cast( + static_cast(sanitize(lhs)) ^ + static_cast(sanitize(rhs)))); } -/* return_type */ operator<<(/* args */) { - throw std::runtime_error{"Not implemented"}; +// Побитовое НЕ (инверсия) +constexpr CheckFlags operator~(CheckFlags flags) { + return sanitize(static_cast( + static_cast(CheckFlags::ALL) & + ~static_cast(sanitize(flags)))); } + +// Вывод флагов в поток +std::ostream& operator<<(std::ostream& os, CheckFlags flags) { + flags = sanitize(flags); + + if (flags == CheckFlags::NONE) { + os << "NONE"; + return os; + } + + std::vector active_flags; + + if (static_cast(flags & CheckFlags::TIME)) { + active_flags.push_back("TIME"); + } + if (static_cast(flags & CheckFlags::DATE)) { + active_flags.push_back("DATE"); + } + if (static_cast(flags & CheckFlags::USER)) { + active_flags.push_back("USER"); + } + if (static_cast(flags & CheckFlags::CERT)) { + active_flags.push_back("CERT"); + } + if (static_cast(flags & CheckFlags::KEYS)) { + active_flags.push_back("KEYS"); + } + if (static_cast(flags & CheckFlags::DEST)) { + active_flags.push_back("DEST"); + } + + for (size_t i = 0; i < active_flags.size(); ++i) { + os << active_flags[i]; + if (i != active_flags.size() - 1) { + os << ", "; + } + } + + return os; +} \ No newline at end of file From 0adb815b28b38afd7e9624b91483f6aa55291af3 Mon Sep 17 00:00:00 2001 From: Nicolay Petrov Date: Thu, 18 Dec 2025 10:18:41 +0500 Subject: [PATCH 21/34] add (solution): add comment cmake task --- CMakeLists.txt | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index b64ab3cd..37883b7a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -27,10 +27,10 @@ add_executable(psds_cpp main.cpp) add_week(01_week) add_week(02_week) add_week(03_week) -add_week(04_week) -add_week(05_week) -add_week(06_week) -add_week(07_week) -add_week(08_week) -add_week(09_week) -add_week(10_week) \ No newline at end of file +//add_week(04_week) +//add_week(05_week) +//add_week(06_week) +//add_week(07_week) +//add_week(08_week) +//add_week(09_week) +//add_week(10_week) \ No newline at end of file From 891f81632f9d8eb3f63a53c756ad96c7ad2736e6 Mon Sep 17 00:00:00 2001 From: Nicolay Petrov Date: Thu, 18 Dec 2025 10:20:54 +0500 Subject: [PATCH 22/34] add (solution): add comment_cmake task --- CMakeLists.txt | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 37883b7a..eced04ed 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -27,10 +27,10 @@ add_executable(psds_cpp main.cpp) add_week(01_week) add_week(02_week) add_week(03_week) -//add_week(04_week) -//add_week(05_week) -//add_week(06_week) -//add_week(07_week) -//add_week(08_week) -//add_week(09_week) -//add_week(10_week) \ No newline at end of file +# add_week(04_week) +# add_week(05_week) +# add_week(06_week) +# add_week(07_week) +# add_week(08_week) +# add_week(09_week) +# add_week(10_week) \ No newline at end of file From df82b9cb65f309131dc53f5961260b7821e3fe2f Mon Sep 17 00:00:00 2001 From: Nicolay Petrov Date: Thu, 18 Dec 2025 17:18:41 +0500 Subject: [PATCH 23/34] add (solution): add filter task --- 03_week/tasks/filter/filter.cpp | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/03_week/tasks/filter/filter.cpp b/03_week/tasks/filter/filter.cpp index 6648cb39..d05210e6 100644 --- a/03_week/tasks/filter/filter.cpp +++ b/03_week/tasks/filter/filter.cpp @@ -1,6 +1,20 @@ +#include #include -/* return_type */ Filter(/* args */) { - throw std::runtime_error{"Not implemented"}; +void Filter(std::vector& vec, bool(*pred)(int)) { + + if (pred == nullptr) { + return; + } + + size_t write_ptr = 0; + + for (size_t read_ptr = 0; read_ptr < vec.size(); ++read_ptr) { + if (pred(vec[read_ptr])) { + vec[write_ptr] = vec[read_ptr]; + ++write_ptr; + } + } + vec.resize(write_ptr); } \ No newline at end of file From 1c9157cc025a8f3942c90b63b0dfff3d55973769 Mon Sep 17 00:00:00 2001 From: Nicolay Petrov Date: Thu, 18 Dec 2025 17:24:50 +0500 Subject: [PATCH 24/34] add (solution): add find_all task --- 03_week/tasks/find_all/find_all.cpp | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/03_week/tasks/find_all/find_all.cpp b/03_week/tasks/find_all/find_all.cpp index 74f393b2..f4cb85fd 100644 --- a/03_week/tasks/find_all/find_all.cpp +++ b/03_week/tasks/find_all/find_all.cpp @@ -1,6 +1,26 @@ -#include +#include - -/* return_type */ FindAll(/* args */) { - throw std::runtime_error{"Not implemented"}; +std::vector FindAll(const std::vector& container, bool (*predicate)(int)) { + std::vector result; + + if (!predicate) { + return result; + } + + size_t count = 0; + for (size_t i = 0; i < container.size(); ++i) { + if (predicate(container[i])) { + ++count; + } + } + + result.reserve(count); + + for (size_t i = 0; i < container.size(); ++i) { + if (predicate(container[i])) { + result.push_back(i); + } + } + + return result; } \ No newline at end of file From 66f85978e1f75124586aecc0110d8e187230d3fc Mon Sep 17 00:00:00 2001 From: Nicolay Petrov Date: Thu, 18 Dec 2025 18:22:50 +0500 Subject: [PATCH 25/34] add (solution): add minmax task --- 03_week/tasks/minmax/minmax.cpp | 47 ++++++++++++++++++++++++++++++--- 1 file changed, 44 insertions(+), 3 deletions(-) diff --git a/03_week/tasks/minmax/minmax.cpp b/03_week/tasks/minmax/minmax.cpp index c2869799..508ea215 100644 --- a/03_week/tasks/minmax/minmax.cpp +++ b/03_week/tasks/minmax/minmax.cpp @@ -1,6 +1,47 @@ +#include #include +#include - -/* return_type */ MinMax(/* args */) { - throw std::runtime_error{"Not implemented"}; +// Неконстантная версия (возвращает итераторы, позволяющие изменять элементы) +std::pair::iterator, std::vector::iterator> +MinMax(std::vector& vec) { + if (vec.empty()) { + return {vec.end(), vec.end()}; + } + + auto min_it = vec.begin(); + auto max_it = vec.begin(); + + for (auto it = vec.begin(); it != vec.end(); ++it) { + if (*it < *min_it) { + min_it = it; + } + else if (*it >= *max_it) { + max_it = it; + } + } + + return {min_it, max_it}; } + +// Константная версия (для работы с const vector) +std::pair::const_iterator, std::vector::const_iterator> +MinMax(const std::vector& vec) { + if (vec.empty()) { + return {vec.cend(), vec.cend()}; + } + + auto min_it = vec.cbegin(); + auto max_it = vec.cbegin(); + + for (auto it = vec.cbegin(); it != vec.cend(); ++it) { + if (*it < *min_it) { + min_it = it; + } + else if (*it >= *max_it) { + max_it = it; + } + } + + return {min_it, max_it}; +} \ No newline at end of file From 33c8359820240ad51080c443c82426c6f908d1f4 Mon Sep 17 00:00:00 2001 From: Nicolay Petrov Date: Thu, 18 Dec 2025 18:29:44 +0500 Subject: [PATCH 26/34] add (solution): add os_overload task --- 03_week/tasks/os_overload/os_overload.cpp | 48 ++++++++++++++++++++--- 1 file changed, 42 insertions(+), 6 deletions(-) diff --git a/03_week/tasks/os_overload/os_overload.cpp b/03_week/tasks/os_overload/os_overload.cpp index e473418d..10eb6f0b 100644 --- a/03_week/tasks/os_overload/os_overload.cpp +++ b/03_week/tasks/os_overload/os_overload.cpp @@ -1,21 +1,57 @@ #include #include #include - +#include struct Coord2D { - int x; - int y; + int x = 0; + int y = 0; }; struct Circle { Coord2D coord; - unsigned radius; + unsigned radius = 1; + + Circle() = default; + Circle(const Coord2D& c) : coord(c) {} + Circle(const Coord2D& c, unsigned r) : coord(c), radius(r) {} }; using CircleRegion = std::pair; using CircleRegionList = std::vector; -/* return_type */ operator<<(/* args */) { - throw std::runtime_error{"Not implemented"}; +std::ostream& operator<<(std::ostream& os, const Coord2D& coord) { + os << "(" << coord.x << ", " << coord.y << ")"; + return os; +} + +std::ostream& operator<<(std::ostream& os, const Circle& circle) { + os << "circle["; + if (circle.radius > 0) { + os << circle.coord << ", r = " << circle.radius; + } + os << "]"; + return os; } + +std::ostream& operator<<(std::ostream& os, const CircleRegion& region) { + os << (region.second ? "+" : "-") << region.first; + return os; +} + +std::ostream& operator<<(std::ostream& os, const CircleRegionList& list) { + if (list.empty()) { + os << "{}"; + } else { + os << "{\n"; + for (size_t i = 0; i < list.size(); ++i) { + os << "\t" << list[i]; + if (i != list.size() - 1) { + os << ","; + } + os << "\n"; + } + os << "}"; + } + return os; +} \ No newline at end of file From f591253fd5902146883ad180a561b16451875d7b Mon Sep 17 00:00:00 2001 From: Nicolay Petrov Date: Thu, 18 Dec 2025 21:05:05 +0500 Subject: [PATCH 27/34] add (solution): add range task --- 03_week/tasks/range/range.cpp | 52 +++++++++++++++++++++++++++++++++-- 1 file changed, 50 insertions(+), 2 deletions(-) diff --git a/03_week/tasks/range/range.cpp b/03_week/tasks/range/range.cpp index d2085495..f97bde9b 100644 --- a/03_week/tasks/range/range.cpp +++ b/03_week/tasks/range/range.cpp @@ -1,7 +1,55 @@ #include #include - std::vector Range(int from, int to, int step) { - throw std::runtime_error{"Not implemented"}; + // Проверка на пустой диапазон + if (step == 0) { + // Вместо исключения возвращаем пустой вектор + return std::vector(); + } + + // Если шаг положительный и from >= to, или шаг отрицательный и from <= to, + // то диапазон пустой + if ((step > 0 && from >= to) || (step < 0 && from <= to)) { + return std::vector(); + } + + // Вычисляем количество элементов + int count = 0; + if (step > 0) { + // Для положительного шага + count = (to - from - 1) / step + 1; + } else { + // Для отрицательного шага + count = (to - from + 1) / step + 1; + } + + // Гарантируем, что count не отрицательный + if (count <= 0) { + return std::vector(); + } + + // Создаем вектор с заранее выделенной памятью + std::vector result; + result.reserve(count); + + // Заполняем значениями + int current = from; + if (step > 0) { + while (current < to) { + result.push_back(current); + current += step; + } + } else { + while (current > to) { + result.push_back(current); + current += step; // step отрицательный, так что это вычитание + } + } + + return result; } + +std::vector Range(int from, int to) { + return Range(from, to, 1); +} \ No newline at end of file From be5fe759badf4edd79e03510a57e213a273462aa Mon Sep 17 00:00:00 2001 From: Nicolay Petrov Date: Thu, 18 Dec 2025 21:07:46 +0500 Subject: [PATCH 28/34] add (solution): add range_1 task --- 03_week/tasks/range/range.cpp | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/03_week/tasks/range/range.cpp b/03_week/tasks/range/range.cpp index f97bde9b..c68173c0 100644 --- a/03_week/tasks/range/range.cpp +++ b/03_week/tasks/range/range.cpp @@ -2,38 +2,28 @@ #include std::vector Range(int from, int to, int step) { - // Проверка на пустой диапазон if (step == 0) { - // Вместо исключения возвращаем пустой вектор return std::vector(); } - // Если шаг положительный и from >= to, или шаг отрицательный и from <= to, - // то диапазон пустой if ((step > 0 && from >= to) || (step < 0 && from <= to)) { return std::vector(); } - // Вычисляем количество элементов int count = 0; if (step > 0) { - // Для положительного шага count = (to - from - 1) / step + 1; } else { - // Для отрицательного шага count = (to - from + 1) / step + 1; } - // Гарантируем, что count не отрицательный if (count <= 0) { return std::vector(); } - // Создаем вектор с заранее выделенной памятью std::vector result; result.reserve(count); - // Заполняем значениями int current = from; if (step > 0) { while (current < to) { @@ -43,7 +33,7 @@ std::vector Range(int from, int to, int step) { } else { while (current > to) { result.push_back(current); - current += step; // step отрицательный, так что это вычитание + current += step; } } From 413666da030a1eb21b8fcc2e427a8ce553c558db Mon Sep 17 00:00:00 2001 From: Nicolay Petrov Date: Thu, 18 Dec 2025 21:09:41 +0500 Subject: [PATCH 29/34] add (solution): add unique task --- 03_week/tasks/unique/unique.cpp | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/03_week/tasks/unique/unique.cpp b/03_week/tasks/unique/unique.cpp index 9d2545bb..1458bcd7 100644 --- a/03_week/tasks/unique/unique.cpp +++ b/03_week/tasks/unique/unique.cpp @@ -1,6 +1,23 @@ #include #include -/* return_type */ Unique(/* args */) { - throw std::runtime_error{"Not implemented"}; -} +std::vector Unique(const std::vector& sorted_vec) { + if (sorted_vec.empty()) { + return std::vector(); + } + + std::vector result; + result.reserve(sorted_vec.size()); + + result.push_back(sorted_vec[0]); + + for (size_t i = 1; i < sorted_vec.size(); ++i) { + if (sorted_vec[i] != sorted_vec[i - 1]) { + result.push_back(sorted_vec[i]); + } + } + + result.shrink_to_fit(); + + return result; +} \ No newline at end of file From 6dda8495279d047d96825a9a3b9acf09e873bb05 Mon Sep 17 00:00:00 2001 From: Nicolay Petrov Date: Tue, 23 Dec 2025 20:50:28 +0500 Subject: [PATCH 30/34] add (solution): add cmake task --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index eced04ed..53e3ff3f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -27,7 +27,7 @@ add_executable(psds_cpp main.cpp) add_week(01_week) add_week(02_week) add_week(03_week) -# add_week(04_week) +add_week(04_week) # add_week(05_week) # add_week(06_week) # add_week(07_week) From baaa204917030db4c45cb16f67284365359e6ed3 Mon Sep 17 00:00:00 2001 From: Nicolay Petrov Date: Wed, 24 Dec 2025 20:42:35 +0500 Subject: [PATCH 31/34] add (solution): add phasor task --- 04_week/tasks/phasor/phasor.cpp | 255 +++++++++++++++++++++++++++++++- 1 file changed, 253 insertions(+), 2 deletions(-) diff --git a/04_week/tasks/phasor/phasor.cpp b/04_week/tasks/phasor/phasor.cpp index 3ec1b9ad..9b81bcaa 100644 --- a/04_week/tasks/phasor/phasor.cpp +++ b/04_week/tasks/phasor/phasor.cpp @@ -1,10 +1,261 @@ - +#include +#include +#include +#include struct ExpTag {}; struct DegTag {}; struct AlgTag {}; - class Phasor { +private: + double real_; // действительная часть + double imag_; // мнимая часть + // Вспомогательная функция для нормализации фазы в диапазон (-pi, pi] + static double normalize_phase(double phase) { + const double two_pi = 2.0 * std::numbers::pi; + + // Приводим фазу в диапазон [0, 2pi) + phase = std::fmod(phase, two_pi); + if (phase < 0) { + phase += two_pi; + } + + // Приводим фазу в диапазон (-pi, pi] + if (phase > std::numbers::pi) { + phase -= two_pi; + } + + return phase; + } + +public: + // Конструкторы + // Конструктор по умолчанию - нулевой фазор + Phasor() : real_(0.0), imag_(0.0) {} + + // Конструктор из полярных координат + Phasor(double magnitude, double phase_rad) { + if (magnitude < 0) { + magnitude = -magnitude; + phase_rad += std::numbers::pi; + } + phase_rad = normalize_phase(phase_rad); + real_ = magnitude * std::cos(phase_rad); + imag_ = magnitude * std::sin(phase_rad); + } + + // Конструктор ExpTag + Phasor(double magnitude, double phase_rad, [[maybe_unused]] ExpTag tag) + : Phasor(magnitude, phase_rad) {} + + // Конструктор DegTag + Phasor(double magnitude, double phase_deg, [[maybe_unused]] DegTag tag) + : Phasor(magnitude, phase_deg * std::numbers::pi / 180.0) {} + + // Конструктор AlgTag + Phasor(double real, double imag, [[maybe_unused]] AlgTag tag) + : real_(real), imag_(imag) {} + + // Методы доступа + double Magnitude() const { + return std::sqrt(real_ * real_ + imag_ * imag_); + } + + double Phase() const { + if (real_ == 0.0 && imag_ == 0.0) { + return 0.0; + } + return std::atan2(imag_, real_); + } + + double PhaseDeg() const { + return Phase() * 180.0 / std::numbers::pi; + } + + double Real() const { + return real_; + } + + double Imag() const { + return imag_; + } + + // Синонимы + + double Abs() const { return Magnitude(); } + double Angle() const { return Phase(); } + double AngleDeg() const { return PhaseDeg(); } + + // Методы модификации + + void SetPolar(double magnitude, double phase_rad) { + *this = Phasor(magnitude, phase_rad); + } + + void SetCartesian(double real, double imag) { + real_ = real; + imag_ = imag; + } + + // Арифметические операторы с присваиванием + + Phasor& operator += (const Phasor& other) { + real_ += other.real_; + imag_ += other.imag_; + return *this; + } + + Phasor& operator -= (const Phasor& other) { + real_ -= other.real_; + imag_ -= other.imag_; + return *this; + } + + Phasor& operator *= (const Phasor& other) { + double mag = Magnitude() * other.Magnitude(); + double phase = Phase() + other.Phase(); + real_ = mag * std::cos(phase); + imag_ = mag * std::sin(phase); + return *this; + } + + Phasor& operator /= (const Phasor& other) { + double other_mag = other.Magnitude(); + if (other_mag == 0.0) { + throw std::runtime_error("Division by zero in Phasor"); + } + double mag = Magnitude() / other_mag; + double phase = Phase() - other.Phase(); + real_ = mag * std::cos(phase); + imag_ = mag * std::sin(phase); + return *this; + } + + // Унарный минус + + Phasor operator -() const { + return Phasor(-real_, -imag_, AlgTag{}); + } + + // Специальные методы + + Phasor Conj() const { + return Phasor(real_, -imag_, AlgTag{}); + } + + Phasor Inv() const { + double mag = Magnitude(); + if (mag == 0.0) { + throw std::runtime_error("Inverse of zero Phasor"); + } + double new_mag = 1.0 / mag; + double new_phase = -Phase(); + return Phasor(new_mag, new_phase); + } }; + +// Бинарные арифметические операторы + +Phasor operator + (const Phasor& a, const Phasor& b) { + Phasor result = a; + result += b; + return result; +} + +Phasor operator - (const Phasor& a, const Phasor& b) { + Phasor result = a; + result -= b; + return result; +} + +Phasor operator * (const Phasor& a, const Phasor& b) { + Phasor result = a; + result *= b; + return result; +} + +Phasor operator / (const Phasor& a, const Phasor& b) { + Phasor result = a; + result /= b; + return result; +} + +// Операции с вещественными числами + +Phasor operator + (const Phasor& a, double b) { + return a + Phasor(b, 0.0, AlgTag{}); +} + +Phasor operator + (double a, const Phasor& b) { + return Phasor(a, 0.0, AlgTag{}) + b; +} + +Phasor operator - (const Phasor& a, double b) { + return a - Phasor(b, 0.0, AlgTag{}); +} + +Phasor operator - (double a, const Phasor& b) { + return Phasor(a, 0.0, AlgTag{}) - b; +} + +Phasor operator * (const Phasor& a, double b) { + return a * Phasor(b, 0.0, AlgTag{}); +} + +Phasor operator * (double a, const Phasor& b) { + return Phasor(a, 0.0, AlgTag{}) * b; +} + +Phasor operator / (const Phasor& a, double b) { + if (b == 0.0) { + throw std::runtime_error("Division by zero"); + } + return a / Phasor(b, 0.0, AlgTag{}); +} + +Phasor operator / (double a, const Phasor& b) { + return Phasor(a, 0.0, AlgTag{}) / b; +} + +// Операторы сравнения + +bool operator == (const Phasor& a, const Phasor& b) { + const double eps = 1e-10; + return std::abs(a.Real() - b.Real()) < eps && + std::abs(a.Imag() - b.Imag()) < eps; +} + +bool operator != (const Phasor& a, const Phasor& b) { + return !(a == b); +} + +// Вспомогательные функции создания + +Phasor MakePhasorCartesian(double real, double imag) { + return Phasor(real, imag, AlgTag{}); +} + +Phasor MakePhasorPolar(double magnitude, double phase_rad) { + return Phasor(magnitude, phase_rad); +} + +Phasor MakePhasorPolarDeg(double magnitude, double phase_deg) { + return Phasor(magnitude, phase_deg, DegTag{}); +} + +// Оператор вывода в поток + +std::ostream& operator << (std::ostream& os, const Phasor& p) { + double mag = p.Magnitude(); + double phase_deg = p.PhaseDeg(); + double real = p.Real(); + double imag = p.Imag(); + + // Форматируем вывод с фиксированной точностью + os.precision(6); + os << std::fixed << mag << "*e(j*" << phase_deg << ") [" + << real << " + j*" << imag << "]"; + return os; +} \ No newline at end of file From 0529a824584a1139d797710526ec88e85b40eae4 Mon Sep 17 00:00:00 2001 From: Nicolay Petrov Date: Wed, 24 Dec 2025 22:13:03 +0500 Subject: [PATCH 32/34] add (solution): add stack task --- 04_week/tasks/stack/stack.cpp | 62 ++++++++++++++++++++++++++++++++++- 1 file changed, 61 insertions(+), 1 deletion(-) diff --git a/04_week/tasks/stack/stack.cpp b/04_week/tasks/stack/stack.cpp index 222e4ffc..fb477783 100644 --- a/04_week/tasks/stack/stack.cpp +++ b/04_week/tasks/stack/stack.cpp @@ -2,5 +2,65 @@ class Stack { - +private: + std::vector stack; +public: + //Объявление методов + void Push(int val); + bool Pop(); + int& Top(); + const int& Top() const; + bool Empty() const; + size_t Size() const; + void Clear(); + void Swap(Stack& stack2); + friend bool operator==(const Stack& lhs, const Stack& rhs); + friend bool operator!=(const Stack& lhs, const Stack& rhs); }; + +//Реализация методов +void Stack::Push(int val){ + stack.push_back(val); +} + +bool Stack::Pop(){ + if (stack.empty()){ + return false; + } else{ + stack.pop_back(); + return true; + } +} + +int& Stack::Top(){ + return stack.back(); +} +//Перегрузка Top +const int& Stack::Top() const{ + return stack.back(); +} + +bool Stack::Empty() const{ + return stack.empty(); +} + +size_t Stack::Size() const{ + return stack.size(); +} + +void Stack::Clear(){ + stack.clear(); +} + +void Stack::Swap(Stack& stack2){ + stack.swap(stack2.stack); +} + +//Операторы +bool operator==(const Stack& lhs, const Stack& rhs){ + return lhs.stack == rhs.stack; +} + +bool operator!=(const Stack& lhs, const Stack& rhs){ + return lhs.stack != rhs.stack; +} \ No newline at end of file From 73054a8f4d21dc569403aa82e588679afa4db723 Mon Sep 17 00:00:00 2001 From: Nicolay Petrov Date: Thu, 25 Dec 2025 22:55:59 +0500 Subject: [PATCH 33/34] add (solution): add queue task --- 04_week/tasks/queue/queue.cpp | 172 +++++++++++++++++++++++++++++++++- 1 file changed, 171 insertions(+), 1 deletion(-) diff --git a/04_week/tasks/queue/queue.cpp b/04_week/tasks/queue/queue.cpp index 2a9f8493..55b5df87 100644 --- a/04_week/tasks/queue/queue.cpp +++ b/04_week/tasks/queue/queue.cpp @@ -1,6 +1,176 @@ #include - +#include +#include +#include class Queue { +private: + std::vector in; + std::vector out; + + // Вспомогательный метод для перекладывания элементов + void PrepareOut(); +public: + // Конструкторы + Queue() = default; + explicit Queue(size_t capacity); + explicit Queue(const std::vector& vec); + explicit Queue(const std::stack& st); + Queue(std::initializer_list list); + + //Методы + void Push(int value); + bool Pop(); + + int& Front(); + const int& Front() const; + int& Back(); + const int& Back() const; + + bool Empty() const; + size_t Size() const; + void Clear(); + void Swap(Queue& other); + + // Операторы сравнения + bool operator==(const Queue& other) const; + bool operator!=(const Queue& other) const; }; + +// Вспомогательный метод для перекладывания элементов +void Queue::PrepareOut() { + if (out.empty() && !in.empty()) { + while (!in.empty()) { + out.push_back(in.back()); + in.pop_back(); + } + } +} + +// Конструктор от размера с резервированием памяти +Queue::Queue(size_t capacity) { + in.reserve(capacity / 2 + 1); + out.reserve(capacity / 2 + 1); +} + +// Конструктор от вектора +Queue::Queue(const std::vector& vec) { + for (int value : vec) { + Push(value); + } +} + +// Конструктор от стека +Queue::Queue(const std::stack& st) { + std::stack temp = st; + std::vector tempVec; + + while (!temp.empty()) { + tempVec.push_back(temp.top()); + temp.pop(); + } + + for (auto it = tempVec.rbegin(); it != tempVec.rend(); ++it) { + Push(*it); + } +} + +// Конструктор от initializer_list +Queue::Queue(std::initializer_list list) { + for (int value : list) { + Push(value); + } +} + +// добавляет элемент в конец очереди +void Queue::Push(int value) { + in.push_back(value); +} + +// убирает элемент из начала очереди +bool Queue::Pop() { + if (Empty()) { + return false; + } + + PrepareOut(); + out.pop_back(); + return true; +} + +// обеспечивает доступ на запись и чтение к элементу в начале очереди (неконстантная версия) +int& Queue::Front() { + PrepareOut(); + return out.back(); +} + +// обеспечивает доступ на запись и чтение к элементу в начале очереди (константная версия) +const int& Queue::Front() const { + // Используем const_cast для вызова PrepareOut на временном объекте + Queue* mutableThis = const_cast(this); + mutableThis->PrepareOut(); + return out.back(); +} + +// обеспечивает доступ на запись и чтение к элементу в конце очереди (неконстантная версия) +int& Queue::Back() { + if (!in.empty()) { + return in.back(); + } + return out.front(); +} + +// обеспечивает доступ на запись и чтение к элементу в конце очереди (константная версия) +const int& Queue::Back() const { + if (!in.empty()) { + return in.back(); + } + return out.front(); +} + +// возвращает результат проверки очереди на отсутствие элементов +bool Queue::Empty() const { + return in.empty() && out.empty(); +} + +// возвращает количество элементов в очереди +size_t Queue::Size() const { + return in.size() + out.size(); +} + +// очищает очередь +void Queue::Clear() { + in.clear(); + out.clear(); +} + +// меняется элементами с другой очередью (без копирования) +void Queue::Swap(Queue& other) { + in.swap(other.in); + out.swap(other.out); +} + +// Оператор сравнения на равенство +bool Queue::operator==(const Queue& other) const { + if (Size() != other.Size()) { + return false; + } + //копии для сравнения + Queue q1 = *this; + Queue q2 = other; + + while (!q1.Empty()) { + if (q1.Front() != q2.Front()) { + return false; + } + q1.Pop(); + q2.Pop(); + } + return true; +} + +// Оператор сравнения на неравенство +bool Queue::operator!=(const Queue& other) const { + return !(*this == other); +} \ No newline at end of file From 6b185e6ca01538281347c63eea027692439f34b5 Mon Sep 17 00:00:00 2001 From: Nicolay Petrov Date: Fri, 26 Dec 2025 14:35:47 +0500 Subject: [PATCH 34/34] add (solution): add ring_buffer task --- 04_week/tasks/ring_buffer/ring_buffer.cpp | 274 +++++++++++++++++++++- 1 file changed, 273 insertions(+), 1 deletion(-) diff --git a/04_week/tasks/ring_buffer/ring_buffer.cpp b/04_week/tasks/ring_buffer/ring_buffer.cpp index e2b57ba2..8e31c9dd 100644 --- a/04_week/tasks/ring_buffer/ring_buffer.cpp +++ b/04_week/tasks/ring_buffer/ring_buffer.cpp @@ -1,6 +1,278 @@ #include - +#include +#include class RingBuffer { +private: + std::vector data_; + size_t head_ = 0; + size_t tail_ = 0; + size_t size_ = 0; + bool full_ = false; + + size_t n_pos(size_t pos) const noexcept; + size_t p_pos(size_t pos) const noexcept; + void copy_nbuffer(RingBuffer& new_buffer) const; + void rebuild_buffer(size_t new_capacity); + +public: + // Конструкторы + explicit RingBuffer(size_t capacity); + RingBuffer(size_t capacity, int initial_value); + RingBuffer(std::initializer_list init); + + // Копирующие операции + RingBuffer(const RingBuffer& other); + RingBuffer& operator=(const RingBuffer& other); + void Push(int value); + bool TryPush(int value); + void Pop(); + bool TryPop(int& value); + + // Доступ к элементам + int operator[](size_t index) const; + int& operator[](size_t index); + int& Front(); + const int& Front() const; + int& Back(); + const int& Back() const; + + bool Empty() const noexcept; + bool Full() const noexcept; + size_t Size() const noexcept; + size_t Capacity() const noexcept; + void Clear() noexcept; + + // Изменение размера + void Resize(size_t new_capacity); + + // Конвертация + std::vector Vector() const; }; + +// Вспомогательные методы + +size_t RingBuffer::n_pos(size_t pos) const noexcept { + return (pos + 1) % data_.size(); +} + +size_t RingBuffer::p_pos(size_t pos) const noexcept { + return (pos == 0) ? data_.size() - 1 : pos - 1; +} + +void RingBuffer::copy_nbuffer(RingBuffer& new_buffer) const { + if (size_ == 0) return; + + for (size_t i = 0; i < size_; ++i) { + new_buffer.Push((*this)[i]); + } +} + +void RingBuffer::rebuild_buffer(size_t new_capacity) { + std::vector new_data(new_capacity); + size_t new_size = (new_capacity < size_) ? new_capacity : size_; + + for (size_t i = 0; i < new_size; ++i) { + new_data[i] = (*this)[(size_ - new_size) + i]; + } + + data_ = std::move(new_data); + head_ = 0; + tail_ = new_size % new_capacity; + size_ = new_size; + full_ = (new_size == new_capacity); +} + +// Конструкторы + +RingBuffer::RingBuffer(size_t capacity) { + size_t actual_capacity = (capacity == 0) ? 1 : capacity; + data_.resize(actual_capacity); +} + +RingBuffer::RingBuffer(size_t capacity, int initial_value) { + size_t actual_capacity = (capacity == 0) ? 1 : capacity; + data_.resize(actual_capacity); + + for (size_t i = 0; i < actual_capacity; ++i) { + data_[i] = initial_value; + } + head_ = 0; + tail_ = 0; + size_ = actual_capacity; + full_ = (actual_capacity > 0); +} + +RingBuffer::RingBuffer(std::initializer_list init) { + size_t capacity = init.size(); + if (capacity == 0) { + capacity = 1; + } + data_.resize(capacity); + + for (int value : init) { + Push(value); + } +} + +// Копирующие операции + +RingBuffer::RingBuffer(const RingBuffer& other) + : data_(other.data_), + head_(other.head_), + tail_(other.tail_), + size_(other.size_), + full_(other.full_) {} + +RingBuffer& RingBuffer::operator=(const RingBuffer& other) { + if (this != &other) { + data_ = other.data_; + head_ = other.head_; + tail_ = other.tail_; + size_ = other.size_; + full_ = other.full_; + } + return *this; +} + +// Основные операции + +void RingBuffer::Push(int value) { + if (full_) { + data_[tail_] = value; + tail_ = n_pos(tail_); + head_ = tail_; + } else { + data_[tail_] = value; + tail_ = n_pos(tail_); + ++size_; + full_ = (head_ == tail_); + } +} + +bool RingBuffer::TryPush(int value) { + if (full_) { + return false; + } + Push(value); + return true; +} + +void RingBuffer::Pop() { + if (Empty()) { + return; + } + head_ = n_pos(head_); + --size_; + full_ = false; +} + +bool RingBuffer::TryPop(int& value) { + if (Empty()) { + return false; + } + value = data_[head_]; + Pop(); + return true; +} + +// Доступ к элементам + +int RingBuffer::operator[](size_t index) const { + if (index >= size_) { + throw std::out_of_range("Index out of range"); + } + return data_[(head_ + index) % data_.size()]; +} + +int& RingBuffer::operator[](size_t index) { + if (index >= size_) { + throw std::out_of_range("Index out of range"); + } + return data_[(head_ + index) % data_.size()]; +} + +int& RingBuffer::Front() { + if (size_ == 0) { + // UB согласно условию + return data_[head_]; + } + return data_[p_pos(tail_)]; +} + +const int& RingBuffer::Front() const { + if (size_ == 0) { + // UB согласно условию + return data_[head_]; + } + return data_[p_pos(tail_)]; +} + +int& RingBuffer::Back() { + if (size_ == 0) { + // UB согласно условию + return data_[head_]; + } + return data_[head_]; +} + +const int& RingBuffer::Back() const { + if (size_ == 0) { + // UB согласно условию + return data_[head_]; + } + return data_[head_]; +} + +// Состояние буфера + +bool RingBuffer::Empty() const noexcept { + return !full_ && (head_ == tail_); +} + +bool RingBuffer::Full() const noexcept { + return full_; +} + +size_t RingBuffer::Size() const noexcept { + return size_; +} + +size_t RingBuffer::Capacity() const noexcept { + return data_.size(); +} + +void RingBuffer::Clear() noexcept { + head_ = 0; + tail_ = 0; + size_ = 0; + full_ = false; +} + +// Изменение размера + +void RingBuffer::Resize(size_t new_capacity) { + if (new_capacity == 0) { + new_capacity = 1; + } + + if (new_capacity == data_.size()) { + return; + } + + rebuild_buffer(new_capacity); +} + +// Конвертация + +std::vector RingBuffer::Vector() const { + std::vector result; + result.reserve(size_); + + for (size_t i = 0; i < size_; ++i) { + result.push_back((*this)[i]); + } + + return result; +} \ No newline at end of file