Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions 01_week/tasks/addition/addition.cpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
#include <cstdint>
#include <stdexcept>


int64_t Addition(int a, int b) {
throw std::runtime_error{"Not implemented"};
return static_cast<int64_t>(a) + static_cast<int64_t>(b);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Лишний каст, второй операнд не следует приводить явно, так как он бы преобразовался с помощью неявного каста. Принято использовать такую возможность и не писать явный каст самостоятельно второй раз

}
50 changes: 46 additions & 4 deletions 01_week/tasks/char_changer/char_changer.cpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,49 @@
#include <cstddef>
#include <stdexcept>
#include <cctype>


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; // Счётчик повторяющихся символов
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Лучше, чтобы название отражало то, что написанно в комментариях

int write = 0; // Указатель для записи обработанного символа
Copy link
Contributor Author

@18thday 18thday Jan 5, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В данном случае это позиция, не указатель, лучше не вводить в замешательство, а еще может лучше добавть префикс pos_write, тогда комментарии излишни

int read = 0; // Указатель для чтения следующего элемента из массива
char repeating_symbol = array[read]; // В процессе выполнения - редыдущий символ после read(отслеживаем повторения)

while (repeating_symbol != '\0'){
if (repeating_symbol == array[read]){
counter++;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

здесь и далее корректней использовать префиксный инкремент

} else {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

лучше для if сделать короткую ветвь с continue:

  1. Не придется листать много кода, что увидеть действие перед переходом на следующую итерацию цикла, либо даже лучше переписать на for
  2. Можно будет убрать 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;
Copy link
Contributor Author

@18thday 18thday Jan 5, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

как будто поусловию некорректно сбрасывать счетчик, тогда мы начнем считать заного и можно насчитать другое число

}

if (counter != 1){
array[write] = static_cast<char>(counter + '0'); // Преобразуем число в символ
counter = 1;
write++;
}

repeating_symbol = array[read];
}

read++;
}

array[write] = '\0';
return write;
}
3 changes: 1 addition & 2 deletions 01_week/tasks/check_flags/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,4 @@

Если передан флаг отсутствия проверок, то необходимо вывести пустые `[]`.

Если передано значение выходит из возможного диапазона значений, то вывод
следует оставить пустым.
Если переданное значение выходит из возможного диапазона значений, то вывод следует оставить пустым.
45 changes: 42 additions & 3 deletions 01_week/tasks/check_flags/check_flags.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
#include <cstdint>
#include <stdexcept>
#include <iostream>
#include <vector>
#include <string>


enum class CheckFlags : uint8_t {
Expand All @@ -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<uint8_t>(flags) & ~static_cast<uint8_t>(CheckFlags::ALL)) != 0) {
std::cout << "";
return;
}

std::vector<std::string> set_flags;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Выглядит очень не оптимально, во первых вектор будет вызывать реалокацию при push_back.
Да и будем перекладывать строки из вектора в поток

if ((static_cast<uint8_t>(flags) & static_cast<uint8_t>(CheckFlags::TIME)) != 0) {
set_flags.push_back("TIME");
}
if ((static_cast<uint8_t>(flags) & static_cast<uint8_t>(CheckFlags::DATE)) != 0) {
set_flags.push_back("DATE");
}
if ((static_cast<uint8_t>(flags) & static_cast<uint8_t>(CheckFlags::USER)) != 0) {
set_flags.push_back("USER");
}
if ((static_cast<uint8_t>(flags) & static_cast<uint8_t>(CheckFlags::CERT)) != 0) {
set_flags.push_back("CERT");
}
if ((static_cast<uint8_t>(flags) & static_cast<uint8_t>(CheckFlags::KEYS)) != 0) {
set_flags.push_back("KEYS");
}
if ((static_cast<uint8_t>(flags) & static_cast<uint8_t>(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 << "]";
}
67 changes: 67 additions & 0 deletions 01_week/tasks/length_lit/length_lit.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
#include <string>


// Константы для преобразования
constexpr long double IN_TO_CM = 2.54L;
constexpr long double FT_TO_IN = 12.0L;
constexpr long double M_TO_CM = 100.0L;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это правильный подход, добавить константы


// ft -> in
double operator"" _ft_to_in(long double ft_value) {
return static_cast<double>(ft_value * FT_TO_IN);
}

// ft -> cm
double operator"" _ft_to_cm(long double ft_value) {
return static_cast<double>(ft_value * FT_TO_IN * IN_TO_CM);
}

// ft -> m
double operator"" _ft_to_m(long double ft_value) {
return static_cast<double>(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<double>(in_value / FT_TO_IN);
}

// in -> cm
double operator"" _in_to_cm(long double in_value) {
return static_cast<double>(in_value * IN_TO_CM);
}

// in -> m
double operator"" _in_to_m(long double in_value) {
return static_cast<double>(in_value * IN_TO_CM / M_TO_CM);
}

// cm -> ft
double operator"" _cm_to_ft(long double cm_value) {
return static_cast<double>(cm_value / IN_TO_CM / FT_TO_IN);
}

// cm -> in
double operator"" _cm_to_in(long double cm_value) {
return static_cast<double>(cm_value / IN_TO_CM);
}

// cm -> m
double operator"" _cm_to_m(long double cm_value) {
return static_cast<double>(cm_value / M_TO_CM);
}

// m -> ft
double operator"" _m_to_ft(long double m_value) {
return static_cast<double>(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<double>(m_value * M_TO_CM / IN_TO_CM);
}

// m -> cm
double operator"" _m_to_cm(long double m_value) {
return static_cast<double>(m_value * M_TO_CM);
}
26 changes: 23 additions & 3 deletions 01_week/tasks/print_bits/print_bits.cpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,27 @@
#include <cstddef>
#include <stdexcept>
#include <iostream>
#include <vector>


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;
}
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Можно 5 строк заменитьтернарным оператор выводить в поток по условию 1 или 0, будет компактнее


if (i != 0 && i % 4 == 0) {
std::cout << "'";
}
}
std::cout << '\n';
}
33 changes: 31 additions & 2 deletions 01_week/tasks/quadratic/quadratic.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,35 @@
#include <stdexcept>
#include <iostream>
#include <cmath>
#include <iomanip>
#include <algorithm> // Для 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<double>(-c) / b;
std::cout << std::defaultfloat << std::setprecision(6) << x;
}
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

