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
7 changes: 5 additions & 2 deletions 01_week/tasks/addition/addition.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,8 @@


int64_t Addition(int a, int b) {
throw std::runtime_error{"Not implemented"};
}
int64_t a_64 = static_cast<int64_t>(a);
int64_t b_64 = static_cast<int64_t>(b);
int64_t sum = a_64 + b_64;
return sum;
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. Причем достаточно бы было тогда одного static_cast, второй операнд не следует приводить явно, так как он бы преобразовался с помощью неявного каста. Принято использовать такую возможность и не писать явный каст самостоятельно второй раз

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

#include <iostream>

size_t CharChanger(char array[], size_t size, char delimiter = ' ') {
throw std::runtime_error{"Not implemented"};
size_t position = 0;
char current;
char next;
unsigned int n_repited_char = 1;
bool is_char_repited = false;
for (size_t i = 0; i < size-1; ++i) {
current = array[i];
next = array[i+1];
if (next == current) { // замена повторяющихся символов
++n_repited_char;
is_char_repited = true;
continue;
}
if (ispunct(current)) { //проверка на другие символы
array[position] = '_';
}
if (isdigit(current)) { // проверка на цифру
array[position] = '*';
}
if (islower(current)) { //проверка на пропись
array[position] = current - 32;
}
if (isupper(current)) { //проверка на пропись
Copy link
Contributor Author

Choose a reason for hiding this comment

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

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

array[position] = current;
}
if (isspace(current)) { //проверка единичного символа на пробел
array[position] = delimiter;
}

if (is_char_repited) { // учет повторений
if (isspace(current)) { // при пробеле
array[position] = delimiter;
}
else { // при символе
++position;
array[position] = (n_repited_char < 10) ? ('0' + n_repited_char) : '0';
}
is_char_repited = false;
n_repited_char = 1;
}
++position;
}
array[position] = '\0';
return position;
}
48 changes: 47 additions & 1 deletion 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 <string>
#include <iostream>


