-
Notifications
You must be signed in to change notification settings - Fork 0
Домашняя работа 2 Cpp (Матричный калькулятор) #1
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?
Changes from all commits
9384bfc
adc7072
d2f9e43
6f434b3
4c184d2
9360115
466b687
e7ee27e
7a1bcb1
87e2693
2348a0f
468a1ee
6120b26
c6adc9b
ed016ec
7d24242
daa02ba
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,39 @@ | ||
| on: push | ||
|
|
||
| env: | ||
| LIB_NAME: matrix_lib | ||
|
|
||
| jobs: | ||
| build: | ||
| runs-on: ubuntu-latest | ||
| container: leshiy1295/gcc_linters_valgrind_cmake_gtest | ||
|
Collaborator
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. =) |
||
| steps: | ||
| - uses: actions/checkout@v2 | ||
| - run: make build | ||
| - name: Upload artifacts | ||
| uses: actions/upload-artifact@v2 | ||
| with: | ||
| name: executable_file | ||
| path: build/main | ||
| test: | ||
| runs-on: ubuntu-latest | ||
| container: leshiy1295/gcc_linters_valgrind_cmake_gtest | ||
| needs: [build] | ||
| steps: | ||
| - uses: actions/checkout@v2 | ||
| - name: install lcov | ||
| run: apt-get install lcov -y | ||
| - name: Build, run and test | ||
| run: | | ||
| make build TEST_OPT=ON | ||
| make run | ||
| make test | ||
| - name: Test coverage | ||
| run: make coverage | ||
| - name: Upload artifacts | ||
| uses: actions/upload-artifact@v2 | ||
| with: | ||
| name: coverage-info | ||
| path: build/report | ||
| - name: launch valgrind | ||
| run: make valgrind_tests | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| /build | ||
| _test.cpp | ||
| main | ||
| /.vscode |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| cmake_minimum_required(VERSION 3.0.0) | ||
| project(main) | ||
|
|
||
| set(CMAKE_CXX_STANDARD 17) | ||
|
|
||
| option(TEST_OPT "build test version" OFF) | ||
| option(DEBUG_OPT "build debug version" OFF) | ||
|
|
||
| add_subdirectory(matrix_lib) | ||
|
|
||
| add_executable(${PROJECT_NAME} main.cpp) | ||
|
|
||
| if(TEST_OPT) | ||
| set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -coverage -lgcov" ) | ||
| endif() | ||
|
|
||
| if(DEBUG_OPT) | ||
| set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -O0") | ||
| endif() | ||
|
|
||
|
|
||
| target_include_directories(${PROJECT_NAME} PUBLIC ${MATRIX_LIB_INCLUDE_DIRS}) | ||
| target_link_libraries(${PROJECT_NAME} PRIVATE ${MATRIX_LIB_LIBRARIES}) | ||
|
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| LIB_DIR = matrix_lib | ||
| BUILD_DIR = build | ||
|
|
||
| TARGET = ./${BUILD_DIR}/main | ||
| TESTS_EXE = tests | ||
| TESTS_DIR = tests | ||
|
|
||
| TEST_OPT = OFF | ||
| DEBUG_OPT = OFF | ||
|
|
||
| .PHONY: build rebuild test run | ||
|
|
||
| build: clean | ||
| mkdir ${BUILD_DIR} | ||
| cd ${BUILD_DIR} && cmake .. -DTEST_OPT=${TEST_OPT} -DDEBUG_OPT=${DEBUG_OPT} && $(MAKE) --no-print-directory | ||
|
|
||
| clean: | ||
| (rm -r ${BUILD_DIR} 2>/dev/null) || exit 0 | ||
|
|
||
| run: | ||
| cd ${BUILD_DIR} && $(MAKE) --no-print-directory | ||
| ${TARGET} | ||
|
|
||
| test: | ||
| ./${BUILD_DIR}/${LIB_DIR}/tests/tests | ||
|
|
||
| coverage: | ||
| cd ${BUILD_DIR} && lcov -t "testing_${LIB_DIR}" -o coverage.info -c -d ${LIB_DIR}/CMakeFiles \ | ||
| && lcov --remove coverage.info -o coverage.info '/usr/include/*' '/usr/lib/*' \ | ||
| && genhtml -o report coverage.info | ||
|
|
||
| valgrind_tests: | ||
| valgrind --tool=memcheck --leak-check=yes --error-exitcode=1 ./${BUILD_DIR}/${LIB_DIR}/${TESTS_DIR}/${TESTS_EXE} | ||
|
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,2 +1,27 @@ | ||
| # techopark_cpp_hw | ||
| Репозиторий для сдачи домашних работ по С++ в Технопарке | ||
|
|
||
| #### Домашняя работа 1 | ||
|
|
||
| ##### Студент: Михаил Мяделец WEB-11 | ||
| ##### Ментор: Денис Кириллов | ||
| ##### Преподаватель: Иван Возвахов | ||
|
|
||
| `Вариант #1` | ||
|
|
||
| Необходимо разработать классы для работы с вещественными числами, векторами (строками размерности 1xN и столбцами размерности Nx1) и матрицами размерности MxN и реализовать операции над ними: | ||
| 1) обращение по индексам к элементам, извлечение диагонали, строки или столбца - 1б (после модификации исходной матрицы извлечённые элементы меняться не должны); | ||
| 2) возможность создания матрицы из векторов или чисел, вектора из чисел - 1б; | ||
| 3) поэлементное сложение/вычитание/умножение объектов одинаковой размерности - 1б; | ||
| 4) умножение числа на матрицу, вектора на матрицу, матрицы на вектор и матрицы на матрицу - 1б; | ||
| 5) суммирование/вычитание числа и вектора/матрицы, матрицы и вектора (с возможностью выбора - по строкам/по столбцам) - 1б; | ||
| 6) получение транспонированной и обратной матриц - 1б; | ||
| 7) подсчёт определителя матрицы - 1б. | ||
|
|
||
| Все основные операции должны быть реализованы через перегрузку операторов (операторы могут быть модифицирующие (+= и др.) и немодифицирующие (+ и др.)). | ||
|
|
||
| Доп. баллы: | ||
| - поддержка "слайсов, как в питоне" (на уровне методов, т.к. операторы такой синтаксис не поддерживают). В качестве примерного интерфейса можно опираться на то, как это сделано в " аналоге numpy на C++" https://github.com/dpilger26/NumCpp -1б; | ||
| - размерность матриц может задаваться с помощью шаблонных параметров -2б; | ||
|
|
||
| Для сдачи необходимо развернуть базовый CI, в котором будут осуществляться автоматическая сборка и тестирование проекта (хотя бы один интеграционный тест, показывающий работоспособность всех реализованных пунктов). Без покрытия тестами каждый пункт оценивается в 50% стоимости. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| #include <iostream> | ||
|
Collaborator
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. добавь сюда хоть какой-нибудь расчет |
||
|
|
||
| #include "dvector.h" | ||
| #include "dmatrix_compile.h" | ||
| #include "dmatrix.h" | ||
|
|
||
| int main() | ||
| { | ||
| DMatrix matrix = { | ||
| {1, -2, 1}, | ||
| {2, 1, -1}, | ||
| {3, 2, -2} | ||
| }; | ||
| DVector vector = {3, 4, 5}; | ||
| DMatrix newMatrix = 2 * vector.Dot(matrix.Inv()); | ||
| std::cout << newMatrix; | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,45 @@ | ||
| cmake_minimum_required(VERSION 3.0.0) | ||
| project(matrix_lib) | ||
|
|
||
| set(CMAKE_CXX_STANDARD 17) | ||
| set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC -O0") | ||
|
|
||
| if(TEST_OPT) | ||
| set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fprofile-arcs -ftest-coverage") | ||
| set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -coverage -lgcov" ) | ||
| endif() | ||
|
|
||
| if(DEBUG_OPT) | ||
| set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g") | ||
| endif() | ||
|
|
||
| file(GLOB_RECURSE SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp) | ||
| file(GLOB_RECURSE HEADERS ${CMAKE_CURRENT_SOURCE_DIR}/include/*.h) | ||
| file(GLOB INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/include) | ||
|
|
||
| # find_package(Boost COMPONENTS system REQUIRED) | ||
|
|
||
| # if(NOT Boost_FOUND) | ||
| # message("Not found Boost") | ||
| # return() | ||
| # endif() | ||
|
|
||
| # Boost_VERSION_MACRO | ||
| # Boost_LIBRARY_DIR | ||
| # Boost_INCLUDE_DIR | ||
|
|
||
| add_library(${PROJECT_NAME} ${SOURCES} ${HEADERS}) | ||
|
|
||
| target_include_directories(${PROJECT_NAME} PUBLIC ${INCLUDE_DIRS}) | ||
|
|
||
| # без PARENT_SCOPE для тестов | ||
| # с PARENT_SCOPE для главного CMakeLists.txt | ||
| set(MATRIX_LIB_LIBRARIES ${PROJECT_NAME} ) | ||
| set(MATRIX_LIB_LIBRARIES ${PROJECT_NAME} PARENT_SCOPE) | ||
| set(MATRIX_LIB_INCLUDE_DIRS ${INCLUDE_DIRS} PARENT_SCOPE) | ||
| set(MATRIX_LIB_INCLUDE_DIRS ${INCLUDE_DIRS} ) | ||
|
|
||
| if (TEST_OPT) | ||
| enable_testing() | ||
| add_subdirectory(tests) | ||
| endif() |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,135 @@ | ||
| #pragma once | ||
|
|
||
| #include "dvector.h" | ||
|
|
||
| enum class ORIENT { ROW = 0, COL }; | ||
|
Collaborator
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. тут енам класс, ниже просто енам. почему? |
||
| enum SLICE { ROW = 0, COL }; | ||
|
Collaborator
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. я бы сделал явное указание, чему равен COL |
||
|
|
||
| // Matrix of doubles number | ||
| class DMatrix | ||
| { | ||
| private: | ||
| DVector *m_matrix = nullptr; | ||
| size_t m_nRows = 0; | ||
| size_t m_nCols = 0; | ||
| size_t m_capacity = 0; | ||
| void grow(); | ||
| public: | ||
| DMatrix() = default; | ||
| DMatrix(DVector *matrix, size_t nRows); | ||
| // Создание матрицы как вектор-строку или вектор-столбец | ||
| DMatrix(DVector const &dvec, ORIENT orientation = ORIENT::ROW); | ||
| DMatrix(size_t rows, size_t cols, double fill_value = 0); | ||
| DMatrix(std::initializer_list<std::initializer_list<double>> const &matrix); | ||
| DMatrix(DMatrix const &other); | ||
| DMatrix(DMatrix &&other); | ||
| DMatrix &operator=(DMatrix other); | ||
| ~DMatrix(); | ||
|
|
||
| /* ****** Задание размера через шаблон *******/ | ||
| template <size_t rows, size_t cols> | ||
| static DMatrix Create(double fill_value = 0); | ||
|
|
||
| public: | ||
| void Clear(); | ||
| bool Empty(); | ||
| void Swap(DMatrix &other); | ||
|
|
||
| void PushRowBack(DVector const &dvec); | ||
| void PushRowBack(std::initializer_list<double> const &init_list); | ||
| void PopRowBack(); | ||
|
|
||
| void PushColBack(DVector const &dvec); | ||
| void PushColBack(std::initializer_list<double> const &init_list); | ||
| void PopColBack(); | ||
|
|
||
| void EraseByIndex(size_t index, ORIENT orientation = ORIENT::ROW); | ||
|
|
||
|
|
||
| /* ****** ЗАДАНИЕ 1 ****** */ | ||
| DVector GetDiag() const; | ||
| DVector GetRow(size_t index) const; | ||
| DVector GetCol(size_t index) const; | ||
|
|
||
| /* ****** ЗАДАНИЕ 4 ****** */ | ||
| DMatrix Dot(DMatrix const &other) const; | ||
| DVector Dot(DVector const &dvec) const; | ||
|
|
||
| size_t nRows() const; | ||
| size_t nCols() const; | ||
| size_t Capacity() const; | ||
|
|
||
| /* ****** ЗАДАНИЕ 5 ****** */ | ||
| // модифицирующие операции | ||
| void AddNum(double value); | ||
| void SubNum(double value); | ||
| void AddVec(DVector const &dvec, ORIENT orientation = ORIENT::ROW); | ||
| void SubVec(DVector const &dvec, ORIENT orientation = ORIENT::ROW); | ||
|
|
||
| /* ****** ЗАДАНИЯ 6 и 7 ****** */ | ||
| DMatrix T() const; | ||
| double Det() const; | ||
| double Minor(size_t iIndex, size_t jIndex) const; | ||
| DMatrix Adj(); | ||
| DMatrix Inv(); | ||
|
|
||
| DVector const &operator[](size_t index) const; | ||
| DVector &operator[](size_t index); | ||
|
|
||
| /* | ||
| Пояснение: | ||
| enum SLICE {ROW = 0, COL}, чтобы | ||
| 1. не писать класс, если в параметрах ROW / COL | ||
| 2. кастилось к enum SLICE, если в параметрах 0 / 1 | ||
| */ | ||
|
Collaborator
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. во! это пояснение - наверх |
||
|
|
||
| /* ****** Slices ****** */ | ||
| DMatrix operator()(size_t begin, size_t end, int step = 1, uint8_t sliceType = SLICE::ROW) const; | ||
|
|
||
| DMatrix SliceRow(size_t begin, size_t end, int step = 1) const; | ||
| DMatrix SliceCol(size_t begin, size_t end, int step = 1) const; | ||
| }; | ||
|
|
||
| // matrix *= value | ||
| DMatrix &operator/=(DMatrix &matrix, double value); | ||
| DMatrix &operator*=(DMatrix &matrix, double value); | ||
|
|
||
| // matrix * value | ||
| DMatrix operator/(DMatrix matrix, double value); | ||
| DMatrix operator*(DMatrix matrix, double value); | ||
|
|
||
| // value *= matrix | ||
|
|
||
| DMatrix &operator/=(double value, DMatrix &matrix); | ||
| DMatrix &operator*=(double value, DMatrix &matrix); | ||
|
|
||
| // value * matrix | ||
| DMatrix operator/(double value, DMatrix matrix); | ||
| DMatrix operator*(double value, DMatrix matrix); | ||
|
|
||
| // matrix += matrix | ||
|
|
||
| DMatrix &operator+=(DMatrix &left, DMatrix const &right); | ||
| DMatrix &operator-=(DMatrix &left, DMatrix const &right); | ||
| DMatrix &operator/=(DMatrix &left, DMatrix const &right); | ||
| DMatrix &operator*=(DMatrix &left, DMatrix const &right); | ||
|
|
||
| // matrix + matrix | ||
| DMatrix operator+(DMatrix left, DMatrix const &right); | ||
| DMatrix operator-(DMatrix left, DMatrix const &right); | ||
| DMatrix operator/(DMatrix left, DMatrix const &right); | ||
| DMatrix operator*(DMatrix left, DMatrix const &right); | ||
|
|
||
| std::ostream &operator<<(std::ostream &out, DMatrix const &matrix); | ||
|
|
||
| void Print(DMatrix const &matrix, std::string const &msg = std::string{}); | ||
|
Collaborator
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<<new DMatrix() ) с его вызовом внутри |
||
|
|
||
| template <size_t rows, size_t cols> | ||
| DMatrix DMatrix::Create(double fill_value) | ||
| { | ||
| if ((rows == 0) ^ (cols == 0)) | ||
| { | ||
| throw std::runtime_error("Creation is impossible"); | ||
|
Collaborator
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. жестоко
Collaborator
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. остальные ошибки у тебя в виде extern const и define |
||
| } | ||
| return DMatrix(rows, cols, fill_value); | ||
| } | ||
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.
часто выделяют prepare или beforescript с установкой всего необходимого, check - с линтером, build, test. требовать так делать не буду, особенно больно будет с линтером