лучше не громоздить вложенность, особые случаи в отдельные ветви выделить, может немного больше будет сравнений, менее эффективно, но читаться будет приятней бнз такого уровня вложенности

} else {
long long discriminant = static_cast<long long>(b) * b - 4 * static_cast<long long>(a) * c;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Понятно для чего так сделано, но не лучше хранить дискриминант в double в данном случае


if (discriminant > 0) {
double x1 = (-b - std::sqrt(static_cast<double>(discriminant))) / (2 * a);
double x2 = (-b + std::sqrt(static_cast<double>(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<double>(-b) / (2 * a);
std::cout << std::defaultfloat << std::setprecision(6) << x;
} else {
std::cout << "no solutions";
}
}
}
13 changes: 10 additions & 3 deletions 01_week/tasks/rms/rms.cpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
#include <cstdef>
#include <stdexcept>
#include <cstddef>
#include <cmath>


double CalculateRMS(double values[], size_t size) {
throw std::runtime_error{"Not implemented"};
if (size <= 0 || values == nullptr){ return 0.0; }
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

отсутствует пробел перед {


double sum = 0;
for (size_t i=0; i < size; i++){
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нужно использовать префиксный инкремент

sum+=std::pow(values[i], 2);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

нет пробелов вокруг арифметических операторов и инициализации i

}

return std::sqrt(sum / size);
}
19 changes: 16 additions & 3 deletions 02_week/tasks/func_array/func_array.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,19 @@
#include <stdexcept>
#include <cstddef>

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) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

наглядней было быиспользовать массив указателей на функцию, вместо указателя на указатель на функцию

if (arr == nullptr || funcArraySize <= 0){
return 0.0;
}

double cumulative_result = 0;
for (unsigned int i=0; i < funcArraySize; ++i){
Copy link
Contributor Author

@18thday 18thday Jan 5, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

пробелы вокруг =

if (arr[i] == nullptr){
continue;
}
cumulative_result+=arr[i](a, b);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

пробелы вокруг оператора +=

}

return cumulative_result;
}
2 changes: 1 addition & 1 deletion 02_week/tasks/last_of_us/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
элемент, удовлетворяющий условию функции предиката. Функция принимает два
указателя на начало и конец целочисленного массива, а также указатель на
функцию предикат, и возвращает указатель на найденный элемент. Если элемент
не найден, то возвращается указатель за последний элемент.
не найден, то возвращается указатель на последний элемент.
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это некорректное исправление так как, end не указывает на элемент и его нельзя разыменовывать


Указатели соответствуют диапазону $[begin, end)$.

Expand Down
30 changes: 27 additions & 3 deletions 02_week/tasks/last_of_us/last_of_us.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,30 @@
#include <stdexcept>
#include <cstddef>

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;
}
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

можно упростить алгоритм поскольку нам нужен последний, быстрее идти с конца и при первом срабатывании сразу возвращать из функции нужный указатель


++begin;
}

if (last_element == nullptr){
return end;
}
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

вероятно это лишняя проверка, так как можно last_element присвоить end изначально и тогда если успешных проверок не было, просто вернется last_element с нужным значением


return last_element;
}
Loading
Loading