-
Notifications
You must be signed in to change notification settings - Fork 33
Еремин Даниил #36
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Еремин Даниил #36
Changes from all commits
31ce710
f299b48
b31a9d1
643d325
9744f6e
48d2baf
be553da
852bf3a
d704a5e
4ef2338
afc1d22
2b41f11
af33200
5eddea2
be140db
d57c94c
0e3b4bf
6779b17
e61c5b9
7370299
b7cb116
280c7d6
067405d
bc3dc9b
6e34b9c
ce86dd7
ea262f1
7d1d00b
67e42d0
c46016a
1b359da
c06738d
01adc7e
92d14f4
87cab48
30bd518
ac16b5b
795eb5b
a78c741
2796646
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| build/ | ||
| .vs/ | ||
| CMakeLists.txt.user | ||
| CMakeSettings.json | ||
| CMakeUserPresets.json | ||
| .vscode/ | ||
| *.out |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,64 @@ | ||
| #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 size, char delimiter = ' '){ | ||
| //Массив для подстановки кол-ва повторений | ||
| char intToChar[10] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; | ||
| //Индексы | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. много лишних комментариев |
||
| size_t i = 0; | ||
| size_t j = 1; | ||
| size_t k = 0; | ||
|
|
||
| int reps = 1; // кол-во повторений символа | ||
| while(j < size){ | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. не хватает пробелов после while и перед {, аналогично для if |
||
| // Если есть повторы, то сначала считаются они | ||
| if(array[i] == array[j]){ | ||
| ++reps; | ||
| j++; | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. тоже должен быть префиксным |
||
| continue; | ||
| } | ||
|
|
||
| array[k] = array[i]; | ||
| //Если повторы были, то записывается число | ||
| if(reps != 1 && array[i] != ' '){ | ||
| array[k+1] = reps < 10 ? intToChar[reps] : intToChar[0]; | ||
| } | ||
|
|
||
| //Проверка, что это символ алфавита и он в нижнем регистре | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. это лишний комментарий, поскольку по коду понятно что происходит |
||
| if(char c = array[k]; std::isalpha(c) && std::islower(c)){ | ||
| array[k] = std::toupper(c); | ||
| } | ||
| //Отдельно обрабатываются пробелы | ||
| else if(array[k] == ' '){ | ||
| array[k] = delimiter; | ||
| ++k; | ||
| i = j++; | ||
| reps = 1; | ||
| continue; | ||
| } | ||
| //Замена цифр | ||
| else if(std::isdigit(array[k])){ | ||
| array[k] = '*'; | ||
| } | ||
| //Замена остальных символов | ||
| else if(!(std::isalpha(array[k]))){ | ||
| array[k] = '_'; | ||
| } | ||
|
|
||
| //Сдвигаем индексы в зависимости от повторов | ||
| if(reps == 1){ | ||
| ++k; | ||
| } | ||
| else if(reps != 1){ | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. лишняя проверка |
||
| k+= 2; | ||
| reps = 1; | ||
| } | ||
| i = j++; | ||
| } | ||
|
|
||
| //В конце добавляется нуль-терминатор | ||
| array[k] = '\0'; | ||
|
|
||
| return k; | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. хотелось бы для k более понятное название |
||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,10 @@ | ||
| #include <cstdint> | ||
| #include <stdexcept> | ||
|
|
||
| #include <unordered_map> | ||
| #include <iostream> | ||
| #include <vector> | ||
| #include <string> | ||
| #include <sstream> | ||
|
|
||
| enum class CheckFlags : uint8_t { | ||
| NONE = 0, | ||
|
|
@@ -14,5 +18,54 @@ enum class CheckFlags : uint8_t { | |
| }; | ||
|
|
||
| void PrintCheckFlags(CheckFlags flags) { | ||
| throw std::runtime_error{"Not implemented"}; | ||
| //Хэш-таблица для быстрого преобразования uint8_t -> string | ||
| std::unordered_map<uint8_t, std::string> flagStr = { | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. не очень хорошее решение |
||
| {0b00000001,"TIME"}, | ||
| {0b00000010,"DATE"}, | ||
| {0b00000100,"USER"}, | ||
| {0b00001000,"CERT"}, | ||
| {0b00010000,"KEYS"}, | ||
| {0b00100000,"DEST"} | ||
| }; | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Это грустно, так как при изменениии CheckFlags надо будет тут менять, а хотелось бы чтобы не было такой зависимости |
||
|
|
||
| //Вектор с результатом работы функции | ||
| std::vector<std::string> result = {"["}; | ||
| //Резервирование места под элементы, чтобы не было лишних реаллокаций | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. выше уже есть одна |
||
| result.reserve(16); | ||
|
|
||
|
|
||
| if(flags == CheckFlags::NONE){ | ||
| std::cout << "[]"; | ||
| return; | ||
| } | ||
| else if(flags == CheckFlags::ALL) | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. если есть return выше то else лучше убрать, это разные случаи |
||
| { | ||
| std::cout << "[TIME,DATE,USER,CERT,KEYS,DEST]"; | ||
| return; | ||
| } | ||
| //Если флаг больше ALL значит он выходит из диапазона значений флагов | ||
| else if(static_cast<uint8_t>(flags) > static_cast<uint8_t>(CheckFlags::ALL)) | ||
| { | ||
| std::cout << ""; | ||
| return; | ||
| } | ||
| //В остальных случаях флаги перебираются и добавляюся в вектор если присутствуют | ||
| else | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. это лишний уровень вложенности |
||
| { | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. получается до этого мы зря создавали result и выделяли под него память, поскольку в коротких ветках особых случаев он не использовался |
||
| for(uint8_t flag = 1; flag < static_cast<uint8_t>(CheckFlags::ALL); flag *= 2){ | ||
| if(static_cast<uint8_t>(flags) & flag){ | ||
| result.push_back(flagStr[flag]); | ||
| result.push_back(","); | ||
| } | ||
| } | ||
| } | ||
|
|
||
|
|
||
| result.pop_back(); //Убираем лишнюю запятую | ||
| result.push_back("]"); | ||
|
|
||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. не сильно оптимальная функция, можно было сразу в поток выводить |
||
| //Вывод результата | ||
| for(auto& elem : result){ | ||
| std::cout << elem; | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| //Футы в дюймы | ||
| constexpr double operator""_ft_to_in(long double ft) { | ||
| return ft * 12.0; | ||
| } | ||
|
|
||
| //Футы в сантиметры | ||
| constexpr double operator""_ft_to_cm(long double ft) { | ||
| return ft * 30.48; | ||
| } | ||
|
|
||
| //Футы в метры | ||
| constexpr double operator""_ft_to_m(long double ft) { | ||
| return ft * 0.3048; | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Не стоит использовать безымянные magic values, в данном случае корректнее определить константы с понятными именами для0.3048 0.0254 12.0 в безымянном namespace и уже с ними работать в коде, для 100 можно тоже, но можно оставить и в коде |
||
| } | ||
|
|
||
| //Дюймы в футы | ||
| constexpr double operator""_in_to_ft(long double in) { | ||
| return in / 12.0; | ||
| } | ||
|
|
||
| //Дюймы в сантиметры | ||
| constexpr double operator""_in_to_cm(long double in) { | ||
| return in * 2.54; | ||
| } | ||
|
|
||
| //Дюймы в метры | ||
| constexpr double operator""_in_to_m(long double in) { | ||
| return in * 0.0254; | ||
| } | ||
|
|
||
| //Сантиметры в футы | ||
| constexpr double operator""_cm_to_ft(long double cm) { | ||
| return cm / 30.48; | ||
| } | ||
|
|
||
| //Сантиметры в дюймы | ||
| constexpr double operator""_cm_to_in(long double cm) { | ||
| return cm / 2.54; | ||
| } | ||
|
|
||
| //Сантиметры в метры | ||
| constexpr double operator""_cm_to_m(long double cm) { | ||
| return cm * 0.01; | ||
| } | ||
|
|
||
| //Метры в футы | ||
| constexpr double operator""_m_to_ft(long double m) { | ||
| return m / 0.3048; | ||
| } | ||
|
|
||
| //Метры в дюймы | ||
| constexpr double operator""_m_to_in(long double m) { | ||
| return m / 0.0254; | ||
| } | ||
|
|
||
| //Метры в сантиметры | ||
| constexpr double operator""_m_to_cm(long double m) { | ||
| return m * 100; | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,22 @@ | ||
| #include <cstddef> | ||
| #include <stdexcept> | ||
|
|
||
| #include <vector> | ||
| #include <iostream> | ||
|
|
||
| void PrintBits(long long value, size_t bytes) { | ||
| throw std::runtime_error{"Not implemented"}; | ||
| size_t bitLen = 8 * bytes; | ||
| std::vector<char> bits(bitLen); | ||
|
|
||
| for(size_t i = 0; i < bitLen; ++i){ | ||
| bits[bitLen-i-1] = value % 2 == 0 ? '0' : '1'; | ||
| value = value >> 1; | ||
| } | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. можно было реализовать в один проход, без выделения доп памяти |
||
|
|
||
| std::cout << "0b"; | ||
| for(size_t i = 0; i < bitLen; ++i){ | ||
| std::cout << bits[i]; | ||
| if((i+1) % 4 == 0 && (i+1) != bitLen){ | ||
| std::cout << '\''; | ||
| } | ||
| } | ||
| std::cout << "\n"; | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,39 @@ | ||
| #include <stdexcept> | ||
|
|
||
| #include <iostream> | ||
| #include <iomanip> | ||
| #include <cmath> | ||
|
|
||
| void SolveQuadratic(int a, int b, int c) { | ||
| throw std::runtime_error{"Not implemented"}; | ||
| //Установка точности вывода в 6 символов | ||
| std::cout << std::setprecision(6); | ||
|
|
||
| double eps = 1e-3; // Погрешность при сравнении double | ||
| double x1{0}, x2{0}; | ||
| long long d = static_cast<long long>(b) * b - 4 * static_cast<long long>(a) * c; | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. зачем считать дескриминант так рано, если мы ещё не проверили короткие случаи |
||
| if(d < 0){ | ||
| std::cout << "no solutions"; | ||
| } | ||
| else if(a == 0 && b == 0 && c != 0){ | ||
| std::cout << "no solutions"; | ||
| } | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. так не очень удобно делать, так как нужно дойти до конца всей функции, чтобы понять что ничего больше не происходит. поэтому в таких случаях лучше из короткой ветви выполнять return и убрать else |
||
| else if(a != 0){ | ||
| x1 = (-b + sqrt(d)) / (2*a); | ||
| x2 = (-b - sqrt(d)) / (2*a); | ||
|
|
||
| if((x1 - x2) < eps){ | ||
| std::cout << x1; | ||
| } | ||
| else{ | ||
| if(x1 > x2){ | ||
| std::swap(x1, x2); | ||
| } | ||
| std::cout << x1 << " " << x2; | ||
| } | ||
| } | ||
| else if(a == 0 && b == 0 && c == 0){ | ||
| std::cout << "infinite solutions"; | ||
| } | ||
| else if(b != 0){ | ||
| x1 = -c / static_cast<double>(b); | ||
| std::cout << x1; | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,16 @@ | ||
| #include <cstdef> | ||
| #include <cstddef> | ||
| #include <stdexcept> | ||
| #include <cmath> | ||
|
|
||
|
|
||
| double CalculateRMS(double values[], size_t size) { | ||
| throw std::runtime_error{"Not implemented"}; | ||
| if(values == nullptr || size == 0){ | ||
| return 0.0; | ||
| } | ||
|
|
||
| double res {0.0}; | ||
| for(size_t i = 0; i < size; ++i){ | ||
| res += values[i]*values[i]; | ||
| } | ||
| return sqrt(res/size); | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,13 @@ | ||
| #include <stdexcept> | ||
| #include <cstddef> | ||
|
|
||
|
|
||
| double ApplyOperations(double a, double b /* other arguments */) { | ||
| throw std::runtime_error{"Not implemented"}; | ||
| double ApplyOperations(double a, double b, double (**functions)(double, double), size_t size) { | ||
| if(size == 0) return 0.0; | ||
|
|
||
| double res{}; | ||
| for(size_t i = 0; i < size; ++i){ | ||
| res += functions[i] == nullptr ? 0.0 : functions[i](a, b); | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. допустимо для указателей пользоваться возможностью неявного приведения к bool (!functions[i]), часто именно так принято |
||
| } | ||
|
|
||
| return res; | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,9 @@ | ||
| #include <stdexcept> | ||
|
|
||
| const int* FindLastElement(const int* begin, const int* end, bool (*predicate)(int)) { | ||
| if(begin == nullptr || end == nullptr || begin > end) return end; | ||
|
|
||
| /* return_type */ FindLastElement(/* ptr_type */ begin, /* ptr_type */ end, /* func_type */ predicate) { | ||
| throw std::runtime_error{"Not implemented"}; | ||
| for(int* current = const_cast<int*>(end-1); current != begin-1; --current){ | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. это UB, нельзя снимать константность с помощью const cast с изначально константного объекта |
||
| if(predicate(*current)) return current; | ||
| } | ||
| return end; | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,10 +1,47 @@ | ||
| #include <stdexcept> | ||
| #include <iostream> | ||
| #include <cstddef> | ||
| #include <iomanip> | ||
|
|
||
|
|
||
| void PrintMemory(int /* write arguments here */) { | ||
| throw std::runtime_error{"Not implemented"}; | ||
| void PrintMemory(int num, bool inverse = false) { | ||
| const size_t size = sizeof(int); | ||
| auto ptr = reinterpret_cast<const unsigned char*>(&num); | ||
|
|
||
| std::cout << "0x"; | ||
|
|
||
| if (inverse) { | ||
| // little-endian | ||
| for (size_t i = size - 1; i < size; --i) { | ||
| std::cout << std::uppercase << std::hex << std::setw(2) << std::setfill('0') | ||
| << static_cast<unsigned int>(ptr[i]); | ||
| } | ||
| } else { | ||
| // big-endian | ||
| for (size_t i = 0; i < size; ++i) { | ||
| std::cout << std::uppercase << std::hex << std::setw(2) << std::setfill('0') | ||
| << static_cast<unsigned int>(ptr[i]); | ||
| } | ||
| } | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. тут явное дублирование циклов, можно было подумать как избавится от него |
||
| std::cout << std::endl; | ||
| } | ||
|
|
||
| void PrintMemory(double /* write arguments here */) { | ||
| throw std::runtime_error{"Not implemented"}; | ||
| void PrintMemory(double num, bool inverse = false) { | ||
| const size_t size = sizeof(double); | ||
| auto ptr = reinterpret_cast<const unsigned char*>(&num); | ||
|
|
||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. идет полное дублирование кода, после получения указателя и, зная sizeof типа num, можно было вызвать третью функцию без дублирования кода |
||
| std::cout << "0x"; | ||
|
|
||
| if (inverse) { | ||
| //little-endian | ||
| for (size_t i = size - 1; i < size; --i) { | ||
| std::cout << std::uppercase << std::hex << std::setw(2) << std::setfill('0') | ||
| << static_cast<unsigned int>(ptr[i]); | ||
| } | ||
| } else { | ||
| // big-endian | ||
| for (size_t i = 0; i < size; ++i) { | ||
| std::cout << std::uppercase << std::hex << std::setw(2) << std::setfill('0') | ||
| << static_cast<unsigned int>(ptr[i]); | ||
| } | ||
| } | ||
| std::cout << std::endl; | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
обычно короткие выражения пишут сразу в return без дополнительных переменных