diff --git a/01_week/tasks/addition/addition.cpp b/01_week/tasks/addition/addition.cpp index 92872802..3529a582 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"}; + return static_cast(a) + static_cast(b); } \ No newline at end of file diff --git a/01_week/tasks/char_changer/char_changer.cpp b/01_week/tasks/char_changer/char_changer.cpp index 3a7344d9..be2df247 100644 --- a/01_week/tasks/char_changer/char_changer.cpp +++ b/01_week/tasks/char_changer/char_changer.cpp @@ -1,7 +1,49 @@ #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 counter = 0; // Счётчик повторяющихся символов + int write = 0; // Указатель для записи обработанного символа + int read = 0; // Указатель для чтения следующего элемента из массива + char repeating_symbol = array[read]; // В процессе выполнения - редыдущий символ после read(отслеживаем повторения) + + while (repeating_symbol != '\0'){ + if (repeating_symbol == array[read]){ + counter++; + } else { + if (isalpha(repeating_symbol)){ + array[write] = toupper(repeating_symbol); + } else if (isdigit(repeating_symbol)){ + array[write] = '*'; + } else if (repeating_symbol == ' '){ + array[write] = delimiter; + } else { + array[write] = '_'; + } + + write++; + + if (repeating_symbol == ' ') { + counter = 1; + } + + if (counter >= 10){ + counter = 0; + } + + if (counter != 1){ + array[write] = static_cast(counter + '0'); // Преобразуем число в символ + counter = 1; + write++; + } + + repeating_symbol = array[read]; + } + + read++; + } + + array[write] = '\0'; + return write; +} \ No newline at end of file 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..22507684 100644 --- a/01_week/tasks/check_flags/check_flags.cpp +++ b/01_week/tasks/check_flags/check_flags.cpp @@ -1,5 +1,7 @@ #include -#include +#include +#include +#include enum class CheckFlags : uint8_t { @@ -14,5 +16,42 @@ 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::vector set_flags; + if ((static_cast(flags) & static_cast(CheckFlags::TIME)) != 0) { + set_flags.push_back("TIME"); + } + if ((static_cast(flags) & static_cast(CheckFlags::DATE)) != 0) { + set_flags.push_back("DATE"); + } + if ((static_cast(flags) & static_cast(CheckFlags::USER)) != 0) { + set_flags.push_back("USER"); + } + if ((static_cast(flags) & static_cast(CheckFlags::CERT)) != 0) { + set_flags.push_back("CERT"); + } + if ((static_cast(flags) & static_cast(CheckFlags::KEYS)) != 0) { + set_flags.push_back("KEYS"); + } + if ((static_cast(flags) & static_cast(CheckFlags::DEST)) != 0) { + set_flags.push_back("DEST"); + } + + std::cout << "["; + for (size_t i = 0; i < set_flags.size(); i++) { + std::cout << set_flags[i]; + if (i < set_flags.size() - 1) { + std::cout << ","; + } + } + std::cout << "]"; +} \ No newline at end of file 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..04c4114f 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"}; + 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); } \ No newline at end of file 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/README.md b/02_week/tasks/last_of_us/README.md index 56fee4ec..077a84fb 100644 --- a/02_week/tasks/last_of_us/README.md +++ b/02_week/tasks/last_of_us/README.md @@ -4,7 +4,7 @@ элемент, удовлетворяющий условию функции предиката. Функция принимает два указателя на начало и конец целочисленного массива, а также указатель на функцию предикат, и возвращает указатель на найденный элемент. Если элемент -не найден, то возвращается указатель за последний элемент. +не найден, то возвращается указатель на последний элемент. Указатели соответствуют диапазону $[begin, end)$. 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..ef17e289 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,30 @@ -#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 = nullptr; + + while (begin < end) + { + if (predicate(*begin)){ + last_element = begin; + } + + ++begin; + } + + if (last_element == nullptr){ + 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..1887280e 100644 --- a/02_week/tasks/little_big/little_big.cpp +++ b/02_week/tasks/little_big/little_big.cpp @@ -1,10 +1,38 @@ -#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[sizeof(int)]; + std::memcpy(bytes, &number, sizeof(int)); + + if (inversion) { + std::reverse(bytes, bytes + sizeof(int)); + } + + std::cout << "0x"; + 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[sizeof(double)]; + std::memcpy(bytes, &number, sizeof(double)); + + if (inversion) { + std::reverse(bytes, bytes + sizeof(double)); + } + + std::cout << "0x"; + 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..4940ed99 100644 --- a/02_week/tasks/longest/longest.cpp +++ b/02_week/tasks/longest/longest.cpp @@ -1,6 +1,38 @@ -#include +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; + while (left != right){ + ++left; + } + } + } + + if (length > max_length){ + startOfSubsequence = left; + max_length = length; + } + + count = max_length; + return const_cast(startOfSubsequence); +} \ 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..f6c872e2 100644 --- a/02_week/tasks/pretty_array/pretty_array.cpp +++ b/02_week/tasks/pretty_array/pretty_array.cpp @@ -1,6 +1,35 @@ -#include +#include +void PrintArray(const int* begin, const int* end, const int count = 0) { + if (begin == nullptr || end == nullptr || count < 0) { + std::cout << "[]\n"; + return; + } -void PrintArray(/* write arguments here */) { - throw std::runtime_error{"Not implemented"}; + std::cout << "["; + if (begin < end) { + for (const int* ptr = begin; ptr < end; ++ptr) { + if (count > 0 && static_cast(ptr - begin) % count == 0 && ptr != begin){ + std::cout << "...\n "; + } + + std::cout << *ptr; + if (ptr != end - 1) { + std::cout << ", "; + } + } + } + else if (begin > end) { + for (const int* ptr = begin; ptr > end; --ptr) { + if (count > 0 && static_cast(begin - ptr) % count == 0 && ptr != begin) { + std::cout << "...\n "; + } + + std::cout << *ptr; + if (ptr != end + 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..cf62e3b4 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(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..cd7971f4 100644 --- a/03_week/tasks/easy_compare/easy_compare.cpp +++ b/03_week/tasks/easy_compare/easy_compare.cpp @@ -1,10 +1,72 @@ -#include - +#include struct Date { unsigned year; unsigned month; unsigned day; + + Date(){this->year = 0u; this->month = 0u; this->day = 0u;} + Date(unsigned year, unsigned month, unsigned day) : year(year), month(month), day(day){} + + bool operator==(Date other) const { + if (this->year == other.year && this->month == other.month && this->day == other.day){ + return true; + } + return false; + } + + bool operator!=(Date other) const { + if (!this->operator==(other)){ + return true; + } + return false; + } + + bool operator<(Date other) const { + if (this->year < other.year){ + return true; + } else if (this->year == other.year){ + if (this->month < other.month){ + return true; + } else if (this->month == other.month){ + if (this->day < other.day){ + return true; + } + } + } + + return false; + } + + bool operator>(Date other) const { + if (this->year > other.year){ + return true; + } else if (this->year == other.year){ + if (this->month > other.month){ + return true; + } else if (this->month == other.month){ + if (this->day > other.day){ + return true; + } + } + } + + return false; + } + + bool operator>=(Date other) const { + if (this->operator>(other) || this->operator==(other)){ + return true; + } + return false; + } + + bool operator<=(Date other) const { + if (this->operator<(other) || this->operator==(other)){ + return true; + } + return false; + } }; struct StudentInfo { @@ -13,4 +75,76 @@ 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 { + if (this->mark == other.mark && this->score == other.score){ + return true; + } + return false; + } + + bool operator!=(StudentInfo other) const { + if (!this->operator==(other)){ + return true; + } + return false; + } + + bool operator<(StudentInfo other) const { + if (this->mark > other.mark){ + return true; + } else if (this->mark == other.mark){ + if (this->score < other.score){ + return true; + } else if (this->score == other.score){ + if (this->course > other.course){ + return true; + } else if (this->course == other.course){ + if (this->birth_date < other.birth_date){ + return true; + } + } + } + } + + return false; + } + + bool operator>(StudentInfo other) const { + if (this->mark < other.mark){ + return true; + } else if (this->mark == other.mark){ + if (this->score > other.score){ + return true; + } else if (this->score == other.score){ + if (this->course < other.course){ + return true; + } else if (this->course == other.course){ + if (this->birth_date > other.birth_date){ + return true; + } + } + } + } + + return false; + } + + bool operator>=(StudentInfo other) const { + if (this->operator>(other) || this->operator==(other)){ + return true; + } + return false; + } + + bool operator<=(StudentInfo other) const { + if (this->operator<(other) || this->operator==(other)){ + return true; + } + return false; + } }; \ 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..75f0e34b 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 +#include enum class CheckFlags : uint8_t { NONE = 0, @@ -12,22 +15,86 @@ 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; + } + + std::vector flag_names; + + if ((valid_flags & static_cast(CheckFlags::TIME)) != 0) { + flag_names.push_back("TIME"); + } + if ((valid_flags & static_cast(CheckFlags::DATE)) != 0) { + flag_names.push_back("DATE"); + } + if ((valid_flags & static_cast(CheckFlags::USER)) != 0) { + flag_names.push_back("USER"); + } + if ((valid_flags & static_cast(CheckFlags::CERT)) != 0) { + flag_names.push_back("CERT"); + } + if ((valid_flags & static_cast(CheckFlags::KEYS)) != 0) { + flag_names.push_back("KEYS"); + } + if ((valid_flags & static_cast(CheckFlags::DEST)) != 0) { + flag_names.push_back("DEST"); + } + + for (size_t i = 0; i < flag_names.size(); ++i) { + os << flag_names[i]; + if (i < flag_names.size() - 1) { + os << ", "; + } + } + + 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..7514a09c 100644 --- a/03_week/tasks/unique/unique.cpp +++ b/03_week/tasks/unique/unique.cpp @@ -1,6 +1,17 @@ -#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.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..a0e1eeba 100644 --- a/04_week/tasks/queue/queue.cpp +++ b/04_week/tasks/queue/queue.cpp @@ -1,6 +1,173 @@ #include +#include +#include class Queue { + std::vector input; + std::vector output; + bool eqArrays(const std::vector& a, const std::vector& b) const; + std::vector unionArrays(const std::vector& input, const std::vector& output) const; + +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::vector tmpInput = std::move(input); + std::vector tmpOutput = std::move(output); + input = std::move(other.input); + output = std::move(other.output); + other.input = std::move(tmpInput); + other.output = std::move(tmpOutput); +} + +bool Queue::eqArrays(const std::vector& a, const std::vector& b) const{ + if (a.size() != b.size()){ return false; } + if (a.empty() && b.empty()){ return true; } + + for (size_t i = 0; i < a.size(); ++i) { + if (a[i] != b[i]) { + return false; + } + } + return true; +} + +std::vector Queue::unionArrays(const std::vector& input, const std::vector& output) const { + std::vector unionArray; + unionArray.reserve(input.size() + output.size()); + + for (auto it = output.rbegin(); it != output.rend(); ++it) { + unionArray.push_back(*it); + } + + for (size_t i=0; i < input.size(); ++i){ + unionArray.push_back(input[i]); + } + + return unionArray; +} + +bool Queue::operator==(const Queue& other) const { + return eqArrays(unionArrays(input, output), unionArrays(other.input, other.output)); +} + +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..d8559ecd 100644 --- a/04_week/tasks/ring_buffer/ring_buffer.cpp +++ b/04_week/tasks/ring_buffer/ring_buffer.cpp @@ -1,6 +1,235 @@ #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; + } +} + +void RingBuffer::Push(const int& value){ + if (size == 0){ + end = 0; + buffer[end] = value; + ++size; + } else { + if (end < capacity-1){ + if (size < capacity){ ++size; } + ++end; + buffer[end] = value; + } else if (end == capacity-1 && size != capacity){ + ++size; + end = 0; + buffer[end] = value; + } else if (end == capacity-1 && size == capacity){ + end = 0; + buffer[end] = value; + } + + if (end == begin && begin != capacity-1){ + ++begin; + } else if (end == begin && begin == capacity-1){ + begin = 0; + } + } +} + +bool RingBuffer::TryPush(const int& value){ + if (size == 0){ + end = 0; + buffer[end] = value; + ++size; + } else { + if (end < capacity-1 && end+1 != begin){ + ++size; + ++end; + buffer[end] = value; + } else if (end == capacity-1 && size != capacity){ // && begin != 0 + ++size; + end = 0; + buffer[end] = value; + } else { + return false; + } + } + + return true; +} + +void RingBuffer::Pop(){ + if (size > 0){ + if (begin+1 <= end){ + ++begin; + } else { + begin = 0; + } + --size; + + } + +} + +bool RingBuffer::TryPop(int& value){ + if (size > 0){ + value = buffer[begin]; + + if (begin+1 <= end){ + ++begin; + } else { + begin = 0; + } + --size; + return true; + } + + return false; +} + +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..5f0b109a 100644 --- a/04_week/tasks/stack/stack.cpp +++ b/04_week/tasks/stack/stack.cpp @@ -2,5 +2,78 @@ 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){ + Stack tmp = std::move(*this); + *this = std::move(other); + other = std::move(tmp); +} + +bool Stack::operator==(const Stack& other) const { + if (Size() != other.Size()){ return false; } + for (int i = 0; i < Size(); ++i) { + if (stack[i] != other.stack[i]) { + return false; + } + } + return true; +} + +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