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
14 changes: 12 additions & 2 deletions 02_week/tasks/func_array/func_array.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
#include <stdexcept>

double ApplyOperations(double a, double b, double (*func[])(double x, double y), size_t size)
{
long double sum = 0.;
if (func)
{
for (size_t i = 0; i < size; ++i)
{
if (*(func+i))
sum += func[i](a, b);
}
}

double ApplyOperations(double a, double b /* other arguments */) {
throw std::runtime_error{"Not implemented"};
return sum;
}
17 changes: 14 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,17 @@
#include <stdexcept>


/* 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(int x))
{
if (predicate && begin && 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.

Лучше написать короткую ветвь, что делать делать если данные величины nullptr.
Что уберет уровень вложенности для основного решения

size_t size = end - begin;
for (long i = size-1; i>=0; --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.

не хватает пробелов вокрыг - и >=.
также сомнительно использовать long, в него ппомещается меньше чем в size_t, что может првиести к проблемам

{
if (predicate(begin[i]))
{
return (begin + i);
}
}
}
return end;
}
70 changes: 65 additions & 5 deletions 02_week/tasks/little_big/little_big.cpp
Original file line number Diff line number Diff line change
@@ -1,10 +1,70 @@
#include <stdexcept>
#include <iostream>
#include <string>


void PrintMemory(int /* write arguments here */) {
throw std::runtime_error{"Not implemented"};
void PrintMemory(int num, bool is_inverted = false)
{

int size = sizeof(int);
unsigned char *conv = reinterpret_cast<unsigned char *>(&num); // указатель на конкретный бит в инте
Copy link
Contributor Author

@18thday 18thday Jan 12, 2026

Choose a reason for hiding this comment

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

  • указатель приклеиваем к типу, не к имени переменной
  • некорректный комментарий, указатель на байт, не на бит

std::string str; // строка, которую мы выведем

char dict[] = {"0123456789ABCDEF"}; // массив символов, в которые мы будем переводить
Copy link
Contributor Author

Choose a reason for hiding this comment

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

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


if (is_inverted) //big endian
{
conv += size-1;
for (; conv >= reinterpret_cast<unsigned char *>(&num); --conv)
{
str.push_back(dict[*conv >> 4]);
str.push_back(dict[*conv & 0b00001111]);
}
}

else // little endian
{
for (; conv - reinterpret_cast<unsigned char *>(&num) < size; ++conv)
{
str.push_back(dict[*conv >> 4]);
str.push_back(dict[*conv & 0b00001111]);
}
}
Copy link
Contributor Author

Choose a reason for hiding this comment

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

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

std::cout << "0x" << str << std::endl;


}

void PrintMemory(double /* write arguments here */) {
throw std::runtime_error{"Not implemented"};
}
void PrintMemory(double num, bool is_inverted = 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.

лишняя пустая строка

int size = sizeof(double);
unsigned char *conv = reinterpret_cast<unsigned char *>(&num); // указатель на конкретный бит в дабле
std::string str;// строка, которую мы выведем

char dict[] = {"0123456789ABCDEF"}; // массив символов, в которые мы будем переводить

if (is_inverted) //big endian
{
conv += size-1;
for (; conv >= reinterpret_cast<unsigned char *>(&num); --conv)
{
str.push_back(dict[*conv >> 4]);
str.push_back(dict[*conv & 0b00001111]);
}
}

else // little endian
{
for (; conv - reinterpret_cast<unsigned char *>(&num) < size; ++conv)
{
str.push_back(dict[*conv >> 4]);
str.push_back(dict[*conv & 0b00001111]);
}
}
Copy link
Contributor Author

Choose a reason for hiding this comment

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

решение аналогичное и дублирует код предыдущей функции. Правильнее было общую часть вынести в третью функцию и после получения указателя на unsigned char*, зная sizeof от типа вызывать эту функцию с общим кодом из фукнции с double и с int



Copy link
Contributor Author

Choose a reason for hiding this comment

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

лишние строки пустые

std::cout << "0x" << str << 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.

лишние строки пустые

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

char *FindLongestSubsequence(char *begin, char *end, size_t &count)
{
count = 0;
if (begin && 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.

это должна быть проверка на особые условия и выход по короткой ветви с nullptr

{

/* return_type */ FindLongestSubsequence(/* ptr_type */ begin, /* ptr_type */ end, /* type */ count) {
throw std::runtime_error{"Not implemented"};
char *subsequence = nullptr;
for (long i = 0; i < end - begin; ++i)
{
char *newsequence = begin + i;
size_t t = 1;
while (*newsequence == *(newsequence + t) && newsequence + t < end)
{
++i;
++t;
}
if (t > count)
{
count = t;
subsequence = newsequence;
}
}
return subsequence;
}
return nullptr;
}

const char *FindLongestSubsequence(const char *begin, const char *end, size_t &count)
Copy link
Contributor Author

Choose a reason for hiding this comment

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

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

{
count = 0;
size_t pos = 0;
if (begin && end)
{

for (long i = 0; i < end - begin; ++i)
{
size_t t = 1;
const char *newsubsequence = begin + i;
while (*newsubsequence == *(newsubsequence + t) && i < end - begin - 1)
{
++i;
++t;
}
if (t > count)
{
count = t;
pos = i - t + 1;
}
}
return begin + pos;
}
return nullptr;
}
51 changes: 48 additions & 3 deletions 02_week/tasks/pretty_array/pretty_array.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,51 @@
#include <stdexcept>
#include <iostream>
#include <cmath>

void PrintArray(std::nullptr_t, std::nullptr_t)
{
std::cout<<"[]\n";
}




template<typename T>
void PrintArray(T* begin, T* end, size_t limiter = 0)
{
if (begin && end && begin != end)
{
std::cout << '[';

size_t len = abs(begin-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.

отсутствуют пробелы

if (begin < end)
{
for (size_t i = 0; i < len; ++i)
{
if (limiter && i != 0 && !(i % limiter))
std::cout << "...\n" << ' ';

i!=(len-1)? ( std::cout << begin[i] << ", "): ( std::cout << begin[i] << "]\n");
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
{
for (size_t i = 0; i < len; ++i)
{
if (limiter && i != 0 && !(i % limiter))
std::cout << "...\n" << ' ';
T *current = begin - i;
current == end + 1 ? (std::cout << *current) : (std::cout << *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.

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

std::cout<<"]\n";
Copy link
Contributor Author

Choose a reason for hiding this comment

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

отсутствуют пробелы вокруг оператора

}
}
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
{
std::cout<<"[]\n";
}
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 PrintArray(/* write arguments here */) {
throw std::runtime_error{"Not implemented"};
}
34 changes: 31 additions & 3 deletions 02_week/tasks/swap_ptr/swap_ptr.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,34 @@
#include <stdexcept>


void SwapPtr(/* write arguments here */) {
throw std::runtime_error{"Not implemented"};
}


void SwapPtr(int*& a, int*& b)
{
int* c = a;
a = b;
b = c;
}

void SwapPtr(const int*& a, const int*& b){
const int* c = a;
a = b;
b = c;
}

void SwapPtr(int**& a, int**& b)
{
int** c = a;
a = b;
b = c;
}

Copy link
Contributor Author

@18thday 18thday Jan 12, 2026

Choose a reason for hiding this comment

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

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


/* рабочий вариант через template для любого типа данных. на лекции не проходили, просто показать что я нашел и такую штуку
template<typename T>
void SwapPtr(T*& a, T*& b){
T* c = a;
a = b;
b = c;
}
*/
33 changes: 30 additions & 3 deletions 03_week/tasks/data_stats/data_stats.cpp
Original file line number Diff line number Diff line change
@@ -1,11 +1,38 @@
#include <stdexcept>

#include <vector>
#include <math.h>
Copy link
Contributor Author

Choose a reason for hiding this comment

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

#include <cmath> подключаем библиотеку на C++


struct DataStats {
double avg = 0.0;
double sd = 0.0;
};

/* return_type */ CalculateDataStats(/* args */) {
throw std::runtime_error{"Not implemented"};
struct DataStats CalculateDataStats(std::vector<int> data) {

struct DataStats output;
if (data.empty()){
output.avg = 0.;
output.sd = 0.;
return output;
}

/*
стандартная девиация считается как sqrt(сумма((i - avg)^2)/size)
если разложим квадратное уравнение: sqrt(сумма(i^2 - 2*i*avg + avg^2)/size)=>
sqrt((сумма(i^2)+ сумма(- 2* i*avg)+сумма(avg^2))/size) - его имплементируем
*/

double first_num = 0.;
double second_num= 0.;

for (size_t i=0; i< data.size(); ++i){
output.avg+=data[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.

пробелы

first_num += static_cast<double>(data[i])*static_cast<double>(data[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.

лишний каст, достаточно одного каста

second_num+= data[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.

не все пробелы

}
output.avg /= data.size();
output.sd = first_num - 2. * second_num * output.avg + output.avg * output.avg * data.size();
output.sd /= data.size();
output.sd = sqrt(output.sd);
Copy link
Contributor Author

Choose a reason for hiding this comment

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

для библиотек C++ используем std::sqrt

return output;
}
41 changes: 37 additions & 4 deletions 03_week/tasks/easy_compare/easy_compare.cpp
Original file line number Diff line number Diff line change
@@ -1,16 +1,49 @@
#include <stdexcept>
#include <tuple>


struct Date {
struct Date
{
unsigned year;
unsigned month;
unsigned day;
};

struct StudentInfo {
struct StudentInfo
{
size_t id;
char mark;
int score;
unsigned course;
Date birth_date;
};
};

bool operator<(const Date &s1, const Date &s2)
{
return std::tie(s1.year, s1.month, s1.day) < std::tie(s2.year, s2.month, s2.day);
}

bool operator==(const Date &s1, const Date &s2)
{
return std::tie(s1.year, s1.month, s1.day) == std::tie(s2.year, s2.month, s2.day);
}

bool operator==(const StudentInfo &s1, const StudentInfo &s2)
{
return std::tie(s1.mark, s1.score) == std::tie(s2.mark, s2.score);
}

bool operator<(const StudentInfo &s1, const StudentInfo &s2)
{
return std::tie(s2.mark, s1.score, s2.course, s1.birth_date) <
std::tie(s1.mark, s2.score, s1.course, s2.birth_date);
}

bool operator!=(const StudentInfo &s1, const StudentInfo &s2) { return !(s1 == s2); }
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 operator>(const StudentInfo &s1, const StudentInfo &s2) { return s2 < s1; }
bool operator<=(const StudentInfo &s1, const StudentInfo &s2) { return !(s2 < s1); }
bool operator>=(const StudentInfo &s1, const StudentInfo &s2) { return !(s1 < s2); }

bool operator!=(const Date &d1, const Date &d2) { return !(d1 == d2); }
bool operator>(const Date &d1, const Date &d2) { return d2 < d1; }
bool operator<=(const Date &d1, const Date &d2) { return !(d2 < d1); }
bool operator>=(const Date &d1, const Date &d2) { return !(d1 < d2); }
Loading