enum class CheckFlags : uint8_t {
Expand All @@ -14,5 +16,49 @@ enum class CheckFlags : uint8_t {
};

void PrintCheckFlags(CheckFlags flags) {
throw std::runtime_error{"Not implemented"};

uint8_t value = static_cast<uint8_t>(flags);
if (value > static_cast<uint8_t>(CheckFlags::ALL)){
return; // Если выходит за диапазон то вывод пустой
}
if (value == static_cast<uint8_t>(CheckFlags::NONE)){
std::cout << "[]";
return; // Если 0 то пустые кавычки
}

std::string check_flags = "[";
bool first = true;

if ((value & static_cast<uint8_t>(CheckFlags::TIME)) != 0){
if (!first) check_flags += ",";
check_flags += "TIME";
first = false;
}
if ((value & static_cast<uint8_t>(CheckFlags::DATE)) != 0){
if (!first) check_flags += ",";
check_flags += "DATE";
first = false;
}
if ((value & static_cast<uint8_t>(CheckFlags::USER)) != 0){
if (!first) check_flags += ",";
check_flags += "USER";
first = false;
}
if ((value & static_cast<uint8_t>(CheckFlags::CERT)) != 0){
if (!first) check_flags += ",";
check_flags += "CERT";
first = false;
}
if ((value & static_cast<uint8_t>(CheckFlags::KEYS)) != 0){
if (!first) check_flags += ",";
check_flags += "KEYS";
first = false;
}
if ((value & static_cast<uint8_t>(CheckFlags::DEST)) != 0){
if (!first) check_flags += ",";
check_flags += "DEST";
first = false;
}
Copy link
Contributor Author

Choose a reason for hiding this comment

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

дублирование кода, много строк с одинаковыми действиями, можно было избавиться от них

check_flags += "]";
std::cout << check_flags;
}
41 changes: 41 additions & 0 deletions 01_week/tasks/length_lit/length_lit.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// ft -> в другие единицы
constexpr long double operator""_ft_to_in(long double ft) {
return ft*12.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.

не хватает пробелов вокруг операторов

}
constexpr long double operator""_ft_to_m(long double ft) {
return ft*0.3048;
}
constexpr long double operator""_ft_to_cm(long double ft) {
return ft*30.48;
}
// m-> в другие единицы
constexpr long double operator""_m_to_ft(long double m) {
return m/0.3048;
}
constexpr long double operator""_m_to_in(long double m) {
return m/0.0254;
}
constexpr long double operator""_m_to_cm(long double m) {
return m*100.0;
}
// in-> в другие единицы
constexpr long double operator""_in_to_ft(long double in) {
return in/12.0;
}
constexpr long double operator""_in_to_m(long double in) {
return in*0.0254;
}
constexpr long double operator""_in_to_cm(long double in) {
return in*2.54;
}
// cm-> в другие единицы

constexpr long double operator""_cm_to_ft(long double cm) {
return cm/30.48;
}
constexpr long double operator""_cm_to_in(long double cm) {
return cm/2.54;
}
constexpr long double operator""_cm_to_m(long double cm) {
return cm/100.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.

Не принято использовать magic values в коде, пожалуй кроме 100, 1000 к примеру.
В данном случае корректнее добавить константы с понятными именами, например для 12 0.0254 0.3048 и уже в коде их использовать

24 changes: 23 additions & 1 deletion 01_week/tasks/print_bits/print_bits.cpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,29 @@
#include <cstddef>
#include <stdexcept>
#include <iostream>


void PrintBits(long long value, size_t bytes) {
throw std::runtime_error{"Not implemented"};
if (bytes <= 0 || bytes > 8) {
return;
}
size_t size = (bytes * 8) + (bytes * 2 - 1) + 4; //размер массива под число включая (bytes * 8) цифр, (bytes * 2 - 1) символов ' после каждой 4 цифры, 3 символа: 0, b, \0 и \n
char bit_num[size];
bit_num[0] = '0';
bit_num[1] = 'b';
bit_num[size - 1] = '\0';
bit_num[size - 2] = '\n';
for (size_t i = size - 3, comma_position = 1; i > 1; --i) {
if (comma_position % 5 == 0) { // добавление знака ' после каждых 4 цифр
bit_num[i] = '\'';
++comma_position;
continue;
}
char symbol = '0' + (value & 1);
bit_num[i] = symbol;
value = value >> 1;

++comma_position;
}
std::cout << bit_num;
Copy link
Contributor Author

Choose a reason for hiding this comment

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

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

}
36 changes: 34 additions & 2 deletions 01_week/tasks/quadratic/quadratic.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,38 @@
#include <stdexcept>
#include <iomanip>
#include <iostream>
#include <cmath>


void SolveQuadratic(int a, int b, int c) {
throw std::runtime_error{"Not implemented"};
}
if (a == 0 && b != 0) { // проверяем уникальные случаи коэффициентов
double x1 = static_cast<double>(-c)/b;
std::cout << std::setprecision(6) << x1;
return;
}
if (a == 0 && b == 0 && c != 0) {
std::cout << "no solutions";
return;
}
if (a == 0 && b == 0 && c == 0) {
std::cout << "infinite solutions";
return;
}
//Проверяем дискрименант
double D = b*b-4*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 4.0 и явный каст одного из b
  • пробелы вокруг операторов ставятся

if (D > 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 x1 = (-b - std::sqrt(D))/(2*a);
double x2 = (-b + std::sqrt(D))/(2*a);
std::cout << std::setprecision(6) << x1 << " " << x2;
return;
}
if (D == 0){
double x1 = static_cast<double>(-b)/(2*a);
std::cout << std::setprecision(6) << x1;
return;
}
if (D < 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.

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

std::cout << "no solutions";
return;
}
}
14 changes: 11 additions & 3 deletions 01_week/tasks/rms/rms.cpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
#include <cstdef>
#include <stdexcept>
#include <cmath>


double CalculateRMS(double values[], size_t size) {
throw std::runtime_error{"Not implemented"};
}
if (!values || size == 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.

пробел перед {

return 0.0;
}
double sum_square = 0.0;
for (size_t i = 0; i < size; ++i){
sum_square += std::pow(values[i], 2);
}
double RMS = std::sqrt(sum_square/size);
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 RMS;
}
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 <iostream>


double ApplyOperations(double a, double b /* other arguments */) {
throw std::runtime_error{"Not implemented"};
}
double ApplyOperations(double a, double b, double (*func[])(double, double), size_t size) {
if (size == 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.

пробел перед {

return 0.0;
}

double result = 0;
for (size_t i = 0; i < size; ++i) {
if (func[i] == nullptr){
result += 0.0;
continue;
}
result += func[i](a,b);
}
return result;
}
17 changes: 13 additions & 4 deletions 02_week/tasks/last_of_us/last_of_us.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
#include <stdexcept>
#include <iterator>


/* 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, bool (*predicate) (const int)) {
if ((end - begin) <= 0 || end == nullptr || begin == nullptr){
Copy link
Contributor Author

Choose a reason for hiding this comment

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

проверку указателей можно сокращать, используя неявное приведение к bool !end || !begin

return end;
}
const int* last = end;
for (; begin < end; ++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.

пробел перед {

if (predicate(*begin)) {
last = begin;
}
}
return last;
}
44 changes: 39 additions & 5 deletions 02_week/tasks/little_big/little_big.cpp
Original file line number Diff line number Diff line change
@@ -1,10 +1,44 @@
#include <stdexcept>
#include <iostream>
#include <string>
#include <iomanip>


void PrintMemory(int /* write arguments here */) {
throw std::runtime_error{"Not implemented"};
void PrintMemory(int number, bool invert = false) {
int* ptr_int = &number;
unsigned char* ptr_char = reinterpret_cast<unsigned char*>(ptr_int);
if (!invert) {
std::cout << "0x";
for (unsigned int i = 0; i < sizeof(int); ++i) {
std::cout << std::hex << std::uppercase << std::setw(2) << std::setfill('0') << static_cast<int>(ptr_char[i]);
}
std::cout << std::endl;
}
else {
std::cout << "0x";
for (int i = sizeof(int) - 1; i >= 0; --i) {
std::cout << std::hex << std::uppercase << std::setw(2) << std::setfill('0') << static_cast<int>(ptr_char[i]);
}
std::cout << std::endl;
}
Copy link
Contributor Author

Choose a reason for hiding this comment

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

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


}

void PrintMemory(double /* write arguments here */) {
throw std::runtime_error{"Not implemented"};
}
void PrintMemory(double number, bool invert = false) {
double* ptr_doub = &number;
unsigned char* ptr_char = reinterpret_cast<unsigned char*>(ptr_doub);
if (!invert) {
std::cout << "0x";
for (unsigned int i = 0; i < sizeof(double); ++i) {
std::cout << std::hex << std::uppercase << std::setw(2) << std::setfill('0') << static_cast<int>(ptr_char[i]);
}
std::cout << std::endl;
}
else {
std::cout << "0x";
for (int i = sizeof(double) - 1; i >= 0; --i) {
std::cout << std::hex << std::uppercase << std::setw(2) << std::setfill('0') << static_cast<int>(ptr_char[i]);
}
std::cout << std::endl;
}
Copy link
Contributor Author

Choose a reason for hiding this comment

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

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

}
34 changes: 32 additions & 2 deletions 02_week/tasks/longest/longest.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,36 @@
#include <stdexcept>
#include <iostream>

char* FindLongestSubsequence(const char* begin, const char* end, size_t& count) {
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"};
const char* longest_start = begin;
const char* current_start = begin;
size_t max_length = 1;
size_t current_length = 1;

for (const char* ptr = begin + 1; ptr < end; ++ptr) {
if (*ptr == *(ptr - 1)) {
++current_length;
} else {
if (current_length > max_length) {
max_length = current_length;
longest_start = current_start;
}
current_start = ptr;
current_length = 1;
}
}

// Если все символы повторяются нужно отдельно проверить еще раз
if (current_length > max_length) {
max_length = current_length;
longest_start = current_start;
}

count = max_length;
return const_cast<char*>(longest_start);
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Это UB. если изначально был указатель на константу, то снимать константность это UB.
Хорошим решением было бы две функции одна принимающая и возвращающая указатели на константы, а вторая без константности. Тогда из неконстантной версии можно было бы вызвать константную и после снять константность с помощью const_cast

}
Loading
Loading