diff --git a/01_week/tasks/addition/addition.cpp b/01_week/tasks/addition/addition.cpp index 92872802..05ffd7d1 100644 --- a/01_week/tasks/addition/addition.cpp +++ b/01_week/tasks/addition/addition.cpp @@ -3,5 +3,5 @@ int64_t Addition(int a, int b) { - 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..f3420f0e 100644 --- a/01_week/tasks/char_changer/char_changer.cpp +++ b/01_week/tasks/char_changer/char_changer.cpp @@ -3,5 +3,91 @@ size_t CharChanger(char array[], size_t size, char delimiter = ' ') { - throw std::runtime_error{"Not implemented"}; -} + if (array == nullptr || size == 0) { + return 0; + } + + size_t read = 0; // позиция чтения + size_t write = 0; // позиция записи + + while (read < size && array[read] != '\0') { + char c = array[read]; + char new_char; + + // Преобразуем символ по правилам + if (c >= '0' && c <= '9') { + new_char = '*'; + } else if (c >= 'a' && c <= 'z') { + new_char = c - 'a' + 'A'; // строчная -> прописная + } else if (c >= 'A' && c <= 'Z') { + new_char = c; + } else if (c == ' ') { + new_char = delimiter; + } else { + new_char = '_'; + } + + // Считаем количество одинаковых символов + size_t count = 1; + size_t next = read + 1; + while (next < size && array[next] != '\0') { + char next_c = array[next]; + char next_new_char; + + if (next_c >= '0' && next_c <= '9') { + next_new_char = '*'; + } else if (next_c >= 'a' && next_c <= 'z') { + next_new_char = next_c - 'a' + 'A'; + } else if (next_c >= 'A' && next_c <= 'Z') { + next_new_char = next_c; + } else if (next_c == ' ') { + next_new_char = delimiter; + } else { + next_new_char = '_'; + } + + if (next_new_char == new_char) { + count++; + next++; + } else { + break; + } + } + + // Записываем результат + if (new_char == delimiter) { + // Для разделителя пишем только один символ + if (write < size - 1) { + array[write++] = new_char; + } + } else if (count >= 10) { + // 10+ повторений: символ + '0' + if (write < size - 2) { + array[write++] = new_char; + array[write++] = '0'; + } + } else if (count > 1) { + // 2-9 повторений: символ + цифра + if (write < size - 2) { + array[write++] = new_char; + array[write++] = '0' + count; + } + } else { + // 1 повторение: только символ + if (write < size - 1) { + array[write++] = new_char; + } + } + + read = next; // переходим к следующей группе символов + } + + // Завершаем строку + if (write < size) { + array[write] = '\0'; + } else if (size > 0) { + array[size - 1] = '\0'; + } + + return write + 1; // позиция после '\0' +} \ 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..69cd8bc2 100644 --- a/01_week/tasks/check_flags/check_flags.cpp +++ b/01_week/tasks/check_flags/check_flags.cpp @@ -14,5 +14,55 @@ enum class CheckFlags : uint8_t { }; void PrintCheckFlags(CheckFlags flags) { - throw std::runtime_error{"Not implemented"}; + uint8_t value = static_cast(flags); + + // Проверка на выход за диапазон (максимальное значение ALL) + uint8_t max_value = 63; // TIME | DATE | USER | CERT | KEYS | DEST + if (value > max_value) { + return; // оставляем вывод пустым + } + + // Начинаем вывод + printf("["); + + bool first = true; + + // Проверяем каждый флаг + if ((value & static_cast(CheckFlags::TIME)) != 0) { + if (!first) printf(","); + printf("TIME"); + first = false; + } + + if ((value & static_cast(CheckFlags::DATE)) != 0) { + if (!first) printf(","); + printf("DATE"); + first = false; + } + + if ((value & static_cast(CheckFlags::USER)) != 0) { + if (!first) printf(","); + printf("USER"); + first = false; + } + + if ((value & static_cast(CheckFlags::CERT)) != 0) { + if (!first) printf(","); + printf("CERT"); + first = false; + } + + if ((value & static_cast(CheckFlags::KEYS)) != 0) { + if (!first) printf(","); + printf("KEYS"); + first = false; + } + + if ((value & static_cast(CheckFlags::DEST)) != 0) { + if (!first) printf(","); + printf("DEST"); + first = false; + } + + printf("]"); } diff --git a/01_week/tasks/length_lit/length_lit.cpp b/01_week/tasks/length_lit/length_lit.cpp index e69de29b..b1e53a74 100644 --- a/01_week/tasks/length_lit/length_lit.cpp +++ b/01_week/tasks/length_lit/length_lit.cpp @@ -0,0 +1,51 @@ +// Футы в другие единицы +constexpr double operator"" _ft_to_in(long double feet) { + return static_cast(feet * 12.0L); +} + +constexpr double operator"" _ft_to_cm(long double feet) { + return static_cast(feet * 30.48L); +} + +constexpr double operator"" _ft_to_m(long double feet) { + return static_cast(feet * 0.3048L); +} + +// Дюймы в другие единицы +constexpr double operator"" _in_to_ft(long double inches) { + return static_cast(inches / 12.0L); +} + +constexpr double operator"" _in_to_cm(long double inches) { + return static_cast(inches * 2.54L); +} + +constexpr double operator"" _in_to_m(long double inches) { + return static_cast(inches * 0.0254L); +} + +// Сантиметры в другие единицы +constexpr double operator"" _cm_to_ft(long double cm) { + return static_cast(cm / 30.48L); +} + +constexpr double operator"" _cm_to_in(long double cm) { + return static_cast(cm / 2.54L); +} + +constexpr double operator"" _cm_to_m(long double cm) { + return static_cast(cm / 100.0L); +} + +// Метры в другие единицы +constexpr double operator"" _m_to_ft(long double meters) { + return static_cast(meters / 0.3048L); +} + +constexpr double operator"" _m_to_in(long double meters) { + return static_cast(meters / 0.0254L); +} + +constexpr double operator"" _m_to_cm(long double meters) { + return static_cast(meters * 100.0L); +} \ 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..921c6107 100644 --- a/01_week/tasks/print_bits/print_bits.cpp +++ b/01_week/tasks/print_bits/print_bits.cpp @@ -3,5 +3,29 @@ void PrintBits(long long value, size_t bytes) { - throw std::runtime_error{"Not implemented"}; + // Проверка допустимого диапазона размера + if (bytes == 0 || bytes > 8) { + return; + } + + // Выводим префикс "0b" + printf("0b"); + + // Проходим по всем битам от старшего к младшему + for (int i = static_cast(bytes * 8) - 1; i >= 0; i--) { + // Получаем i-тый бит + if (value & (1LL << i)) { + printf("1"); + } else { + printf("0"); + } + + // Добавляем апостроф каждые 8 бит (кроме последней группы) + if (i > 0 && i % 8 == 0) { + printf("'"); + } + } + + // Перевод строки в конце + printf("\n"); } diff --git a/01_week/tasks/quadratic/quadratic.cpp b/01_week/tasks/quadratic/quadratic.cpp index abf7d632..cc7a25c3 100644 --- a/01_week/tasks/quadratic/quadratic.cpp +++ b/01_week/tasks/quadratic/quadratic.cpp @@ -1,6 +1,50 @@ #include - +#include +#include void SolveQuadratic(int a, int b, int c) { - throw std::runtime_error{"Not implemented"}; + std::cout << std::setprecision(6); + + // Случай бесконечных решений: 0*x² + 0*x + 0 = 0 + if (a == 0 && b == 0 && c == 0) { + std::cout << "infinite solutions" << std::endl; + return; + } + + // Линейное уравнение: 0*x² + b*x + c = 0 + if (a == 0) { + if (b == 0) { + // 0*x + c = 0, где c ≠ 0 - нет решений + std::cout << "no solutions" << std::endl; + } else { + // b*x + c = 0 → x = -c/b + double x = -static_cast(c) / b; + std::cout << x << std::endl; + } + return; + } + + // Квадратное уравнение: a*x² + b*x + c = 0, где a ≠ 0 + double discriminant = static_cast(b) * b - 4.0 * a * c; + + if (discriminant < 0) { + // Отрицательный дискриминант - нет действительных корней + std::cout << "no solutions" << std::endl; + } else if (discriminant == 0) { + // Нулевой дискриминант - один корень + double x = -static_cast(b) / (2.0 * a); + std::cout << x << std::endl; + } else { + // Положительный дискриминант - два корня + double sqrt_d = std::sqrt(discriminant); + double x1 = (-b - sqrt_d) / (2.0 * a); + double x2 = (-b + sqrt_d) / (2.0 * a); + + // Убеждаемся, что x1 < x2 + if (x1 > x2) { + std::swap(x1, x2); + } + + std::cout << x1 << " " << x2 << std::endl; + } } \ No newline at end of file diff --git a/01_week/tasks/rms/rms.cpp b/01_week/tasks/rms/rms.cpp index 6882f0a9..9d375c5a 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"}; + // Обработка пустого массива + if (size == 0) { + return 0.0; + } + + // Сумма квадратов элементов + 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); } \ 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..f58bae1d 100644 --- a/02_week/tasks/func_array/func_array.cpp +++ b/02_week/tasks/func_array/func_array.cpp @@ -1,6 +1,25 @@ #include +// Тип для указателя на функцию операции +using FuncType = double(*)(double, double); -double ApplyOperations(double a, double b /* other arguments */) { - throw std::runtime_error{"Not implemented"}; +double ApplyOperations(double a, double b, FuncType operations[], size_t size) { + // В случае пустого массива операций возвращаем 0.0 + if (size == 0) { + return 0.0; + } + + double sum = 0.0; + + // Чистый цикл без использования STL алгоритмов + for (size_t i = 0; i < size; ++i) { + // Проверяем, что указатель на функцию не равен nullptr + if (operations[i] != nullptr) { + // Выполняем операцию и добавляем результат к сумме + sum += operations[i](a, b); + } + // Если operations[i] == nullptr, просто пропускаем (добавляем 0 к сумме) + } + + 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..cf89a98c 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,29 @@ #include -/* return_type */ FindLastElement(/* ptr_type */ begin, /* ptr_type */ end, /* func_type */ predicate) { - throw std::runtime_error{"Not implemented"}; +// Тип для указателя на функцию-предикат +using Predicate = bool(*)(int); + +const int* FindLastElement(const int* begin, const int* end, Predicate predicate) { + // Проверка на некорректные указатели + if (begin == nullptr || end == nullptr) { + return end; + } + + // Проверка на некорректный диапазон (begin > end) + if (begin > end) { + return end; + } + + // Указатель для последнего найденного элемента + const int* last_found = end; // Изначально указывает за последний элемент + + // Проходим по массиву с начала до конца + for (const int* current = begin; current < end; ++current) { + if (predicate(*current)) { + last_found = current; // Обновляем указатель на последний найденный элемент + } + } + + return last_found; } \ 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..23dd67ed 100644 --- a/02_week/tasks/little_big/little_big.cpp +++ b/02_week/tasks/little_big/little_big.cpp @@ -1,10 +1,52 @@ +#include #include +#include +#include - -void PrintMemory(int /* write arguments here */) { - throw std::runtime_error{"Not implemented"}; +void PrintMemory(int value, bool reverseBytes = false) { + unsigned int temp; + std::memcpy(&temp, &value, sizeof(value)); + + if (!reverseBytes) { + // Little-endian порядок (по умолчанию) + std::cout << "0x"; + for (int i = 0; i < static_cast(sizeof(temp)); i++) { + unsigned char byte = (temp >> (i * 8)) & 0xFF; + std::cout << std::hex << std::setw(2) << std::setfill('0') + << static_cast(byte); + } + } else { + // Big-endian порядок (инвертированный) + std::cout << "0x"; + for (int i = static_cast(sizeof(temp)) - 1; i >= 0; i--) { + unsigned char byte = (temp >> (i * 8)) & 0xFF; + std::cout << std::hex << std::setw(2) << std::setfill('0') + << static_cast(byte); + } + } + std::cout << std::dec << "\n"; } -void PrintMemory(double /* write arguments here */) { - throw std::runtime_error{"Not implemented"}; +void PrintMemory(double value, bool reverseBytes = false) { + unsigned long long temp; + std::memcpy(&temp, &value, sizeof(value)); + + if (!reverseBytes) { + // Little-endian порядок (по умолчанию) + std::cout << "0x"; + for (int i = 0; i < static_cast(sizeof(temp)); i++) { + unsigned char byte = (temp >> (i * 8)) & 0xFF; + std::cout << std::hex << std::setw(2) << std::setfill('0') + << static_cast(byte); + } + } else { + // Big-endian порядок (инвертированный) + std::cout << "0x"; + for (int i = static_cast(sizeof(temp)) - 1; i >= 0; i--) { + unsigned char byte = (temp >> (i * 8)) & 0xFF; + std::cout << std::hex << std::setw(2) << std::setfill('0') + << static_cast(byte); + } + } + std::cout << std::dec << "\n"; } \ No newline at end of file diff --git a/02_week/tasks/longest/longest.cpp b/02_week/tasks/longest/longest.cpp index 04b3c354..0e385418 100644 --- a/02_week/tasks/longest/longest.cpp +++ b/02_week/tasks/longest/longest.cpp @@ -1,6 +1,57 @@ #include +//include - -/* return_type */ FindLongestSubsequence(/* ptr_type */ begin, /* ptr_type */ end, /* type */ count) { - throw std::runtime_error{"Not implemented"}; +const char* FindLongestSubsequence(const char* begin, const char* end, std::size_t& count) { + // Проверка на некорректные указатели + if (!begin || !end || begin > end) { + count = 0; + return nullptr; + } + + // Проверка на пустой диапазон + if (begin == end) { + count = 0; + return nullptr; + } + + const char* longest_start = begin; + const char* current_start = begin; + std::size_t longest_length = 1; + std::size_t current_length = 1; + + // Проходим по массиву, начиная со второго элемента + const char* current = begin + 1; + while (current < end) { + if (*current == *current_start) { + // Текущий символ совпадает с началом текущей подпоследовательности + current_length++; + } else { + // Текущий символ отличается, начинаем новую подпоследовательность + if (current_length > longest_length) { + longest_length = current_length; + longest_start = current_start; + } + current_start = current; + current_length = 1; + } + current++; + } + + // Проверяем последнюю подпоследовательность + if (current_length > longest_length) { + longest_length = current_length; + longest_start = current_start; + } + + count = longest_length; + return longest_start; } + +char* FindLongestSubsequence(char* begin, char* end, std::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..c5643e66 100644 --- a/02_week/tasks/pretty_array/pretty_array.cpp +++ b/02_week/tasks/pretty_array/pretty_array.cpp @@ -1,6 +1,80 @@ +#include #include - -void PrintArray(/* write arguments here */) { - throw std::runtime_error{"Not implemented"}; +void PrintArray(const int* begin, const int* end, size_t limit = 0) { + // Если указатели равны nullptr, выводим пустой массив + if (begin == nullptr && end == nullptr) { + std::cout << "[]\n"; + return; + } + + // Если диапазон пустой + if (begin == end) { + std::cout << "[]\n"; + return; + } + + bool reverse = false; + const int* current = begin; + const int* last = end; + + // Определяем направление обхода + if (end < begin) { + reverse = true; + // Для обратного порядка: begin должен быть "после" end в массиве + // Меняем местами указатели для упрощения логики + current = end + 1; // end указывает "за конец" в обратном порядке + last = begin + 1; // begin указывает "на начало" в обратном порядке + } + + std::cout << "["; + + size_t elements_in_current_line = 0; + size_t total_elements = 0; + + // Подсчитываем общее количество элементов + if (!reverse) { + total_elements = end - begin; + } else { + total_elements = begin - end; + } + + // Выводим элементы + while (true) { + // Выводим текущий элемент + if (!reverse) { + std::cout << *current; + } else { + std::cout << *(last - 1); + } + + elements_in_current_line++; + total_elements--; + + // Проверяем, нужно ли переходить на новую строку + if (limit > 0 && elements_in_current_line >= limit && total_elements > 0) { + std::cout << ", ...\n "; + elements_in_current_line = 0; + } + // Проверяем, последний ли это элемент + else if (total_elements == 0) { + std::cout << "]"; + break; + } + // Иначе выводим запятую и пробел + else { + std::cout << ", "; + } + + // Переходим к следующему элементу + if (!reverse) { + current++; + if (current >= end) break; + } else { + last--; + if (last <= end) break; + } + } + + 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..826178dd 100644 --- a/02_week/tasks/swap_ptr/swap_ptr.cpp +++ b/02_week/tasks/swap_ptr/swap_ptr.cpp @@ -1,6 +1,19 @@ #include +void SwapPtr(int*& a, int*& b) { + int* temp = a; + a = b; + b = temp; +} -void SwapPtr(/* write arguments here */) { - throw std::runtime_error{"Not implemented"}; +void SwapPtr(const int*& a, const int*& b) { + const int* temp = a; + a = b; + b = temp; +} + +void SwapPtr(int**& a, int**& b) { + int** temp = a; + a = b; + b = temp; } \ No newline at end of file