diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..43adaaf0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +# Build directories +build/ +*/build/ +*/build*/ + +# IDE +.vscode/ \ No newline at end of file diff --git a/01_week/tasks/addition/addition.cpp b/01_week/tasks/addition/addition.cpp index 92872802..f51e4e98 100644 --- a/01_week/tasks/addition/addition.cpp +++ b/01_week/tasks/addition/addition.cpp @@ -3,5 +3,6 @@ int64_t Addition(int a, int b) { - throw std::runtime_error{"Not implemented"}; + int64_t result = static_cast(a) + static_cast(b); + return result; } \ No newline at end of file diff --git a/01_week/tasks/char_changer/README.md b/01_week/tasks/char_changer/README.md index a3aab410..0e09908b 100644 --- a/01_week/tasks/char_changer/README.md +++ b/01_week/tasks/char_changer/README.md @@ -13,7 +13,7 @@ 1. Строчные латинские символы заменяются на прописные, правило 1 действует 1. Последовательные пробельные символы, заменяются на один без указания числа повторений и преобразуются в заданный извне разделитель `delimeter`. -1. Все остальные символы заменяются на символ `_` +1. Все остальные символы заменяются на символ `_`. Правило 1 действует Гарантируется, что последний символ в массиве `'\0'`. diff --git a/01_week/tasks/char_changer/char_changer.cpp b/01_week/tasks/char_changer/char_changer.cpp index 3a7344d9..04b4b212 100644 --- a/01_week/tasks/char_changer/char_changer.cpp +++ b/01_week/tasks/char_changer/char_changer.cpp @@ -1,7 +1,79 @@ #include #include +#include +size_t Counter(char array[], size_t size, size_t startIdx){ + char symbol = array[startIdx]; + size_t count = 1; + for (size_t i=startIdx+1; i= +'0' && array[i] <= +'9'){ + result[new_ar_pos] = '*'; + if (count >= 10){ + ++new_ar_pos; + result[new_ar_pos] = '0'; + } + else if (count > 1){ + ++new_ar_pos; + result[new_ar_pos] = count + '0'; + } + } + else if (array[i] >= +'a' && array[i] <= +'z'){ + result[new_ar_pos] = std::toupper(array[i]); + if (count >= 10){ + ++new_ar_pos; + result[new_ar_pos] = '0'; + } + else if (count > 1){ + ++new_ar_pos; + result[new_ar_pos] = count + '0'; + } + } + else if (array[i] >= +'A' && array[i] <= +'Z'){ + result[new_ar_pos] = array[i]; + if (count >= 10){ + ++new_ar_pos; + result[new_ar_pos] = '0'; + } + else if (count > 1){ + ++new_ar_pos; + result[new_ar_pos] = count + '0'; + } + } + else{ + result[new_ar_pos] = '_'; + if (count >= 10){ + ++new_ar_pos; + result[new_ar_pos] = '0'; + } + else if (count > 1){ + ++new_ar_pos; + result[new_ar_pos] = count + '0'; + } + } + i += count; + ++new_ar_pos; + } + for (size_t i = 0; i < new_ar_pos && i < size - 1; ++i) { + array[i] = result[i]; + } + array[std::min(new_ar_pos, size - 1)] = '\0'; + return new_ar_pos; } + diff --git a/01_week/tasks/check_flags/check_flags.cpp b/01_week/tasks/check_flags/check_flags.cpp index 75e7c652..184c4413 100644 --- a/01_week/tasks/check_flags/check_flags.cpp +++ b/01_week/tasks/check_flags/check_flags.cpp @@ -14,5 +14,28 @@ enum class CheckFlags : uint8_t { }; void PrintCheckFlags(CheckFlags flags) { - throw std::runtime_error{"Not implemented"}; + + uint8_t flags_int = static_cast(flags); + if (flags_int > static_cast(CheckFlags::ALL)) { + std::cout << ""; + return; + } + + std::string names[6] = {"TIME", "DATE", "USER", "CERT", "KEYS" , "DEST"}; + std::string result = "["; + bool symbol_added = false; + + uint8_t mask = 1; + for (size_t i = 0; i < 6; ++i) { + mask = (1 << i); + if (flags_int & mask) { + if (symbol_added) { + result += ","; + } + result += names[i]; + symbol_added = true; + } + } + + std::cout << result + "]"; } diff --git a/01_week/tasks/length_lit/length_lit.cpp b/01_week/tasks/length_lit/length_lit.cpp index e69de29b..df5d5ecc 100644 --- a/01_week/tasks/length_lit/length_lit.cpp +++ b/01_week/tasks/length_lit/length_lit.cpp @@ -0,0 +1,47 @@ +constexpr double operator""_m_to_cm(long double meters){ + return meters * 100; +} + +constexpr double operator""_cm_to_m(long double centimeter){ + return centimeter / 100.0; +} + +constexpr double operator""_ft_to_m(long double feets){ + return feets * 0.3048; +} + +constexpr double operator""_ft_to_cm(long double feets){ + return operator""_m_to_cm(operator""_ft_to_m(feets)); +} + +constexpr double operator""_ft_to_in(long double feets){ + return feets * 12.0; +} + +constexpr double operator""_in_to_m(long double inches){ + return inches * 0.0254; +} + +constexpr double operator""_in_to_cm(long double inches){ + return operator""_m_to_cm(operator""_in_to_m(inches)); +} + +constexpr double operator""_in_to_ft(long double inches){ + return inches / 12.0; +} + +constexpr double operator""_m_to_ft(long double meters){ + return meters * 3.280839895; +} + +constexpr double operator""_m_to_in(long double meters){ + return meters * 39.37007874; +} + +constexpr double operator""_cm_to_ft(long double centimeters){ + return operator""_cm_to_m(operator""_m_to_ft(centimeters)); +} + +constexpr double operator""_cm_to_in(long double centimeters){ + return operator""_cm_to_m(operator""_m_to_in(centimeters)); +} \ 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..a9aa4cec 100644 --- a/01_week/tasks/print_bits/print_bits.cpp +++ b/01_week/tasks/print_bits/print_bits.cpp @@ -1,7 +1,21 @@ #include #include +#include void PrintBits(long long value, size_t bytes) { - throw std::runtime_error{"Not implemented"}; + std::string result = "0b"; + size_t total_bits = bytes * 8; + long long mask = 0LL; + // Тут надо int, иначе условие бесконечное, потому что будет + // происходит переполнение счетчика + for (int i = total_bits - 1; i >= 0; --i) { + mask = 1LL << i; + + if (value & mask) result += '1'; + else result += '0'; + + if (i % 4 == 0 && i != 0) result += '\''; + } + std::cout << result << "\n"; } diff --git a/01_week/tasks/quadratic/quadratic.cpp b/01_week/tasks/quadratic/quadratic.cpp index abf7d632..500101f4 100644 --- a/01_week/tasks/quadratic/quadratic.cpp +++ b/01_week/tasks/quadratic/quadratic.cpp @@ -1,6 +1,64 @@ #include +#include +#include +#include +bool isLevelLine(int a, int b){ + if (a == 0 && b == 0) return true; + else return false; + +} + +bool isLinear(int a, int b){ + if (a == 0 && b != 0) return true; + else return false; + +} + +bool isQuadratic(int a){ + if (a != 0) return true; + else return false; + +} + +std::string AddRootToStr(double x){ + std::ostringstream oss; + oss << std::setprecision(6); + if (std::abs(x - std::round(x)) < 1e-10) { + oss << static_cast(std::round(x)); + } else { + oss << x; + } + return oss.str(); +} void SolveQuadratic(int a, int b, int c) { - throw std::runtime_error{"Not implemented"}; + std::string result = ""; + if (isLevelLine(a, b)){ + if (c == 0) result = "infinite solutions"; + else result = "no solutions"; + } + else if (isLinear(a, b)){ + double x = -static_cast(c) / b; + result = AddRootToStr(x); + } + else if (isQuadratic(a)){ + double discr = b * b - 4 * a * c; + if (discr < 0) { + result = "no solutions"; + } + else if (std::abs(discr) < 1e-10) { + double x = -b / (2.0 * a); + result = AddRootToStr(x); + } + else { + double x1 = (-b + sqrt(discr)) / (2.0 * a); + double x2 = (-b - sqrt(discr)) / (2.0 * a); + + if (x1 > x2) std::swap(x1, x2); + result = AddRootToStr(x1) + " " + AddRootToStr(x2); + } + } + + std::cout << result; } \ No newline at end of file diff --git a/01_week/tasks/rms/rms.cpp b/01_week/tasks/rms/rms.cpp index 6882f0a9..d81e9401 100644 --- a/01_week/tasks/rms/rms.cpp +++ b/01_week/tasks/rms/rms.cpp @@ -1,7 +1,12 @@ -#include -#include +#include +#include double CalculateRMS(double values[], size_t size) { - throw std::runtime_error{"Not implemented"}; + double res = 0.0; + if (values == nullptr || size == 0) return res; + for (size_t i=0; i < size; ++i){ + res += values[i] * values[i]; + } + return std::sqrt(res / size); } \ 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..83eb5efe 100644 --- a/02_week/tasks/func_array/func_array.cpp +++ b/02_week/tasks/func_array/func_array.cpp @@ -1,6 +1,14 @@ #include -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 func_count) { + double result = 0.0; + const double& a_ref = a; + const double& b_ref = b; + for (size_t i=0; i -/* 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)) { + const int* result = end; + if ((begin == nullptr) || (end==nullptr) || (predicate == nullptr) || (begin > end)){ + result = end; + return result; + } + + for (; begin != end; ++begin){ + const int elem = *begin; + if (predicate(elem)){ + result = begin; + } + } + + return result; } \ 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..b9fd1db5 100644 --- a/02_week/tasks/little_big/little_big.cpp +++ b/02_week/tasks/little_big/little_big.cpp @@ -1,10 +1,28 @@ #include +#include +#include +#include +void PrintingFunc(unsigned char* byte_ptr, size_t bytes, bool shouldInverse){ + std::ostringstream oss; + oss << "0x"; + + for (size_t i = 0; i < bytes; ++i) { + size_t index = shouldInverse ? (bytes - 1 - i) : i; + oss << std::hex << std::uppercase << std::setw(2) << std::setfill('0') + << static_cast(byte_ptr[index]); + } + + oss << "\n"; + std::cout << oss.str(); +} -void PrintMemory(int /* write arguments here */) { - throw std::runtime_error{"Not implemented"}; +void PrintMemory(int number, bool shouldInverse=false) { + unsigned char* byte_ptr = reinterpret_cast(&number); + PrintingFunc(byte_ptr, 4, shouldInverse); } -void PrintMemory(double /* write arguments here */) { - throw std::runtime_error{"Not implemented"}; +void PrintMemory(double number, bool shouldInverse=false) { + unsigned char* byte_ptr = reinterpret_cast(&number); + PrintingFunc(byte_ptr, 8, shouldInverse); } \ No newline at end of file diff --git a/02_week/tasks/longest/longest.cpp b/02_week/tasks/longest/longest.cpp index 04b3c354..03845f02 100644 --- a/02_week/tasks/longest/longest.cpp +++ b/02_week/tasks/longest/longest.cpp @@ -1,6 +1,37 @@ #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, size_t& count) { + const char* start_of_longest_seq = nullptr; + count = 0; + size_t this_seq_count = 0; + + if ((begin == nullptr) || (end==nullptr) || (begin > end)){ + return start_of_longest_seq; + } + + const char* next_el = nullptr; + for (; begin != end;){ + this_seq_count = 1; + if (begin < end - 1){ + next_el = begin + 1; + for (; next_el != end; ++next_el){ + if (*next_el != *begin) break; + ++this_seq_count; + } + } + + if (this_seq_count > count){ + count = this_seq_count; + start_of_longest_seq = begin; + } + begin += this_seq_count; + } + + return start_of_longest_seq; } + +char* FindLongestSubsequence(char* begin, char* end, size_t& count){ + const char* const_result = FindLongestSubsequence(const_cast(begin), const_cast(end), count); + return const_cast(const_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..1871520f 100644 --- a/02_week/tasks/pretty_array/pretty_array.cpp +++ b/02_week/tasks/pretty_array/pretty_array.cpp @@ -1,6 +1,33 @@ #include -void PrintArray(/* write arguments here */) { - throw std::runtime_error{"Not implemented"}; -} \ No newline at end of file +void PrintArray(const int* start, const int* end, size_t limit = 0) { + std::string result = "["; + size_t counter = 0; + + if ((start!=nullptr) && (end!=nullptr)){ + bool startToEnd = end > start; + const int* last_el_ptr = startToEnd ? end - 1 : end + 1; + for (; start!=end; startToEnd ? ++start : --start){ + ++counter; + result += std::to_string(*start); + if (start == last_el_ptr){ + // Последний элемент + continue; + } + else if ((limit != 0) && counter == limit) + { + // Переход на новую строку + counter = 0; + result += ", ...\n "; + } + else { + // Просто некоторый элемент + result += ", "; + } + } + } + + result += "]\n"; + std::cout << result; +} diff --git a/02_week/tasks/swap_ptr/swap_ptr.cpp b/02_week/tasks/swap_ptr/swap_ptr.cpp index 93db625d..d14c2e86 100644 --- a/02_week/tasks/swap_ptr/swap_ptr.cpp +++ b/02_week/tasks/swap_ptr/swap_ptr.cpp @@ -1,6 +1,9 @@ #include - -void SwapPtr(/* write arguments here */) { - throw std::runtime_error{"Not implemented"}; -} \ No newline at end of file +template +// Сделаем через generic, главное чтобы приходил какой-то указатель +void SwapPtr(T*& ptr1, T*& ptr2) { + T* temp = ptr1; + ptr1 = ptr2; + ptr2 = temp; +} diff --git a/03_week/tasks/data_stats/data_stats.cpp b/03_week/tasks/data_stats/data_stats.cpp index b941c211..c0c25d2d 100644 --- a/03_week/tasks/data_stats/data_stats.cpp +++ b/03_week/tasks/data_stats/data_stats.cpp @@ -1,4 +1,6 @@ #include +#include +#include struct DataStats { @@ -6,6 +8,17 @@ struct DataStats { double sd = 0.0; }; -/* return_type */ CalculateDataStats(/* args */) { - throw std::runtime_error{"Not implemented"}; +DataStats CalculateDataStats(std::vector vector) { + double avg = 0.0; + double sko = 0.0; + size_t size_of_v = vector.size(); + for (int num : vector){ + avg += num; + } + avg = size_of_v > 0 ? avg/size_of_v : 0.0; + for (int num : vector){ + sko += (num-avg)*(num-avg); + } + sko = size_of_v > 0 ? sqrt(sko / size_of_v) : 0.0; + return DataStats{avg, sko}; } diff --git a/03_week/tasks/easy_compare/easy_compare.cpp b/03_week/tasks/easy_compare/easy_compare.cpp index dd5cb7f6..e9a13b99 100644 --- a/03_week/tasks/easy_compare/easy_compare.cpp +++ b/03_week/tasks/easy_compare/easy_compare.cpp @@ -1,16 +1,64 @@ #include - struct Date { - unsigned year; - unsigned month; - unsigned day; + unsigned year = 0u; + unsigned month = 0u; + unsigned day = 0u; + + bool operator== (const Date& other) const { + return std::tie(year, month, day) == std::tie(other.year, other.month, other.day); + } + + bool operator< (const Date& other) const { + return std::tie(year, month, day) < std::tie(other.year, other.month, other.day); + } + + bool operator!= (const Date& other) const { + return !(*this==other); + } + + bool operator<= (const Date& other) const { + return (*this (const Date& other) const { + return !(*this<=other); + } + + bool operator>= (const Date& other) const { + return !(*this < other); + } }; struct StudentInfo { - size_t id; - char mark; - int score; - unsigned course; - Date birth_date; + size_t id = 0; + char mark = 'A'; + int score = 0; + unsigned course = 1u; + Date birth_date{}; + + bool operator== (const StudentInfo& other) const { + return std::tie(mark, score) == std::tie(other.mark, other.score); + } + + bool operator< (const StudentInfo& other) const { + if (this->mark == other.mark){} + else{ + return +this->mark > +other.mark; + } + if (this->score == other.score){} + else{ + return this->score < other.score; + } + if (this->course == other.course){} + else{ + return this->course > other.course; + } + if (this->birth_date == other.birth_date){return false;} + else{ + return this->birth_date < other.birth_date; + } + + } + }; \ No newline at end of file diff --git a/03_week/tasks/enum_operators/enum_operators.cpp b/03_week/tasks/enum_operators/enum_operators.cpp index a539be38..d4ad5cde 100644 --- a/03_week/tasks/enum_operators/enum_operators.cpp +++ b/03_week/tasks/enum_operators/enum_operators.cpp @@ -1,5 +1,7 @@ #include #include +#include +#include enum class CheckFlags : uint8_t { NONE = 0, @@ -12,22 +14,56 @@ enum class CheckFlags : uint8_t { ALL = TIME | DATE | USER | CERT | KEYS | DEST }; -/* return_type */ operator|(/* args */) { - throw std::runtime_error{"Not implemented"}; +CheckFlags operator|(const CheckFlags& lhs, const CheckFlags& rhs) { + return static_cast( + (static_cast(lhs) | static_cast(rhs)) & 0x3F // Оставим только шесть бит + ); } -/* return_type */ operator&(/* args */) { - throw std::runtime_error{"Not implemented"}; +bool operator&(const CheckFlags& lhs, const CheckFlags& rhs) { + uint8_t lhs_int = static_cast(lhs) & 0x3F; + uint8_t rhs_int = static_cast(rhs) & 0x3F; + if (lhs_int == 0u || rhs_int == 0u) return false; + return ((lhs_int & rhs_int) == lhs_int || (lhs_int & rhs_int) == rhs_int); } -/* return_type */ operator^(/* args */) { - throw std::runtime_error{"Not implemented"}; +CheckFlags operator^(const CheckFlags& lhs, const CheckFlags& rhs) { + return static_cast( + (static_cast(lhs) ^ static_cast(rhs)) & 0x3F // Оставим только шесть бит + ); } -/* return_type */ operator~(/* args */) { - throw std::runtime_error{"Not implemented"}; +CheckFlags operator~(const CheckFlags& flags) { + return static_cast( + (~static_cast(flags)) & 0x3F + ); } -/* return_type */ operator<<(/* args */) { - throw std::runtime_error{"Not implemented"}; +std::ostream& operator<<(std::ostream& os, CheckFlags flags) { + flags = static_cast(static_cast(flags) & 0x3F); + if (flags == CheckFlags::NONE) { + os << "NONE"; + return os; + } + + + const std::pair flag_infos[] = { + {CheckFlags::TIME, "TIME"}, + {CheckFlags::DATE, "DATE"}, + {CheckFlags::USER, "USER"}, + {CheckFlags::CERT, "CERT"}, + {CheckFlags::KEYS, "KEYS"}, + {CheckFlags::DEST, "DEST"} + }; + + bool isFirst = true; + for (const auto& info : flag_infos) { + if (static_cast(flags & info.first) != 0) { + if (!isFirst) os << ", "; + os << info.second; + isFirst = false; + } + } + + return os; } diff --git a/03_week/tasks/filter/filter.cpp b/03_week/tasks/filter/filter.cpp index 6648cb39..491bdaad 100644 --- a/03_week/tasks/filter/filter.cpp +++ b/03_week/tasks/filter/filter.cpp @@ -1,6 +1,18 @@ #include +#include - -/* return_type */ Filter(/* args */) { - throw std::runtime_error{"Not implemented"}; +void Filter(std::vector& vector, bool (*func)(int)) { + size_t index_good = 0; + + for (size_t i = 0; i < vector.size(); ++i) { + if ((func) && (!func(vector[i]))) { + continue; + } + else { + vector[index_good] = vector[i]; + ++index_good; + } + } + + vector.resize(index_good); } \ No newline at end of file diff --git a/03_week/tasks/find_all/find_all.cpp b/03_week/tasks/find_all/find_all.cpp index 74f393b2..763038b4 100644 --- a/03_week/tasks/find_all/find_all.cpp +++ b/03_week/tasks/find_all/find_all.cpp @@ -1,6 +1,20 @@ #include +#include +std::vector FindAll(const std::vector& vector, bool (*func)(int)) { + if (!func) return {}; -/* return_type */ FindAll(/* args */) { - throw std::runtime_error{"Not implemented"}; + size_t count = 0; + for (int value : vector) { + if (func(value)) ++count; + } + + std::vector positions; + positions.reserve(count); + + for (size_t i = 0; i < vector.size(); ++i) { + if (func(vector[i])) positions.push_back(i); + } + + return positions; } \ No newline at end of file diff --git a/03_week/tasks/minmax/minmax.cpp b/03_week/tasks/minmax/minmax.cpp index c2869799..c4174431 100644 --- a/03_week/tasks/minmax/minmax.cpp +++ b/03_week/tasks/minmax/minmax.cpp @@ -1,6 +1,17 @@ #include +#include -/* return_type */ MinMax(/* args */) { - throw std::runtime_error{"Not implemented"}; +std::pair::const_iterator, std::vector::const_iterator> MinMax(const std::vector& vector) { + auto min_iter = vector.begin(); + auto max_iter = vector.begin(); + + if (vector.empty()) return {vector.end(), vector.end()}; + + for (auto iterator = vector.begin(); iterator != vector.end(); ++iterator){ + if (*iterator < *min_iter) min_iter = iterator; + if (*iterator >= *max_iter) max_iter = iterator; + } + + return {min_iter, max_iter}; } diff --git a/03_week/tasks/os_overload/os_overload.cpp b/03_week/tasks/os_overload/os_overload.cpp index e473418d..3ac5864e 100644 --- a/03_week/tasks/os_overload/os_overload.cpp +++ b/03_week/tasks/os_overload/os_overload.cpp @@ -1,21 +1,59 @@ #include #include #include +#include struct Coord2D { - int x; - int y; + int x=0; + int y=0; + + Coord2D() = default;; + Coord2D(int x_in, int y_in): x(x_in), y(y_in){}; }; struct Circle { - Coord2D coord; - unsigned radius; + Coord2D coord{}; + unsigned radius = 1u; + + Circle() = default; + Circle(Coord2D c, unsigned r=1u): coord(c), radius(r){}; }; using CircleRegion = std::pair; using CircleRegionList = std::vector; -/* return_type */ operator<<(/* args */) { - throw std::runtime_error{"Not implemented"}; +std::ostream& operator << (std::ostream& os, const Coord2D& coordination){ + os << "(" << coordination.x << ", " << coordination.y << ")"; + return os; +} + +std::ostream& operator << (std::ostream& os, Circle circle){ + os << "circle["; + if (circle.radius == 0u) { + os <<"]"; + } + else { + os << circle.coord << ", r = " << circle.radius << "]"; + } + return os; +} + +std::ostream& operator << (std::ostream& os, CircleRegion circRegion){ + circRegion.second ? os << "+" : os << "-"; + os << circRegion.first; + return os; +} + +std::ostream& operator << (std::ostream& os, CircleRegionList circRegionVector){ + os << "{"; + + for (auto circRegion = circRegionVector.begin(); circRegion != circRegionVector.end(); ++circRegion){ + if (circRegion == circRegionVector.begin()) os << "\n"; + os << "\t" << *circRegion; + if (circRegion != circRegionVector.end() - 1) os << ","; + os << "\n"; + } + os << "}"; + return os; } diff --git a/03_week/tasks/range/range.cpp b/03_week/tasks/range/range.cpp index d2085495..ebfb8e54 100644 --- a/03_week/tasks/range/range.cpp +++ b/03_week/tasks/range/range.cpp @@ -2,6 +2,20 @@ #include -std::vector Range(int from, int to, int step) { - throw std::runtime_error{"Not implemented"}; +std::vector Range(int from, int to, int step=1) { + + std::vector result; + + if ((step == 0) || (from > to && step>0) || (from < to && step<0)) return result; + + size_t size_of_result = step > 0 ? (to - from + step - 1) / step : (from - to - step - 1) / (-step); + result.resize(size_of_result); + size_t cur_idx = 0; + + for (int i=from; step>0 ? i < to : i > to; i+=step){ + result[cur_idx] = i; + ++cur_idx; + } + + return result; } diff --git a/03_week/tasks/unique/unique.cpp b/03_week/tasks/unique/unique.cpp index 9d2545bb..336a6f4c 100644 --- a/03_week/tasks/unique/unique.cpp +++ b/03_week/tasks/unique/unique.cpp @@ -1,6 +1,38 @@ #include #include -/* return_type */ Unique(/* args */) { - throw std::runtime_error{"Not implemented"}; +std::vector Unique(const std::vector & vector) { + + std::vector result; + std::vector::const_iterator cur_iter = vector.begin(); + + if (vector.empty()) return result; + + size_t count = 1; + + for (auto iter = vector.begin(); iter != vector.end();){ + + cur_iter = iter; + ++iter; + + while (iter != vector.end()) { + if (*iter != *cur_iter) {++count; break;} + else ++iter; + } + } + + result.reserve(count); + + for (auto iter = vector.begin(); iter != vector.end();){ + + result.push_back(*iter); + cur_iter = iter; + ++iter; + + while (iter != vector.end() && *iter == *cur_iter) { + ++iter; + } + } + + return result; } diff --git a/04_week/tasks/phasor/phasor.cpp b/04_week/tasks/phasor/phasor.cpp index 3ec1b9ad..fc4f892c 100644 --- a/04_week/tasks/phasor/phasor.cpp +++ b/04_week/tasks/phasor/phasor.cpp @@ -1,10 +1,200 @@ - +# include +#include +#include struct ExpTag {}; struct DegTag {}; struct AlgTag {}; +class Phasor; +Phasor operator/(const Phasor& lhs, const Phasor& rhs); + class Phasor { + public: + Phasor() = default; + + Phasor(double ampl, double angle){ + SetPolar(ampl, angle); + } + + Phasor(double ampl, double angle, ExpTag tag){ + (void)tag; + SetPolar(ampl, angle); + } + + Phasor(double ampl, double angleDeg, DegTag tag){ + (void)tag; + SetPolar(ampl, angleDeg * M_PI / 180); + } + + Phasor(double real, double imag, AlgTag tag){ + (void)tag; + SetCartesian(real, imag); + } + + void SetPolar(double ampl, double angle){ + real_ = ampl * cos(angle); + imag_ = ampl * sin(angle); + } + + void SetCartesian(double real, double imag){ + real_ = real; + imag_ = imag; + } + + double Magnitude() const { + return sqrt(real_ * real_ + imag_ * imag_); + } + + double Phase() const { + return atan2(imag_, real_); + } + + double PhaseDeg() const { + double angle_deg = Phase() * 180 / M_PI; + if (fabs(angle_deg + 180.0) < 1e-12) { + return 180.0; + } + return angle_deg; + } + + double Real() const { + return real_; + } + + double Imag() const { + return imag_; + } + + double Abs() const { + return Magnitude(); + } + + double Angle() const { + return Phase(); + } + + double AngleDeg() const { + return PhaseDeg(); + } + + Phasor Conj() const{ + return Phasor(real_, -imag_, AlgTag{}); + } + + Phasor Inv() const{ + return Phasor(1, 0, AlgTag{}) / *this; + } + + protected: + double real_ = 0.0; + double imag_ = 0.0; }; + +Phasor operator-(const Phasor& phasor){ + return Phasor(-phasor.Real(), -phasor.Imag(), AlgTag{}); +} + +Phasor operator+(const Phasor& lhs, const Phasor& rhs){ + return Phasor(lhs.Real() + rhs.Real(), lhs.Imag() + rhs.Imag(), AlgTag{}); +} + +Phasor operator+(const Phasor& lhs, const double rhs) { + return Phasor(lhs.Real() + rhs, lhs.Imag(), AlgTag{}); +} + +Phasor operator+(const double lhs, const Phasor& rhs) { + return rhs + lhs; +} + +Phasor operator-(const Phasor& lhs, const Phasor& rhs){ + return lhs + (-rhs); +} + +Phasor operator-(const Phasor& lhs, const double rhs) { + return Phasor(lhs.Real() - rhs, lhs.Imag(), AlgTag{}); +} + +Phasor operator-(const double lhs, const Phasor& rhs) { + return Phasor(lhs - rhs.Real(), -rhs.Imag(), AlgTag{}); +} + +Phasor operator*(const Phasor& lhs, const Phasor& rhs){ + double real = lhs.Real() * rhs.Real() - lhs.Imag() * rhs.Imag(); + double imag = lhs.Real() * rhs.Imag() + lhs.Imag() * rhs.Real(); + return Phasor(real, imag, AlgTag{}); +} + +Phasor operator*(const Phasor& lhs, const double rhs) { + return Phasor(lhs.Real() * rhs, lhs.Imag() * rhs, AlgTag{}); +} + +Phasor operator*(const double lhs, const Phasor& rhs) { + return rhs * lhs; +} + +Phasor operator/(const Phasor& lhs, const Phasor& rhs){ + + double real = (lhs.Real() * rhs.Real() + lhs.Imag() * rhs.Imag()) / pow(rhs.Magnitude(), 2); + double imag = (-lhs.Real() * rhs.Imag() + lhs.Imag() * rhs.Real()) / pow(rhs.Magnitude(), 2); + return Phasor(real, imag, AlgTag{}); +} + +Phasor operator/(const Phasor& lhs, const double rhs) { + return Phasor(lhs.Real() / rhs, lhs.Imag() / rhs, AlgTag{}); +} + +Phasor operator/(const double lhs, const Phasor& rhs) { + return Phasor(lhs, 0, AlgTag{}) / rhs; +} + +Phasor& operator+=(Phasor& lhs, const Phasor& rhs) { + lhs.SetCartesian(lhs.Real() + rhs.Real(), lhs.Imag() + rhs.Imag()); + return lhs; +} + +Phasor& operator-=(Phasor& lhs, const Phasor& rhs) { + lhs.SetCartesian(lhs.Real() - rhs.Real(), lhs.Imag() - rhs.Imag()); + return lhs; +} + +Phasor& operator*=(Phasor& lhs, const Phasor& rhs) { + lhs.SetCartesian(lhs.Real() * rhs.Real() - lhs.Imag() * rhs.Imag(), + lhs.Real() * rhs.Imag() + lhs.Imag() * rhs.Real()); + return lhs; +} + +Phasor& operator/=(Phasor& lhs, const Phasor& rhs) { + lhs.SetCartesian((lhs.Real() * rhs.Real() + lhs.Imag() * rhs.Imag()) / pow(rhs.Magnitude(), 2), + (lhs.Imag() * rhs.Real() - lhs.Real() * rhs.Imag()) / pow(rhs.Magnitude(), 2)); + return lhs; +} + +bool operator==(const Phasor& lhs, const Phasor& rhs){ + return fabs(lhs.Real() - rhs.Real()) < 1e-9 && fabs(lhs.Imag() - rhs.Imag()) < 1e-9; +} + +bool operator!=(const Phasor& lhs, const Phasor& rhs){ + return !(lhs == rhs); +} + +std::ostream& operator << (std::ostream& os, const Phasor& phasor){ + os << std::fixed << std::setprecision(3) << phasor.Magnitude() << "*e(j*" << phasor.AngleDeg() << ") [" <<\ + phasor.Real() << " + j*" << phasor.Imag() << "]"; + return os; +} + + +Phasor MakePhasorCartesian(double real, double imag){ + return Phasor(real, imag, AlgTag{}); +} + +Phasor MakePhasorPolar(double ampl, double angle){ + return Phasor(ampl, angle, ExpTag{}); +} + +Phasor MakePhasorPolarDeg(double ampl, double angle){ + return Phasor(ampl, angle, DegTag{}); +} \ No newline at end of file diff --git a/04_week/tasks/queue/queue.cpp b/04_week/tasks/queue/queue.cpp index 2a9f8493..47983e29 100644 --- a/04_week/tasks/queue/queue.cpp +++ b/04_week/tasks/queue/queue.cpp @@ -1,6 +1,180 @@ #include +#include +#include +#include class Queue { + public: + Queue() = default; + Queue(int size){ + in_.reserve(size); + } + Queue(std::vector vector){ + in_ = vector; + } + Queue(std::stack stack){ + in_.reserve(stack.size()); + std::vector temp; + while (!stack.empty()) { + temp.push_back(stack.top()); + stack.pop(); + } + + std::reverse(temp.begin(), temp.end()); + in_ = temp; + + } + + Queue(std::initializer_list initList) { + in_.reserve(initList.size()); + for (int val : initList) { + in_.push_back(val); + } + } + + void Push(int in_num){ + in_.push_back(in_num); + } + + bool Pop(){ + if (Empty()) return false; + if (out_.empty()) In_to_out(); + out_.pop_back(); + return true; + } + + bool Empty() const{ + return in_.empty() && out_.empty(); + } + + size_t Size() const{ + return in_.size() + out_.size(); + } + + void Clear(){ + in_.clear(); + out_.clear(); + in_.shrink_to_fit(); + out_.shrink_to_fit(); + } + + void Swap(Queue& other){ + std::swap(in_, other.in_); + std::swap(out_, other.out_); + + } + + int& Front(){ + if (Empty()) { + // UB + return out_.back(); + } + + if (out_.empty()) { + In_to_out(); + } + + return out_.back(); + } + + int& Back(){ + if (Empty()) { + // UB + return out_.front(); + } + + if (!in_.empty()) { + // Если есть что-то в первом списке + return in_.back(); + } + else { + // Если есть нет, то с конца последнего + return out_.front(); + } + } + + const int& Front() const { + if (Empty()) { + return out_.back(); + } + + + if (out_.empty()) { + Queue temp = *this; + temp.In_to_out(); + return temp.out_.back(); + } + + return out_.back(); + } + + const int& Back() const { + if (Empty()) { + return in_.back(); + } + + if (!in_.empty()) { + return in_.back(); + } + else { + return out_[0]; + } + } + + bool operator==(const Queue& other) const{ + + if (Size() != other.Size()){ + return false; + } + if (Empty()){ + if (other.Empty()){ + return true; + } + return false; + } + Queue one = *this; + Queue two = other; + + one.In_to_out(); + two.In_to_out(); + + for (size_t i = 0; i!= Size(); ++i){ + if (one.out_[i] != two.out_[i]){ + return false; + } + } + return true; + } + + bool operator!=(const Queue& other) const{ + return ! (*this == other); + } + + protected: + std:: vector in_{}; + std:: vector out_{}; + + void In_to_out(){ + if (in_.empty()) { + return; + } + std::vector new_out; + new_out.reserve(out_.size() + in_.size()); + + for (auto it = in_.rbegin(); it != in_.rend(); ++it) { + new_out.push_back(*it); + } + + for (auto it = out_.begin(); it != out_.end(); ++it) { + new_out.push_back(*it); + } + + out_.swap(new_out); + in_.clear(); + in_.shrink_to_fit(); + } }; + + diff --git a/04_week/tasks/ring_buffer/ring_buffer.cpp b/04_week/tasks/ring_buffer/ring_buffer.cpp index e2b57ba2..a29264eb 100644 --- a/04_week/tasks/ring_buffer/ring_buffer.cpp +++ b/04_week/tasks/ring_buffer/ring_buffer.cpp @@ -1,6 +1,177 @@ #include +#include class RingBuffer { + public: + RingBuffer(size_t size) { + size_ = size > 0 ? size : 1; + data_.resize(size_); + counter_ = 0; + pos_for_next_ = 0; + oldest_ = 0; + } + RingBuffer(size_t size, int init_val) : RingBuffer(size) { + for (std::vector::iterator iter = data_.begin(); iter!=data_.end(); ++iter){ + *iter = init_val; + } + pos_for_next_ = 0; + counter_ = size > 0 ? size : 1; + } + RingBuffer(std::initializer_list initList) : RingBuffer(initList.size()) { + data_.assign(initList.begin(), initList.end()); + pos_for_next_ = 0; + counter_ = initList.size(); + } + void Push(int val) { + data_[pos_for_next_] = val; + Increase_pos(pos_for_next_); + if (counter_ == size_) { + Increase_pos(oldest_); + return; + } + ++counter_; + } + bool TryPush(int val) { + if (counter_ == size_) { + return false; + } + Push(val); + return true; + } + void Pop() { + if (counter_ == 0) { + return; + } + Increase_pos(oldest_); + --counter_; + } + bool TryPop(int& buffer) { + if (counter_ == 0) { + return false; + } + buffer = data_[oldest_]; + Pop(); + return true; + } + + int& operator[](size_t index) { + size_t actual_index = (oldest_ + index) % size_; + return data_[actual_index]; + } + + const int& operator[](size_t index) const { + size_t actual_index = (oldest_ + index) % size_; + return data_[actual_index]; + } + + int& Front() { + if (counter_ == 0){ + return *data_.begin(); + } + size_t temp = pos_for_next_; + Decrease_pos(temp); + return data_[temp]; + } + + int& Back() { + if (counter_ == 0){ + return *data_.begin(); + } + return data_[oldest_]; + } + + bool Empty(){ + return (counter_ == 0); + } + + bool Full(){ + return (counter_ == size_); + } + + size_t Size(){ + return counter_; + } + + size_t Capacity(){ + return size_; + } + + void Clear(){ + counter_ = 0; + oldest_ = 0; + pos_for_next_ = 0; + } + + std::vector Vector() { + std::vector result; + result.reserve(counter_); + size_t temp_oldest = oldest_; + for (size_t i = 0; i != counter_; ++i){ + result.push_back(data_[temp_oldest]); + Increase_pos(temp_oldest); + } + return result; + } + + void Resize(size_t new_size){ + std::vector new_data; + new_size = new_size > 0 ? new_size : 1; + new_data.resize(new_size); + size_t new_counter = 0; + size_t start_pos = 0; + + // Copying + if (new_size > size_) { + start_pos = oldest_; + } + else if (counter_ > new_size) { + start_pos = pos_for_next_; + for (size_t i = 0; i != new_size; ++i){ + Decrease_pos(start_pos); + } + } + else { + start_pos = 0; + } + for (size_t i = start_pos; new_counter != std::min(new_size, counter_); Increase_pos(i)){ + new_data[new_counter] = data_[i]; + ++new_counter; + } + + // Other data + if (new_size > size_) { + pos_for_next_ = new_counter; + } + else { + pos_for_next_ = 0; + oldest_ = 0; + } + size_ = new_size; + data_ = new_data; + counter_ = new_counter; + } + + protected: + std::vector data_; + size_t size_; + size_t pos_for_next_; + size_t oldest_; + size_t counter_; + + void Increase_pos(size_t& pos) { + if (pos == size_ - 1) { + pos = 0; + return; + } + ++pos; + } + void Decrease_pos(size_t& pos) { + if (pos == 0) { + pos = size_ - 1; + return; + } + --pos; + } }; diff --git a/04_week/tasks/stack/stack.cpp b/04_week/tasks/stack/stack.cpp index 222e4ffc..98064275 100644 --- a/04_week/tasks/stack/stack.cpp +++ b/04_week/tasks/stack/stack.cpp @@ -2,5 +2,56 @@ class Stack { + public: + void Push(int num) { + data_.push_back(num); + } + bool Pop() { + if (data_.empty()) return false; + data_.pop_back(); + return true; + } + const int& Top() const { + if (data_.empty()){ + return *data_.begin(); + } + return data_[data_.size()-1]; + } + int& Top() { + if (data_.empty()){ + return *data_.begin(); + } + return data_[data_.size()-1]; + } + bool Empty() const{ + return data_.empty(); + } + size_t Size() const{ + return data_.size(); + } + void Clear(){ + data_.clear(); + } + void Swap(Stack& other){ + std::swap(this->data_, other.data_); + } + bool operator==(const Stack& other) const{ + if (Empty() && other.Empty()){ + return true; + } + if (Size() != other.Size()){ + return false; + } + for (size_t i=0; i!=Size(); ++i){ + if (data_[i] != other.data_[i]) return false; + } + return true; + } + bool operator!=(const Stack& other) const{ + return ! (*this==other); + } + + private: + std::vector data_{}; };