diff --git a/01_week/tasks/addition/addition.cpp b/01_week/tasks/addition/addition.cpp index 92872802..29b7c4e6 100644 --- a/01_week/tasks/addition/addition.cpp +++ b/01_week/tasks/addition/addition.cpp @@ -1,7 +1,8 @@ #include #include - -int64_t Addition(int a, int b) { - throw std::runtime_error{"Not implemented"}; +int64_t Addition(int a, int b) +{ + // throw std::runtime_error{"Not implemented"}; + return static_cast(a) + 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..06087aa1 100644 --- a/01_week/tasks/char_changer/char_changer.cpp +++ b/01_week/tasks/char_changer/char_changer.cpp @@ -1,7 +1,111 @@ #include #include +#include +size_t CharChanger(char array[], size_t size, char delimiter = ' ') +{ + // throw std::runtime_error{"Not implemented"}; + size_t j = 0; + size_t i = 0; -size_t CharChanger(char array[], size_t size, char delimiter = ' ') { - throw std::runtime_error{"Not implemented"}; + while (i < size && array[i] != '\0') + { + if (array[i] == ' ') + { + // Пропускаем все пробелы + size_t spaces = 0; + while (i < size && array[i] == ' ') + { + i++; + spaces++; + } + + // Записываем разделитель если есть пробелы + if (spaces > 0) + { + if (j < size - 1) + { + array[j] = delimiter; + j++; + } + else + { + break; + } + } + } + else + { + // Определяем длину последовательности одинаковых символов + char original = array[i]; + size_t count = 0; + while (i + count < size && array[i + count] == original && array[i + count] != '\0') + { + count++; + } + + // Преобразуем символ + char current = original; + if (std::isdigit(static_cast(original))) + { + current = '*'; + } + else if (std::islower(static_cast(original))) + { + current = std::toupper(static_cast(original)); + } + else if (!std::isupper(static_cast(original))) + { + current = '_'; + } + + // Записываем результат с учетом правила повторений + if (count == 1) + { + if (j < size - 1) + { + array[j] = current; + j++; + } + else + { + break; + } + } + else + { + if (j + 1 < size - 1) + { + array[j] = current; + if (count >= 10) + { + array[j + 1] = '0'; + } + else + { + array[j + 1] = '0' + count; + } + j += 2; + } + else + { + break; + } + } + + i += count; + } + } + + // Завершаем строку + if (j < size) + { + array[j] = '\0'; + } + else if (size > 0) + { + array[size - 1] = '\0'; + } + + return j; } diff --git a/01_week/tasks/check_flags/check_flags.cpp b/01_week/tasks/check_flags/check_flags.cpp index 75e7c652..e1aa25a0 100644 --- a/01_week/tasks/check_flags/check_flags.cpp +++ b/01_week/tasks/check_flags/check_flags.cpp @@ -1,8 +1,10 @@ #include #include +#include +#include - -enum class CheckFlags : uint8_t { +enum class CheckFlags : uint8_t +{ NONE = 0, TIME = (1 << 0), DATE = (1 << 1), @@ -13,6 +15,54 @@ enum class CheckFlags : uint8_t { ALL = TIME | DATE | USER | CERT | KEYS | DEST }; -void PrintCheckFlags(CheckFlags flags) { - throw std::runtime_error{"Not implemented"}; +void PrintCheckFlags(CheckFlags flags) +{ + // throw std::runtime_error{"Not implemented"}; + uint8_t value = static_cast(flags); + + // Проверка на выход за диапазон + if (value > static_cast(CheckFlags::ALL)) + { + return; + } + + std::vector active_flags; + + // Проверяем каждый флаг в правильном порядке + if (value & static_cast(CheckFlags::TIME)) + { + active_flags.push_back("TIME"); + } + if (value & static_cast(CheckFlags::DATE)) + { + active_flags.push_back("DATE"); + } + if (value & static_cast(CheckFlags::USER)) + { + active_flags.push_back("USER"); + } + if (value & static_cast(CheckFlags::CERT)) + { + active_flags.push_back("CERT"); + } + if (value & static_cast(CheckFlags::KEYS)) + { + active_flags.push_back("KEYS"); + } + if (value & static_cast(CheckFlags::DEST)) + { + active_flags.push_back("DEST"); + } + + // Формируем вывод + std::cout << "["; + for (size_t i = 0; i < active_flags.size(); ++i) + { + if (i > 0) + { + std::cout << ","; + } + std::cout << active_flags[i]; + } + std::cout << "]"; } diff --git a/01_week/tasks/length_lit/length_lit.cpp b/01_week/tasks/length_lit/length_lit.cpp index e69de29b..926ebdf2 100644 --- a/01_week/tasks/length_lit/length_lit.cpp +++ b/01_week/tasks/length_lit/length_lit.cpp @@ -0,0 +1,136 @@ +#include + +// Константы преобразования +constexpr double FEET_TO_METERS = 0.3048; +constexpr double INCHES_TO_METERS = 0.0254; +constexpr double METERS_TO_FEET = 1.0 / FEET_TO_METERS; +constexpr double METERS_TO_INCHES = 1.0 / INCHES_TO_METERS; +constexpr double FEET_TO_INCHES = 12.0; +constexpr double INCHES_TO_FEET = 1.0 / FEET_TO_INCHES; +constexpr double METERS_TO_CM = 100.0; +constexpr double CM_TO_METERS = 0.01; + +// Футы в другие единицы +constexpr double operator"" _ft_to_m(long double feet) +{ + return feet * FEET_TO_METERS; +} + +constexpr double operator"" _ft_to_cm(long double feet) +{ + return feet * FEET_TO_METERS * METERS_TO_CM; +} + +constexpr double operator"" _ft_to_in(long double feet) +{ + return feet * FEET_TO_INCHES; +} + +// Дюймы в другие единицы +constexpr double operator"" _in_to_m(long double inches) +{ + return inches * INCHES_TO_METERS; +} + +constexpr double operator"" _in_to_cm(long double inches) +{ + return inches * INCHES_TO_METERS * METERS_TO_CM; +} + +constexpr double operator"" _in_to_ft(long double inches) +{ + return inches * INCHES_TO_FEET; +} + +// Метры в другие единицы +constexpr double operator"" _m_to_ft(long double meters) +{ + return meters * METERS_TO_FEET; +} + +constexpr double operator"" _m_to_in(long double meters) +{ + return meters * METERS_TO_INCHES; +} + +constexpr double operator"" _m_to_cm(long double meters) +{ + return meters * METERS_TO_CM; +} + +// Сантиметры в другие единицы +constexpr double operator"" _cm_to_m(long double centimeters) +{ + return centimeters * CM_TO_METERS; +} + +constexpr double operator"" _cm_to_ft(long double centimeters) +{ + return centimeters * CM_TO_METERS * METERS_TO_FEET; +} + +constexpr double operator"" _cm_to_in(long double centimeters) +{ + return centimeters * CM_TO_METERS * METERS_TO_INCHES; +} + +// Перегрузки для целочисленных литералов +constexpr double operator"" _ft_to_m(unsigned long long feet) +{ + return static_cast(feet) * FEET_TO_METERS; +} + +constexpr double operator"" _ft_to_cm(unsigned long long feet) +{ + return static_cast(feet) * FEET_TO_METERS * METERS_TO_CM; +} + +constexpr double operator"" _ft_to_in(unsigned long long feet) +{ + return static_cast(feet) * FEET_TO_INCHES; +} + +constexpr double operator"" _in_to_m(unsigned long long inches) +{ + return static_cast(inches) * INCHES_TO_METERS; +} + +constexpr double operator"" _in_to_cm(unsigned long long inches) +{ + return static_cast(inches) * INCHES_TO_METERS * METERS_TO_CM; +} + +constexpr double operator"" _in_to_ft(unsigned long long inches) +{ + return static_cast(inches) * INCHES_TO_FEET; +} + +constexpr double operator"" _m_to_ft(unsigned long long meters) +{ + return static_cast(meters) * METERS_TO_FEET; +} + +constexpr double operator"" _m_to_in(unsigned long long meters) +{ + return static_cast(meters) * METERS_TO_INCHES; +} + +constexpr double operator"" _m_to_cm(unsigned long long meters) +{ + return static_cast(meters) * METERS_TO_CM; +} + +constexpr double operator"" _cm_to_m(unsigned long long centimeters) +{ + return static_cast(centimeters) * CM_TO_METERS; +} + +constexpr double operator"" _cm_to_ft(unsigned long long centimeters) +{ + return static_cast(centimeters) * CM_TO_METERS * METERS_TO_FEET; +} + +constexpr double operator"" _cm_to_in(unsigned long long centimeters) +{ + return static_cast(centimeters) * CM_TO_METERS * METERS_TO_INCHES; +} \ 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..568e1d82 100644 --- a/01_week/tasks/print_bits/print_bits.cpp +++ b/01_week/tasks/print_bits/print_bits.cpp @@ -1,7 +1,51 @@ #include #include +#include +void PrintBits(long long value, size_t bytes) +{ + // throw std::runtime_error{"Not implemented"}; + // Проверяем допустимость размера + if (bytes == 0 || bytes > 8) + { + return; + } -void PrintBits(long long value, size_t bytes) { - throw std::runtime_error{"Not implemented"}; + // Вычисляем общее количество битов + size_t total_bits = bytes * 8; + + // Создаем маску для извлечения нужного количества байтов + unsigned long long mask = 0; + if (bytes == 8) + { + mask = ~0ULL; // Все биты установлены в 1 + } + else + { + mask = (1ULL << total_bits) - 1; + } + + // Приводим значение к беззнаковому типу и применяем маску + unsigned long long unsigned_value = static_cast(value); + unsigned_value &= mask; + + // Выводим префикс + std::cout << "0b"; + + // Выводим биты группами по 4 + for (int i = static_cast(total_bits) - 1; i >= 0; i--) + { + // Получаем текущий бит + unsigned long long bit = (unsigned_value >> i) & 1; + std::cout << (bit ? '1' : '0'); + + // Добавляем апостроф после каждой группы из 4 битов (кроме последней) + if (i > 0 && i % 4 == 0) + { + std::cout << "'"; + } + } + + // Завершаем вывод переводом строки + std::cout << "\n"; } diff --git a/01_week/tasks/quadratic/quadratic.cpp b/01_week/tasks/quadratic/quadratic.cpp index abf7d632..0e41f2c7 100644 --- a/01_week/tasks/quadratic/quadratic.cpp +++ b/01_week/tasks/quadratic/quadratic.cpp @@ -1,6 +1,78 @@ #include +#include +#include +#include +#include +void PrintRoot(double root) +{ + if (std::abs(root) < 1e-10) + { // Проверяем, близок ли корень к нулю + std::cout << "0"; + } + else + { + std::cout << root; + } +} -void SolveQuadratic(int a, int b, int c) { - throw std::runtime_error{"Not implemented"}; -} \ No newline at end of file +void SolveQuadratic(int a, int b, int c) +{ + // throw std::runtime_error{"Not implemented"}; + std::cout << std::setprecision(6); + + // Случай: a = 0 (линейное уравнение) + if (a == 0) + { + // Случай: b = 0 + if (b == 0) + { + if (c == 0) + { + std::cout << "infinite solutions"; + } + else + { + std::cout << "no solutions"; + } + } + else + { + // Линейное уравнение: bx + c = 0 + double root = -static_cast(c) / b; + PrintRoot(root); + } + return; + } + + // Квадратное уравнение + double discriminant = static_cast(b) * b - 4.0 * a * c; + + if (discriminant < 0) + { + std::cout << "no solutions"; + } + else if (discriminant == 0) + { + // Один корень + double root = -static_cast(b) / (2.0 * a); + PrintRoot(root); + } + else + { + // Два корня + double sqrt_d = std::sqrt(discriminant); + double root1 = (-b - sqrt_d) / (2.0 * a); + double root2 = (-b + sqrt_d) / (2.0 * a); + + // Упорядочиваем корни по возрастанию + if (root1 > root2) + { + std::swap(root1, root2); + } + + PrintRoot(root1); + std::cout << " "; + PrintRoot(root2); + } +} diff --git a/01_week/tasks/rms/rms.cpp b/01_week/tasks/rms/rms.cpp index 6882f0a9..5271e5c3 100644 --- a/01_week/tasks/rms/rms.cpp +++ b/01_week/tasks/rms/rms.cpp @@ -1,7 +1,23 @@ -#include +#include #include +double CalculateRMS(double values[], size_t size) +{ + // throw std::runtime_error{"Not implemented"}; + // Обработка особых случаев: пустой массив или nullptr + if (values == nullptr || size == 0) + { + return 0.0; + } -double CalculateRMS(double values[], size_t size) { - throw std::runtime_error{"Not implemented"}; -} \ No newline at end of file + // Вычисление суммы квадратов элементов + double sum_of_squares = 0.0; + for (size_t i = 0; i < size; ++i) + { + sum_of_squares += values[i] * values[i]; + } + + // Вычисление среднего значения квадратов и извлечение корня + double mean_of_squares = sum_of_squares / size; + return std::sqrt(mean_of_squares); +} diff --git a/02_week/tasks/func_array/func_array.cpp b/02_week/tasks/func_array/func_array.cpp index b327e68d..aa6a8311 100644 --- a/02_week/tasks/func_array/func_array.cpp +++ b/02_week/tasks/func_array/func_array.cpp @@ -1,6 +1,21 @@ #include +double ApplyOperations(double a, double b, double (**operations)(double, double), size_t size) +{ + // throw std::runtime_error{"Not implemented"}; + if (operations == nullptr || size == 0) + { + return 0.0; + } -double ApplyOperations(double a, double b /* other arguments */) { - throw std::runtime_error{"Not implemented"}; + double sum = 0.0; + for (size_t i = 0; i < size; ++i) + { + if (operations[i] != nullptr) + { + sum += operations[i](a, b); + } + } + + return sum; } \ 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..b547ec6f 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,44 @@ #include +const int *FindLastElement(const int *begin, const int *end, bool (*predicate)(int)) +{ + // throw std::runtime_error{"Not implemented"}; + // Проверка на некорректные указатели + if (begin == nullptr || end == nullptr) + { + return end; // Если end тоже nullptr, вернется nullptr + } -/* return_type */ FindLastElement(/* ptr_type */ begin, /* ptr_type */ end, /* func_type */ predicate) { - throw std::runtime_error{"Not implemented"}; + // Проверка на некорректный диапазон (begin > end) + if (begin > end) + { + return end; + } + + // Если диапазон пустой + if (begin == end) + { + return end; + } + + // Ищем последний элемент, удовлетворяющий условию + const int *current = end - 1; // Начинаем с последнего элемента + + while (current >= begin) + { + if (predicate(*current)) + { + return current; + } + + // Проверяем, не вышли ли за начало массива + if (current == begin) + { + break; + } + current--; + } + + // Если элемент не найден, возвращаем end + return end; } \ 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..a2f443fa 100644 --- a/02_week/tasks/little_big/little_big.cpp +++ b/02_week/tasks/little_big/little_big.cpp @@ -1,10 +1,79 @@ +#include #include +#include +void PrintMemory(int value, bool reverse) +{ + // throw std::runtime_error{"Not implemented"}; + unsigned char bytes[sizeof(int)]; + std::memcpy(bytes, &value, sizeof(int)); -void PrintMemory(int /* write arguments here */) { - throw std::runtime_error{"Not implemented"}; + std::cout << "0x"; + if (reverse) + { + // Big-endian + for (int i = sizeof(int) - 1; i >= 0; --i) + { + // Ручной вывод hex + unsigned char high = (bytes[i] >> 4) & 0x0F; + unsigned char low = bytes[i] & 0x0F; + std::cout.put(high < 10 ? '0' + high : 'A' + (high - 10)); + std::cout.put(low < 10 ? '0' + low : 'A' + (low - 10)); + } + } + else + { + // Little-endian + for (size_t i = 0; i < sizeof(int); ++i) + { + unsigned char high = (bytes[i] >> 4) & 0x0F; + unsigned char low = bytes[i] & 0x0F; + std::cout.put(high < 10 ? '0' + high : 'A' + (high - 10)); + std::cout.put(low < 10 ? '0' + low : 'A' + (low - 10)); + } + } + std::cout.put('\n'); } -void PrintMemory(double /* write arguments here */) { - throw std::runtime_error{"Not implemented"}; +void PrintMemory(double value, bool reverse) +{ + // throw std::runtime_error{"Not implemented"}; + unsigned char bytes[sizeof(double)]; + std::memcpy(bytes, &value, sizeof(double)); + + std::cout << "0x"; + if (reverse) + { + // Big-endian + for (int i = sizeof(double) - 1; i >= 0; --i) + { + unsigned char high = (bytes[i] >> 4) & 0x0F; + unsigned char low = bytes[i] & 0x0F; + std::cout.put(high < 10 ? '0' + high : 'A' + (high - 10)); + std::cout.put(low < 10 ? '0' + low : 'A' + (low - 10)); + } + } + else + { + // Little-endian + for (size_t i = 0; i < sizeof(double); ++i) + { + unsigned char high = (bytes[i] >> 4) & 0x0F; + unsigned char low = bytes[i] & 0x0F; + std::cout.put(high < 10 ? '0' + high : 'A' + (high - 10)); + std::cout.put(low < 10 ? '0' + low : 'A' + (low - 10)); + } + } + std::cout.put('\n'); +} + +// Перегрузки с одним параметром +void PrintMemory(int value) +{ + PrintMemory(value, false); +} + +void PrintMemory(double value) +{ + PrintMemory(value, false); } \ No newline at end of file diff --git a/02_week/tasks/little_big/test.cpp b/02_week/tasks/little_big/test.cpp index bd40bc24..008a54b0 100644 --- a/02_week/tasks/little_big/test.cpp +++ b/02_week/tasks/little_big/test.cpp @@ -98,7 +98,7 @@ TEST_F(PrintMemoryTest, DoubleZero) { TEST_F(PrintMemoryTest, DoublePositive) { PrintMemory(36.6); std::string output = GetOutput(); - EXPECT_EQ(output, "0xCDCCCCCCCC4C4240\n"); + EXPECT_EQ(output, "0xCDCCCCCCCC4C424\n"); } TEST_F(PrintMemoryTest, DoubleNegative) { diff --git a/02_week/tasks/longest/longest.cpp b/02_week/tasks/longest/longest.cpp index 04b3c354..b4a1b74b 100644 --- a/02_week/tasks/longest/longest.cpp +++ b/02_week/tasks/longest/longest.cpp @@ -1,6 +1,58 @@ #include +const char *FindLongestSubsequence(const char *begin, const char *end, size_t &count) +{ + // throw std::runtime_error{"Not implemented"}; + // Проверка на некорректные указатели или диапазон + if (begin == nullptr || end == nullptr || begin > end) + { + count = 0; + return nullptr; + } -/* return_type */ FindLongestSubsequence(/* ptr_type */ begin, /* ptr_type */ end, /* type */ count) { - throw std::runtime_error{"Not implemented"}; + // Проверка на пустой диапазон + if (begin == end) + { + count = 0; + return nullptr; + } + + const char *current_start = begin; + const char *longest_start = begin; + size_t current_length = 1; + size_t max_length = 1; + + const char *current = begin + 1; + + while (current < end) + { + // Если текущий символ совпадает с символом в current_start + if (*current == *(current_start)) + { + current_length++; + } + else + { + // Если текущая подпоследовательность длиннее максимальной + if (current_length > max_length) + { + max_length = current_length; + longest_start = current_start; + } + // Начинаем новую подпоследовательность + current_start = current; + current_length = 1; + } + current++; + } + + // Проверяем последнюю подпоследовательность + if (current_length > max_length) + { + max_length = current_length; + longest_start = current_start; + } + + count = max_length; + return longest_start; } diff --git a/02_week/tasks/pretty_array/pretty_array.cpp b/02_week/tasks/pretty_array/pretty_array.cpp index 48eab341..31283bd7 100644 --- a/02_week/tasks/pretty_array/pretty_array.cpp +++ b/02_week/tasks/pretty_array/pretty_array.cpp @@ -1,6 +1,98 @@ #include +#include +void PrintArray(const int *begin, const int *end, size_t limit = 0) +{ + // throw std::runtime_error{"Not implemented"}; + // Проверка на nullptr или пустой массив + if (begin == nullptr || end == nullptr) + { + std::cout << "[]\n"; + return; + } -void PrintArray(/* write arguments here */) { - throw std::runtime_error{"Not implemented"}; + // Вычисляем количество элементов + size_t count = 0; + bool reverse = false; + const int *current = nullptr; + + if (end > begin) + { + // Обычный порядок + count = end - begin; + current = begin; + reverse = false; + } + else if (end < begin) + { + // Обратный порядок + count = begin - end; + current = begin; + reverse = true; + } + else + { + // Пустой массив + std::cout << "[]\n"; + return; + } + + std::cout << '['; + + if (limit == 0 || limit >= count) + { + // Вывод без ограничения + for (size_t i = 0; i < count; ++i) + { + if (i > 0) + std::cout << ", "; + std::cout << *current; + + if (reverse) + { + --current; + } + else + { + ++current; + } + } + std::cout << "]\n"; + return; + } + + // Вывод с ограничением + size_t elements_printed = 0; + size_t elements_in_current_line = 0; + + while (elements_printed < count) + { + if (elements_in_current_line > 0) + { + std::cout << ", "; + } + + std::cout << *current; + ++elements_printed; + ++elements_in_current_line; + + // Переход к следующему элементу + if (reverse) + { + --current; + } + else + { + ++current; + } + + // Проверяем, нужно ли переносить строку + if (elements_in_current_line == limit && elements_printed < count) + { + std::cout << ", ...\n "; + elements_in_current_line = 0; + } + } + + std::cout << "]\n"; } \ No newline at end of file diff --git a/02_week/tasks/pretty_array/test.cpp b/02_week/tasks/pretty_array/test.cpp index 3224871a..93cfe013 100644 --- a/02_week/tasks/pretty_array/test.cpp +++ b/02_week/tasks/pretty_array/test.cpp @@ -27,6 +27,16 @@ class PrintArrayTest : public ::testing::Test { std::streambuf* origin_cout; }; +TEST(FunctionSignatureTest, IntSignature) { + static_assert(std::is_same_v(&PrintMemory)), void (*)(int, bool)>, + "function must have signature: void PrintMemory(int, bool)"); +} + +TEST(FunctionSignatureTest, DoubleSignature) { + static_assert(std::is_same_v(&PrintMemory)), void (*)(double, bool)>, + "function must have signature: void PrintMemory(double, bool)"); +} + TEST_F(PrintArrayTest, EmptyArray) { int arr[] = {1}; PrintArray(arr, arr); diff --git a/02_week/tasks/swap_ptr/swap_ptr.cpp b/02_week/tasks/swap_ptr/swap_ptr.cpp index 93db625d..f0e275bc 100644 --- a/02_week/tasks/swap_ptr/swap_ptr.cpp +++ b/02_week/tasks/swap_ptr/swap_ptr.cpp @@ -1,6 +1,23 @@ #include +void SwapPtr(int *&ptr1, int *&ptr2) +{ + // throw std::runtime_error{"Not implemented"}; + int *temp = ptr1; + ptr1 = ptr2; + ptr2 = temp; +} -void SwapPtr(/* write arguments here */) { - throw std::runtime_error{"Not implemented"}; +void SwapPtr(const int *&ptr1, const int *&ptr2) +{ + const int *temp = ptr1; + ptr1 = ptr2; + ptr2 = temp; +} + +void SwapPtr(int **&ptr1, int **&ptr2) +{ + int **temp = ptr1; + ptr1 = ptr2; + ptr2 = temp; } \ No newline at end of file