diff --git a/01_week/tasks/addition/addition.cpp b/01_week/tasks/addition/addition.cpp index 92872802..f3469331 100644 --- a/01_week/tasks/addition/addition.cpp +++ b/01_week/tasks/addition/addition.cpp @@ -1,7 +1,6 @@ #include -#include int64_t Addition(int a, int b) { - throw std::runtime_error{"Not implemented"}; -} \ No newline at end of file + return static_cast(a) + b; +} diff --git a/01_week/tasks/char_changer/char_changer.cpp b/01_week/tasks/char_changer/char_changer.cpp index 3a7344d9..5438542a 100644 --- a/01_week/tasks/char_changer/char_changer.cpp +++ b/01_week/tasks/char_changer/char_changer.cpp @@ -1,7 +1,47 @@ #include -#include +#include -size_t CharChanger(char array[], size_t size, char delimiter = ' ') { - throw std::runtime_error{"Not implemented"}; +size_t CharChanger(char array[], size_t, char delimiter = ' ') { + int counterRepeatedSymbols = 1; // Счётчик повторяющихся символов + int pos_write = 0; // Индекс для записи обработанного символа + char repeating_symbol = array[0]; // В процессе выполнения - предыдущий символ(отслеживаем повторения) + + for (char* ptr = array + 1; repeating_symbol != '\0'; ++ptr) { + if (repeating_symbol == *ptr){ + ++counterRepeatedSymbols; + continue; + } + + if (isalpha(repeating_symbol)){ + array[pos_write] = toupper(repeating_symbol); + } else if (isdigit(repeating_symbol)){ + array[pos_write] = '*'; + } else if (repeating_symbol == ' '){ + array[pos_write] = delimiter; + } else { + array[pos_write] = '_'; + } + ++pos_write; + + + if (repeating_symbol == ' ') { + counterRepeatedSymbols = 1; + } + + if (counterRepeatedSymbols >= 10){ + counterRepeatedSymbols = 0; + } + + if (counterRepeatedSymbols != 1){ + array[pos_write] = static_cast(counterRepeatedSymbols + '0'); // Преобразуем число в символ + counterRepeatedSymbols = 1; + ++pos_write; + } + + repeating_symbol = *ptr; + } + + array[pos_write] = '\0'; + return pos_write; } diff --git a/01_week/tasks/check_flags/README.md b/01_week/tasks/check_flags/README.md index b0940336..a2e605ea 100644 --- a/01_week/tasks/check_flags/README.md +++ b/01_week/tasks/check_flags/README.md @@ -8,5 +8,4 @@ Если передан флаг отсутствия проверок, то необходимо вывести пустые `[]`. -Если передано значение выходит из возможного диапазона значений, то вывод -следует оставить пустым. \ No newline at end of file +Если переданное значение выходит из возможного диапазона значений, то вывод следует оставить пустым. \ No newline at end of file diff --git a/01_week/tasks/check_flags/check_flags.cpp b/01_week/tasks/check_flags/check_flags.cpp index 75e7c652..9f39250e 100644 --- a/01_week/tasks/check_flags/check_flags.cpp +++ b/01_week/tasks/check_flags/check_flags.cpp @@ -1,5 +1,5 @@ #include -#include +#include enum class CheckFlags : uint8_t { @@ -14,5 +14,47 @@ enum class CheckFlags : uint8_t { }; void PrintCheckFlags(CheckFlags flags) { - throw std::runtime_error{"Not implemented"}; + if (flags == CheckFlags::NONE) { + std::cout << "[]"; + return; + } + + if ((static_cast(flags) & ~static_cast(CheckFlags::ALL)) != 0) { + std::cout << ""; + return; + } + + std::cout << "["; + bool first = true; + if ((static_cast(flags) & static_cast(CheckFlags::TIME)) != 0) { + if (!first) std::cout << ","; + std::cout << "TIME"; + first = false; + } + if ((static_cast(flags) & static_cast(CheckFlags::DATE)) != 0) { + if (!first) std::cout << ","; + std::cout << "DATE"; + first = false; + } + if ((static_cast(flags) & static_cast(CheckFlags::USER)) != 0) { + if (!first) std::cout << ","; + std::cout << "USER"; + first = false; + } + if ((static_cast(flags) & static_cast(CheckFlags::CERT)) != 0) { + if (!first) std::cout << ","; + std::cout << "CERT"; + first = false; + } + if ((static_cast(flags) & static_cast(CheckFlags::KEYS)) != 0) { + if (!first) std::cout << ","; + std::cout << "KEYS"; + first = false; + } + if ((static_cast(flags) & static_cast(CheckFlags::DEST)) != 0) { + if (!first) std::cout << ","; + std::cout << "DEST"; + first = false; + } + std::cout << "]"; } diff --git a/01_week/tasks/length_lit/length_lit.cpp b/01_week/tasks/length_lit/length_lit.cpp index e69de29b..7f91a3b4 100644 --- a/01_week/tasks/length_lit/length_lit.cpp +++ b/01_week/tasks/length_lit/length_lit.cpp @@ -0,0 +1,67 @@ +#include + + +// Константы для преобразования +constexpr long double IN_TO_CM = 2.54L; +constexpr long double FT_TO_IN = 12.0L; +constexpr long double M_TO_CM = 100.0L; + +// ft -> in +double operator"" _ft_to_in(long double ft_value) { + return static_cast(ft_value * FT_TO_IN); +} + +// ft -> cm +double operator"" _ft_to_cm(long double ft_value) { + return static_cast(ft_value * FT_TO_IN * IN_TO_CM); +} + +// ft -> m +double operator"" _ft_to_m(long double ft_value) { + return static_cast(ft_value * FT_TO_IN * IN_TO_CM / M_TO_CM); +} + +// in -> ft +double operator"" _in_to_ft(long double in_value) { + return static_cast(in_value / FT_TO_IN); +} + +// in -> cm +double operator"" _in_to_cm(long double in_value) { + return static_cast(in_value * IN_TO_CM); +} + +// in -> m +double operator"" _in_to_m(long double in_value) { + return static_cast(in_value * IN_TO_CM / M_TO_CM); +} + +// cm -> ft +double operator"" _cm_to_ft(long double cm_value) { + return static_cast(cm_value / IN_TO_CM / FT_TO_IN); +} + +// cm -> in +double operator"" _cm_to_in(long double cm_value) { + return static_cast(cm_value / IN_TO_CM); +} + +// cm -> m +double operator"" _cm_to_m(long double cm_value) { + return static_cast(cm_value / M_TO_CM); +} + +// m -> ft +double operator"" _m_to_ft(long double m_value) { + return static_cast(m_value * M_TO_CM / IN_TO_CM / FT_TO_IN); +} + +// m -> in +double operator"" _m_to_in(long double m_value) { + return static_cast(m_value * M_TO_CM / IN_TO_CM); +} + +// m -> cm +double operator"" _m_to_cm(long double m_value) { + return static_cast(m_value * M_TO_CM); +} \ No newline at end of file diff --git a/01_week/tasks/print_bits/print_bits.cpp b/01_week/tasks/print_bits/print_bits.cpp index a48a43c1..155a3b45 100644 --- a/01_week/tasks/print_bits/print_bits.cpp +++ b/01_week/tasks/print_bits/print_bits.cpp @@ -1,7 +1,27 @@ #include -#include +#include +#include void PrintBits(long long value, size_t bytes) { - throw std::runtime_error{"Not implemented"}; -} + if (bytes <= 0 || bytes > 8) { + return; + } + + std::cout << "0b"; + + // Выводим биты, начиная со старшего + for (int i = bytes * 8 - 1; i >= 0; --i) { + // "Выталкиваем" все биты, кроме i-ого, так чтобы i-ый был последним и выводим этот бит + if ((value >> i) & 1) { + std::cout << 1; + } else { + std::cout << 0; + } + + if (i != 0 && i % 4 == 0) { + std::cout << "'"; + } + } + std::cout << '\n'; +} \ No newline at end of file diff --git a/01_week/tasks/quadratic/quadratic.cpp b/01_week/tasks/quadratic/quadratic.cpp index abf7d632..4fcf562e 100644 --- a/01_week/tasks/quadratic/quadratic.cpp +++ b/01_week/tasks/quadratic/quadratic.cpp @@ -1,6 +1,35 @@ -#include +#include +#include +#include +#include // Для std::min и std::max void SolveQuadratic(int a, int b, int c) { - throw std::runtime_error{"Not implemented"}; + if (a == 0) { + if (b == 0) { + if (c == 0) { + std::cout << "infinite solutions"; + } else { + std::cout << "no solutions"; + } + } else { + double x = static_cast(-c) / b; + std::cout << std::defaultfloat << std::setprecision(6) << x; + } + } else { + long long discriminant = static_cast(b) * b - 4 * static_cast(a) * c; + + if (discriminant > 0) { + double x1 = (-b - std::sqrt(static_cast(discriminant))) / (2 * a); + double x2 = (-b + std::sqrt(static_cast(discriminant))) / (2 * a); + std::cout << std::defaultfloat << std::setprecision(6) << std::min(x1, x2); + std::cout << " "; + std::cout << std::defaultfloat << std::setprecision(6) << std::max(x1, x2); + } else if (discriminant == 0) { + double x = static_cast(-b) / (2 * a); + std::cout << std::defaultfloat << std::setprecision(6) << x; + } else { + std::cout << "no solutions"; + } + } } \ No newline at end of file diff --git a/01_week/tasks/rms/rms.cpp b/01_week/tasks/rms/rms.cpp index 6882f0a9..75bcb8c0 100644 --- a/01_week/tasks/rms/rms.cpp +++ b/01_week/tasks/rms/rms.cpp @@ -1,7 +1,14 @@ -#include -#include +#include +#include double CalculateRMS(double values[], size_t size) { - throw std::runtime_error{"Not implemented"}; -} \ No newline at end of file + if (size <= 0 || values == nullptr){ return 0.0; } + + double sum = 0; + for (size_t i=0; i < size; ++i){ + sum+=std::pow(values[i], 2); + } + + return std::sqrt(sum / size); +} diff --git a/02_week/tasks/func_array/func_array.cpp b/02_week/tasks/func_array/func_array.cpp index b327e68d..ef115411 100644 --- a/02_week/tasks/func_array/func_array.cpp +++ b/02_week/tasks/func_array/func_array.cpp @@ -1,6 +1,19 @@ -#include +#include +using funcPtr = double (*)(double, double); -double ApplyOperations(double a, double b /* other arguments */) { - throw std::runtime_error{"Not implemented"}; +double ApplyOperations(const double a, const double b, funcPtr* arr, size_t funcArraySize) { + if (arr == nullptr || funcArraySize <= 0){ + return 0.0; + } + + double cumulative_result = 0; + for (unsigned int i=0; i < funcArraySize; ++i){ + if (arr[i] == nullptr){ + continue; + } + cumulative_result+=arr[i](a, b); + } + + return cumulative_result; } \ No newline at end of file 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..b63142c8 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,25 @@ -#include +#include +using funcPtr = bool (*)(int); -/* 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, funcPtr predicate) { + if (begin == nullptr || end == nullptr || predicate == nullptr){ + return end; + } + + if (begin >= end){ + return end; + } + + const int* last_element = end; + + while (begin < end) + { + --end; + if (predicate(*end)){ + return end; + } + } + + return last_element; } \ No newline at end of file diff --git a/02_week/tasks/little_big/little_big.cpp b/02_week/tasks/little_big/little_big.cpp index abe24379..b8f40a5e 100644 --- a/02_week/tasks/little_big/little_big.cpp +++ b/02_week/tasks/little_big/little_big.cpp @@ -1,10 +1,47 @@ -#include +#include +#include +#include +#include -void PrintMemory(int /* write arguments here */) { - throw std::runtime_error{"Not implemented"}; +void PrintMemory(int number, bool inversion = false) { + unsigned char* bytes = reinterpret_cast(&number); + + std::cout << "0x"; + if (inversion) { + // Читаем байты в обратном порядке сразу при выводе + for (size_t i = sizeof(int); i > 0; --i) { + std::cout << std::hex << std::uppercase + << std::setfill('0') << std::setw(2) + << static_cast(bytes[i-1]); + } + } else { + for (size_t i = 0; i < sizeof(int); ++i) { + std::cout << std::hex << std::uppercase + << std::setfill('0') << std::setw(2) + << static_cast(bytes[i]); + } + } + std::cout << std::dec << std::endl; } -void PrintMemory(double /* write arguments here */) { - throw std::runtime_error{"Not implemented"}; +void PrintMemory(double number, bool inversion = false) { + unsigned char* bytes = reinterpret_cast(&number); + + std::cout << "0x"; + if (inversion) { + // Читаем байты в обратном порядке сразу при выводе + for (size_t i = sizeof(double); i > 0; --i) { + std::cout << std::hex << std::uppercase + << std::setfill('0') << std::setw(2) + << static_cast(bytes[i-1]); + } + } else { + for (size_t i = 0; i < sizeof(double); ++i) { + std::cout << std::hex << std::uppercase + << std::setfill('0') << std::setw(2) + << static_cast(bytes[i]); + } + } + std::cout << std::dec << std::endl; } \ No newline at end of file diff --git a/02_week/tasks/longest/longest.cpp b/02_week/tasks/longest/longest.cpp index 04b3c354..f14d3470 100644 --- a/02_week/tasks/longest/longest.cpp +++ b/02_week/tasks/longest/longest.cpp @@ -1,6 +1,47 @@ -#include +const char* FindLongestSubsequence(const char* begin, const char* end, size_t &count) { + if (begin == nullptr || end == nullptr || begin >= end){ + count = 0; + return nullptr; + } + const char* startOfSubsequence = begin; + const char* left = begin; + const char* right = ++begin; + int max_length = 1; + int length = 1; -/* return_type */ FindLongestSubsequence(/* ptr_type */ begin, /* ptr_type */ end, /* type */ count) { - throw std::runtime_error{"Not implemented"}; + while (right != end) + { + if (*left == *right){ + ++right; + ++length; + } else { + if (length > max_length){ + startOfSubsequence = left; + max_length = length; + } + + length = 0; + left = right; + } + } + + if (length > max_length){ + startOfSubsequence = left; + max_length = length; + } + + count = max_length; + return startOfSubsequence; } + +char* FindLongestSubsequence(char* begin, char* end, size_t &count) { + // Вызываем константную версию + const char* result = FindLongestSubsequence( + const_cast(begin), + const_cast(end), + count + ); + // Снимаем константность + return const_cast(result); +} \ No newline at end of file diff --git a/02_week/tasks/pretty_array/pretty_array.cpp b/02_week/tasks/pretty_array/pretty_array.cpp index 48eab341..461c929e 100644 --- a/02_week/tasks/pretty_array/pretty_array.cpp +++ b/02_week/tasks/pretty_array/pretty_array.cpp @@ -1,6 +1,33 @@ -#include +#include +void PrintArray(const int* begin, const int* end, const int count = 0) { + if (!begin || !end || begin == end || count < 0) { + std::cout << "[]\n"; + return; + } -void PrintArray(/* write arguments here */) { - throw std::runtime_error{"Not implemented"}; + // Определяем направление: 1 для движения вперед, -1 для движения назад + const int step = (begin < end) ? 1 : -1; + + // Вычисляем количество элементов (всегда положительное) + const int total_elements = (step == 1) ? (end - begin) : (begin - end); + + std::cout << "["; + for (int i = 0; i < total_elements; ++i) { + // Вычисляем текущий указатель на основе индекса и шага + const int* ptr = begin + (i * step); + + // Логика переноса строки (count) + if (count > 0 && i > 0 && i % count == 0) { + std::cout << "...\n "; + } + + std::cout << *ptr; + + // Запятая, если это не последний элемент + if (i < total_elements - 1) { + std::cout << ", "; + } + } + std::cout << "]\n"; } \ No newline at end of file diff --git a/02_week/tasks/swap_ptr/swap_ptr.cpp b/02_week/tasks/swap_ptr/swap_ptr.cpp index 93db625d..2813af8f 100644 --- a/02_week/tasks/swap_ptr/swap_ptr.cpp +++ b/02_week/tasks/swap_ptr/swap_ptr.cpp @@ -1,6 +1,6 @@ -#include - - -void SwapPtr(/* write arguments here */) { - throw std::runtime_error{"Not implemented"}; +template +void SwapPtr(T*& ptr1, T*& ptr2) { + T* temp = ptr2; + ptr2 = ptr1; + ptr1 = temp; } \ No newline at end of file diff --git a/03_week/tasks/data_stats/data_stats.cpp b/03_week/tasks/data_stats/data_stats.cpp index b941c211..70bc78e5 100644 --- a/03_week/tasks/data_stats/data_stats.cpp +++ b/03_week/tasks/data_stats/data_stats.cpp @@ -1,11 +1,32 @@ -#include - +#include +#include struct DataStats { double avg = 0.0; double sd = 0.0; }; -/* return_type */ CalculateDataStats(/* args */) { - throw std::runtime_error{"Not implemented"}; -} +DataStats CalculateDataStats(const std::vector& numArray) { + double average = 0.0; + double standardDeviation = 0.0; + + if (!numArray.empty()){ + double delta = 0.0; + double delta2 = 0.0; + int count = 0.0; + + for (double num : numArray){ + ++count; + delta = num - average; + average += delta / count; + delta2 = num - average; + standardDeviation += delta * delta2; + } + + standardDeviation = std::sqrt(standardDeviation / count); + } + + DataStats datastats = {average, standardDeviation}; + + return datastats; +} \ No newline at end of file diff --git a/03_week/tasks/easy_compare/easy_compare.cpp b/03_week/tasks/easy_compare/easy_compare.cpp index dd5cb7f6..60471f49 100644 --- a/03_week/tasks/easy_compare/easy_compare.cpp +++ b/03_week/tasks/easy_compare/easy_compare.cpp @@ -1,10 +1,37 @@ -#include - +#include +#include struct Date { - unsigned year; - unsigned month; - unsigned day; + unsigned year = 0u; + unsigned month = 0u; + unsigned day = 0u; + + Date(){} + Date(unsigned year, unsigned month, unsigned day) : year(year), month(month), day(day){} + + bool operator==(Date other) const { + return std::tie(year, month, day) == std::tie(other.year, other.month, other.day); + } + + bool operator!=(Date other) const { + return !(*this == other); + } + + bool operator<(Date other) const { + return std::tie(year, month, day) < std::tie(other.year, other.month, other.day); + } + + bool operator>(Date other) const { + return std::tie(year, month, day) > std::tie(other.year, other.month, other.day); + } + + bool operator>=(Date other) const { + return *this > other || *this == other; + } + + bool operator<=(Date other) const { + return *this < other || *this == other; + } }; struct StudentInfo { @@ -13,4 +40,32 @@ struct StudentInfo { int score; unsigned course; Date birth_date; + + StudentInfo(){} + StudentInfo(size_t id, char mark, int score, unsigned course, Date birth_date) : + id(id), mark(mark), score(score), course(course), birth_date(birth_date){} + + bool operator==(StudentInfo other) const { + return std::tie(mark, score) == std::tie(other.mark, other.score); + } + + bool operator!=(StudentInfo other) const { + return !(*this == other); + } + + bool operator<(StudentInfo other) const { + return std::tie(other.mark, score, other.course, birth_date) < std::tie(mark, other.score, course, other.birth_date); + } + + bool operator>(StudentInfo other) const { + return std::tie(other.mark, score, other.course, birth_date) > std::tie(mark, other.score, course, other.birth_date); + } + + bool operator>=(StudentInfo other) const { + return *this > other || *this == other; + } + + bool operator<=(StudentInfo other) const { + return *this < other || *this == other; + } }; \ No newline at end of file diff --git a/03_week/tasks/enum_operators/enum_operators.cpp b/03_week/tasks/enum_operators/enum_operators.cpp index a539be38..646b6f3a 100644 --- a/03_week/tasks/enum_operators/enum_operators.cpp +++ b/03_week/tasks/enum_operators/enum_operators.cpp @@ -1,5 +1,5 @@ -#include -#include +#include +#include enum class CheckFlags : uint8_t { NONE = 0, @@ -12,22 +12,89 @@ enum class CheckFlags : uint8_t { ALL = TIME | DATE | USER | CERT | KEYS | DEST }; -/* return_type */ operator|(/* args */) { - throw std::runtime_error{"Not implemented"}; +CheckFlags operator|(CheckFlags a, CheckFlags b) { + uint8_t a_val = static_cast(a); + uint8_t b_val = static_cast(b); + uint8_t result = a_val | b_val; + + uint8_t valid_result = result & static_cast(CheckFlags::ALL); + return static_cast(valid_result); } -/* return_type */ operator&(/* args */) { - throw std::runtime_error{"Not implemented"}; +bool operator&(CheckFlags a, CheckFlags b) { + uint8_t a_val = static_cast(a); + uint8_t b_val = static_cast(b); + + uint8_t a_valid = a_val & static_cast(CheckFlags::ALL); + uint8_t b_valid = b_val & static_cast(CheckFlags::ALL); + + if (a_valid == 0 || b_valid == 0) { + return false; + } + + return (a_valid & b_valid) == a_valid || (a_valid & b_valid) == b_valid; } -/* return_type */ operator^(/* args */) { - throw std::runtime_error{"Not implemented"}; +CheckFlags operator^(CheckFlags a, CheckFlags b) { + uint8_t a_val = static_cast(a); + uint8_t b_val = static_cast(b); + + uint8_t a_valid = a_val & static_cast(CheckFlags::ALL); + uint8_t b_valid = b_val & static_cast(CheckFlags::ALL); + + uint8_t result = a_valid ^ b_valid; + return static_cast(result); } -/* return_type */ operator~(/* args */) { - throw std::runtime_error{"Not implemented"}; +CheckFlags operator~(CheckFlags a) { + uint8_t a_val = static_cast(a); + uint8_t a_valid = a_val & static_cast(CheckFlags::ALL); + + uint8_t result = ~a_valid & static_cast(CheckFlags::ALL); + + return static_cast(result); } -/* return_type */ operator<<(/* args */) { - throw std::runtime_error{"Not implemented"}; -} +std::ostream& operator<<(std::ostream& os, CheckFlags flags) { + uint8_t flags_val = static_cast(flags); + uint8_t valid_flags = flags_val & static_cast(CheckFlags::ALL); + + if (valid_flags == 0) { + os << "NONE"; + return os; + } + + bool first = true; + if ((valid_flags & static_cast(CheckFlags::TIME)) != 0) { + if (!first) os << ", "; + os << "TIME"; + first = false; + } + if ((valid_flags & static_cast(CheckFlags::DATE)) != 0) { + if (!first) os << ", "; + os << "DATE"; + first = false; + } + if ((valid_flags & static_cast(CheckFlags::USER)) != 0) { + if (!first) os << ", "; + os << "USER"; + first = false; + } + if ((valid_flags & static_cast(CheckFlags::CERT)) != 0) { + if (!first) os << ", "; + os << "CERT"; + first = false; + } + if ((valid_flags & static_cast(CheckFlags::KEYS)) != 0) { + if (!first) os << ", "; + os << "KEYS"; + first = false; + } + if ((valid_flags & static_cast(CheckFlags::DEST)) != 0) { + if (!first) os << ", "; + os << "DEST"; + first = false; + } + + return os; +} \ No newline at end of file diff --git a/03_week/tasks/filter/filter.cpp b/03_week/tasks/filter/filter.cpp index 6648cb39..5a12ad06 100644 --- a/03_week/tasks/filter/filter.cpp +++ b/03_week/tasks/filter/filter.cpp @@ -1,6 +1,20 @@ -#include +#include +#include // Для std::is_same_v - -/* return_type */ Filter(/* args */) { - throw std::runtime_error{"Not implemented"}; -} \ No newline at end of file +template +void Filter(std::vector& array, Predicat func) { + if constexpr (!std::is_same_v) { + if (array.empty()){ + return; + } + + int lagging = 0; + for (size_t i=0; i < array.size(); ++i){ + if (func(array[i])){ + array[lagging] = array[i]; + ++lagging; + } + } + array.resize(lagging); + } +} diff --git a/03_week/tasks/find_all/find_all.cpp b/03_week/tasks/find_all/find_all.cpp index 74f393b2..6a0f1036 100644 --- a/03_week/tasks/find_all/find_all.cpp +++ b/03_week/tasks/find_all/find_all.cpp @@ -1,6 +1,22 @@ -#include +#include +#include // Для std::is_same_v +template +std::vector FindAll(const std::vector& array, Predicat func) { + if constexpr (!std::is_same_v) { + if (array.empty()){ + return {}; + } -/* return_type */ FindAll(/* args */) { - throw std::runtime_error{"Not implemented"}; + std::vector result; + for (size_t i = 0; i < array.size(); ++i) { + if (func(array[i])) { + result.push_back(i); + } + } + result.shrink_to_fit(); + return result; + } + + return {}; } \ No newline at end of file diff --git a/03_week/tasks/minmax/minmax.cpp b/03_week/tasks/minmax/minmax.cpp index c2869799..c5cbe99b 100644 --- a/03_week/tasks/minmax/minmax.cpp +++ b/03_week/tasks/minmax/minmax.cpp @@ -1,6 +1,22 @@ -#include +#include +#include // Для std::pair и std::make_pair +std::pair::const_iterator, std::vector::const_iterator> MinMax(const std::vector& vec) { + if (vec.empty()) { + return std::make_pair(vec.end(), vec.end()); + } -/* return_type */ MinMax(/* args */) { - throw std::runtime_error{"Not implemented"}; + auto min_it = vec.begin(); + auto max_it = vec.begin(); + + for (auto it = vec.begin() + 1; it != vec.end(); ++it) { + if (*it < *min_it) { + min_it = it; + } + if (*it >= *max_it) { + max_it = it; + } + } + + return std::make_pair(min_it, max_it); } diff --git a/03_week/tasks/os_overload/os_overload.cpp b/03_week/tasks/os_overload/os_overload.cpp index e473418d..6521b492 100644 --- a/03_week/tasks/os_overload/os_overload.cpp +++ b/03_week/tasks/os_overload/os_overload.cpp @@ -1,21 +1,64 @@ -#include +#include #include #include struct Coord2D { - int x; - int y; + int x = 0; + int y = 0; + + Coord2D(){} + Coord2D(int x_val, int y_val) : x(x_val), y(y_val) {} }; + struct Circle { Coord2D coord; - unsigned radius; + unsigned radius = 1; + + Circle(){} + Circle(Coord2D c_val) : coord(c_val){} + Circle(Coord2D c_val, unsigned r_val) : coord(c_val), radius(r_val) {} }; + 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) { + if (circle.radius == 0) { + os << "circle[]"; + } else { + os << "circle[" << circle.coord << ", r = " << circle.radius << "]"; + } + 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 << ",\n"; + } else { + os << "\n"; + } + } + os << "}"; + } + return os; } diff --git a/03_week/tasks/range/range.cpp b/03_week/tasks/range/range.cpp index d2085495..7e0fae07 100644 --- a/03_week/tasks/range/range.cpp +++ b/03_week/tasks/range/range.cpp @@ -1,7 +1,21 @@ -#include #include +std::vector Range(int from, int to, int step = 1) { + if (step == 0) { + return {}; + } -std::vector Range(int from, int to, int step) { - throw std::runtime_error{"Not implemented"}; + if ((step > 0 && from >= to) || (step < 0 && from <= to)) { + return {}; + } + + int count = (to - from + step - (step > 0 ? 1 : -1)) / step; + std::vector result; + result.reserve(count); + + for (int i = 0; i < count; ++i) { + result.push_back(from + i * step); + } + + return result; } diff --git a/03_week/tasks/unique/unique.cpp b/03_week/tasks/unique/unique.cpp index 9d2545bb..82cd2394 100644 --- a/03_week/tasks/unique/unique.cpp +++ b/03_week/tasks/unique/unique.cpp @@ -1,6 +1,18 @@ -#include #include -/* return_type */ Unique(/* args */) { - throw std::runtime_error{"Not implemented"}; +std::vector Unique(const std::vector& input_vector) { + if (input_vector.empty()) { + return {}; + } + + std::vector result; + result.reserve(input_vector.size()); + result.push_back(input_vector[0]); + for (size_t i = 1; i < input_vector.size(); ++i) { + if (input_vector[i] != input_vector[i-1]) { + result.push_back(input_vector[i]); + } + } + result.shrink_to_fit(); + return result; } diff --git a/04_week/tasks/phasor/phasor.cpp b/04_week/tasks/phasor/phasor.cpp index 3ec1b9ad..6055f6a2 100644 --- a/04_week/tasks/phasor/phasor.cpp +++ b/04_week/tasks/phasor/phasor.cpp @@ -1,10 +1,267 @@ +#define _USE_MATH_DEFINES +#include +#include +#include -struct ExpTag {}; -struct DegTag {}; -struct AlgTag {}; +struct ExpTag{}; +struct DegTag{}; +struct AlgTag{}; -class Phasor { +class Phasor +{ + double real; + double imag; +public: + Phasor() : real(0.0), imag(0.0) {} + Phasor(double amplitude, double phase) : real(amplitude * std::cos(phase)), imag(amplitude * std::sin(phase)) {} + Phasor(double amplitude, double phase, ExpTag) : Phasor(amplitude, phase) {} + Phasor(double amplitude, double phase, DegTag) : Phasor(amplitude, M_PI * phase / 180) {} + Phasor(double real, double imag, AlgTag) : real(real), imag(imag) {} + + void SetPolar(const double &r, const double &angle); + void SetCartesian(const double &x, const double &y); + double Magnitude() const; + double Abs() const; + double Phase() const; + double Angle() const; + double PhaseDeg() const; + double AngleDeg() const; + double Real() const; + double Imag() const; + Phasor Conj() const; + Phasor Inv() const; + + Phasor operator+(const Phasor &other) const; + Phasor operator-(const Phasor &other) const; + Phasor operator*(const Phasor &other) const; + Phasor operator/(const Phasor &other) const; + Phasor operator-() const; + + Phasor& operator+=(const Phasor &other); + Phasor& operator-=(const Phasor &other); + Phasor& operator*=(const Phasor &other); + Phasor& operator/=(const Phasor &other); + + bool operator==(const Phasor &other) const; + bool operator!=(const Phasor &other) const; + + friend std::ostream& operator<<(std::ostream& os, const Phasor& phasor); }; + + +Phasor operator+(const Phasor &p, double scalar); +Phasor operator+(double scalar, const Phasor &p); +Phasor operator-(const Phasor &p, double scalar); +Phasor operator-(double scalar, const Phasor &p); +Phasor operator*(const Phasor &p, double scalar); +Phasor operator*(double scalar, const Phasor &p); +Phasor operator/(const Phasor &p, double scalar); +Phasor operator/(double scalar, const Phasor &p); + +void Phasor::SetPolar(const double &r, const double &angle) +{ + real = r * std::cos(angle); + imag = r * std::sin(angle); +} + +void Phasor::SetCartesian(const double &x, const double &y) +{ + real = x; + imag = y; +} + +double Phasor::Magnitude() const +{ + return std::sqrt(real * real + imag * imag); +} + +double Phasor::Abs() const +{ + return std::sqrt(real * real + imag * imag); +} + +double Phasor::Phase() const +{ + return std::atan2(imag, real); +} + +double Phasor::Angle() const +{ + return std::atan2(imag, real); +} + +double Phasor::PhaseDeg() const +{ + double angle_deg = 180 * Phase() / M_PI; + if (angle_deg > 180.0) { + angle_deg = 180.0; + } else if (angle_deg <= -180.0) { + angle_deg = 180.0; + } + return angle_deg; +} + +double Phasor::AngleDeg() const +{ + double angle_deg = 180 * Phase() / M_PI; + if (angle_deg > 180.0) { + angle_deg = 180.0; + } else if (angle_deg <= -180.0) { + angle_deg = 180.0; + } + return angle_deg; +} + +double Phasor::Real() const +{ + return real; +} + +double Phasor::Imag() const +{ + return imag; +} + +Phasor Phasor::operator+(const Phasor &other) const +{ + return Phasor(real + other.Real(), imag + other.Imag(), AlgTag{}); +} + +Phasor Phasor::operator-(const Phasor &other) const +{ + return Phasor(real - other.Real(), imag - other.Imag(), AlgTag{}); +} + +Phasor Phasor::operator*(const Phasor &other) const +{ + return Phasor(real * other.Real() - imag * other.Imag(), real * other.Imag() + imag * other.Real(), AlgTag{}); +} + +Phasor Phasor::operator/(const Phasor &other) const +{ + double denominator = other.Real() * other.Real() + other.Imag() * other.Imag(); + return Phasor((real * other.Real() + imag * other.Imag()) / denominator, (imag * other.Real() - real * other.Imag()) / denominator, AlgTag{}); +} + +Phasor Phasor::operator-() const +{ + return Phasor(-real, -imag, AlgTag{}); +} + +Phasor& Phasor::operator+=(const Phasor &other) +{ + real += other.Real(); + imag += other.Imag(); + return *this; +} + +Phasor& Phasor::operator-=(const Phasor &other) +{ + real -= other.Real(); + imag -= other.Imag(); + return *this; +} + +Phasor& Phasor::operator*=(const Phasor &other) +{ + SetCartesian(real * other.Real() - imag * other.Imag(), real * other.Imag() + imag * other.Real()); + return *this; +} + +Phasor& Phasor::operator/=(const Phasor &other) +{ + double denominator = other.Real() * other.Real() + other.Imag() * other.Imag(); + SetCartesian((real * other.Real() + imag * other.Imag()) / denominator, (imag * other.Real() - real * other.Imag()) / denominator); + return *this; +} + +bool Phasor::operator==(const Phasor &other) const +{ + const double EPSILON = 1e-9; + return (std::abs(real - other.Real()) < EPSILON && std::abs(imag - other.Imag()) < EPSILON); +} + +bool Phasor::operator!=(const Phasor &other) const +{ + return !(*this == other); +} + +Phasor Phasor::Conj() const +{ + return Phasor(real, -imag, AlgTag{}); +} + +Phasor Phasor::Inv() const +{ + double mag_sq = Magnitude() * Magnitude(); + if (mag_sq == 0.0) { + return Phasor(0.0, 0.0, AlgTag{}); + } else { + return Phasor(real / mag_sq, -imag / mag_sq, AlgTag{}); + } +} + +Phasor MakePhasorCartesian(double real, double imag) +{ + return Phasor(real, imag, AlgTag{}); +} + +Phasor MakePhasorPolar(double amplitude, double phase) +{ + return Phasor(amplitude, phase, ExpTag{}); +} + +Phasor MakePhasorPolarDeg(double amplitude, double phase_deg) +{ + return Phasor(amplitude, phase_deg, DegTag{}); +} + +Phasor operator+(const Phasor &p, double scalar) +{ + return Phasor(p.Real() + scalar, p.Imag(), AlgTag{}); +} + +Phasor operator+(double scalar, const Phasor &p) +{ + return Phasor(p.Real() + scalar, p.Imag(), AlgTag{}); +} + +Phasor operator-(const Phasor &p, double scalar) +{ + return Phasor(p.Real() - scalar, p.Imag(), AlgTag{}); +} + +Phasor operator-(double scalar, const Phasor &p) +{ + return Phasor(scalar - p.Real(), -p.Imag(), AlgTag{}); +} + +Phasor operator*(const Phasor &p, double scalar) +{ + return Phasor(p.Magnitude() * scalar, p.Phase(), ExpTag{}); +} + +Phasor operator*(double scalar, const Phasor &p) +{ + return Phasor(p.Magnitude() * scalar, p.Phase(), ExpTag{}); +} + +Phasor operator/(const Phasor &p, double scalar) +{ + return Phasor(p.Magnitude() / scalar, p.Phase(), ExpTag{}); +} + +Phasor operator/(double scalar, const Phasor &p) +{ + return Phasor(scalar / p.Magnitude(), -p.Phase(), ExpTag{}); +} + +std::ostream& operator<<(std::ostream& os, const Phasor& phasor){ + os << std::fixed << std::setprecision(3) << phasor.Magnitude() << "*e(j*" << phasor.PhaseDeg() << ") "; + os << "[" << phasor.Real() << " + j*" << phasor.Imag() << "]"; + return os; +} + diff --git a/04_week/tasks/queue/queue.cpp b/04_week/tasks/queue/queue.cpp index 2a9f8493..4a23c1b4 100644 --- a/04_week/tasks/queue/queue.cpp +++ b/04_week/tasks/queue/queue.cpp @@ -1,6 +1,162 @@ #include +#include +#include class Queue { + std::vector input; + std::vector output; +public: + Queue(){}; + Queue(std::vector vector); + Queue(std::stack stack); + Queue(const std::initializer_list& list); + Queue(const size_t& size); + + void Push(const int& value); + + bool Pop(); + + int& Front(); + const int& Front() const; + + int& Back(); + const int& Back() const; + + bool Empty() const; + + int Size() const; + + void Clear(); + + void Swap(Queue& other); + + bool operator==(const Queue& other) const; + bool operator!=(const Queue& other) const; }; + + +Queue::Queue(std::vector vector) : output(std::move(vector)) { + std::reverse(output.begin(), output.end()); +} + +Queue::Queue(std::stack stack) { + while (!stack.empty()) { + output.push_back(stack.top()); + stack.pop(); + } +} + +Queue::Queue(const std::initializer_list& list) : output(list) { + std::reverse(output.begin(), output.end()); +} + +Queue::Queue(const size_t& size){ + input.reserve(size); +} + +void Queue::Push(const int& value){ + input.push_back(value); +} + +bool Queue::Pop(){ + if (input.empty() && output.empty()){ + return false; + } + + if (output.empty()){ + output.reserve(input.size()); + while (!input.empty()){ + output.push_back(input.back()); + input.pop_back(); + } + } + + output.pop_back(); + return true; +} + +int& Queue::Front(){ + if (output.empty()){ + return input.front(); + } else { + return output.back(); + } +} + +const int& Queue::Front() const { + if (output.empty()){ + return input.front(); + } else { + return output.back(); + } +} + +int& Queue::Back(){ + if (input.empty()){ + return output.front(); + } else { + return input.back(); + } +} + +const int& Queue::Back() const { + if (input.empty()){ + return output.front(); + } else { + return input.back(); + } +} + +bool Queue::Empty() const { + return (input.empty()) && (output.empty()); +} + +int Queue::Size() const { + return input.size() + output.size(); +} + +void Queue::Clear(){ + input.clear(); + output.clear(); +} + +void Queue::Swap(Queue& other){ + std::swap(input, other.input); + std::swap(output, other.output); +} + +bool Queue::operator==(const Queue& other) const { + // Быстрая проверка на размер + if ((input.size() + output.size()) != (other.input.size() + other.output.size())) { + return false; + } + + // Вспомогательная функция для получения элемента по индексу в "виртуальном" векторе + auto getElement = [](const Queue& q, size_t index) { + // Сначала идут элементы из output в обратном порядке + if (index < q.output.size()) { + return q.output[q.output.size() - 1 - index]; + } + // Затем элементы из input в прямом порядке + return q.input[index - q.output.size()]; + }; + + // Поэлементное сравнение без выделения памяти + size_t totalSize = input.size() + output.size(); + for (size_t i = 0; i < totalSize; ++i) { + if (getElement(*this, i) != getElement(other, i)) { + return false; + } + } + + return true; +} + +bool Queue::operator!=(const Queue& other) const { + if (*this == other){ + return false; + } + return true; +} \ No newline at end of file diff --git a/04_week/tasks/ring_buffer/ring_buffer.cpp b/04_week/tasks/ring_buffer/ring_buffer.cpp index e2b57ba2..0cf065c6 100644 --- a/04_week/tasks/ring_buffer/ring_buffer.cpp +++ b/04_week/tasks/ring_buffer/ring_buffer.cpp @@ -1,6 +1,188 @@ #include +#include class RingBuffer { + std::vector buffer; + size_t capacity = 0; + size_t size = 0; + +public: + size_t begin = 0; + size_t end = 0; + + RingBuffer(size_t size); + RingBuffer(size_t size, const int& value); + RingBuffer(const std::initializer_list& list); + + void Push(const int& value); + bool TryPush(const int& value); + + void Pop(); + bool TryPop(int& value); + + int& operator[](const size_t& idx); + const int& operator[](const size_t& idx) const; + + int& Front(); + const int& Front() const; + + int& Back(); + const int& Back() const; + + int Size() const; + + int Capacity() const; + + bool Empty() const; + + bool Full() const; + + void Clear(); + + void Resize(size_t new_size); + + std::vector Vector() const; }; + + +RingBuffer::RingBuffer(size_t size){ + if (size == 0){ + size = 1; + } + + buffer.resize(size); + capacity = size; +} + +RingBuffer::RingBuffer(size_t size, const int& value){ + if (size == 0){ + size = 1; + } + + buffer.resize(size, value); + capacity = size; + this->size = size; + end = size-1; +} + +RingBuffer::RingBuffer(const std::initializer_list& list) : RingBuffer(list.size() > 0 ? list.size() : 1) +{ + if (list.size() > 0) { + size = list.size(); + end = list.size() - 1; + begin = 0; + buffer = list; + } +} + +bool RingBuffer::TryPush(const int& value) { + if (Full()) return false; + + if (!Empty()) { + end = (end + 1) % capacity; + } + buffer[end] = value; + ++size; + return true; +} + +void RingBuffer::Push(const int& value) { + if (Full()) { + Pop(); + } + TryPush(value); +} + +bool RingBuffer::TryPop(int& value) { + if (Empty()) return false; + value = buffer[begin]; + begin = (begin + 1) % capacity; + --size; + return true; +} + +void RingBuffer::Pop() { + int trash; + TryPop(trash); +} + +int& RingBuffer::operator[](const size_t& idx) { + return buffer[(begin + idx) % capacity]; +} + +const int& RingBuffer::operator[](const size_t& idx) const { + return buffer[(begin + idx) % capacity]; +} + +int& RingBuffer::Front() { return buffer[end]; } +const int& RingBuffer::Front() const { return buffer[end]; } + +int& RingBuffer::Back() { return buffer[begin]; } +const int& RingBuffer::Back() const { return buffer[begin]; } + +int RingBuffer::Size() const { return size; } + +int RingBuffer::Capacity() const { return capacity; } + +bool RingBuffer::Empty() const { return size == 0; } + +bool RingBuffer::Full() const { return size == capacity; } + +void RingBuffer::Clear() { + end = 0; + begin = 0; + size = 0; +} + +void RingBuffer::Resize(size_t new_size) { + if (new_size == capacity) { + return; + } + + if (new_size == 0){ + new_size = 1; + } + + std::vector new_buffer(new_size); + size_t new_current_size; + + if (new_size >= size){ + for (size_t i = 0; i < size; ++i) { + new_buffer[i] = buffer[i]; + new_current_size = size; + } + } else { + size_t j = begin+(size-new_size); + for (size_t i = 0; i < new_size; ++i) { + if (i+(size-new_size) < capacity){ + new_buffer[i] = buffer[j]; + new_current_size = new_size; + } else { + i = 0; + } + + if (j+1 < capacity){ + ++j; + } else { + j = 0; + } + } + } + + buffer = std::move(new_buffer); + capacity = new_size; + size = new_current_size; + begin = 0; + end = (size == 0) ? 0 : size - 1; +} + +std::vector RingBuffer::Vector() const { + std::vector result_vector; + result_vector.reserve(size); + for (size_t i = 0; i < size; ++i) { + result_vector.push_back(buffer[(begin + i) % capacity]); + } + return result_vector; +} \ No newline at end of file diff --git a/04_week/tasks/stack/stack.cpp b/04_week/tasks/stack/stack.cpp index 222e4ffc..59cc49a9 100644 --- a/04_week/tasks/stack/stack.cpp +++ b/04_week/tasks/stack/stack.cpp @@ -2,5 +2,70 @@ class Stack { + std::vector stack; +public: + void Push(const int& value); + + int& Top(); + const int& Top() const; + + int Pop(); + + bool Empty() const; + + int Size() const; + + void Clear(); + + void Swap(Stack& other); + + bool operator==(const Stack& other) const; + + bool operator!=(const Stack& other) const; }; + +void Stack::Push(const int& value){ + stack.push_back(value); +} + +int& Stack::Top() { + return stack.back(); +} + +const int& Stack::Top() const { + return stack.back(); +} + +int Stack::Pop(){ + if (!Empty()){ + int value = stack.back(); + stack.pop_back(); + return value; + } + return 0; +} + +bool Stack::Empty() const { + return stack.empty(); +} + +int Stack::Size() const { + return stack.size(); +} + +void Stack::Clear(){ + stack.clear(); +} + +void Stack::Swap(Stack& other){ + std::swap((*this).stack, other.stack); +} + +bool Stack::operator==(const Stack& other) const { + return ((*this).stack == other.stack); +} + +bool Stack::operator!=(const Stack& other) const { + return !(*this == other); +} diff --git a/main.cpp b/main.cpp index 9dad8356..b7a6622d 100644 --- a/main.cpp +++ b/main.cpp @@ -2,6 +2,6 @@ int main() { - std::cout << "I wait your unbelievable code here" << std::endl; + std::cout << "My unbelievable code here" << std::endl; return 0; -} +} \ No newline at end of file