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
39 changes: 39 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
on: push

env:
LIB_NAME: matrix_lib

Copy link
Collaborator

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. требовать так делать не буду, особенно больно будет с линтером

jobs:
build:
runs-on: ubuntu-latest
container: leshiy1295/gcc_linters_valgrind_cmake_gtest
Copy link
Collaborator

Choose a reason for hiding this comment

The 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
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/build
_test.cpp
main
/.vscode
24 changes: 24 additions & 0 deletions CMakeLists.txt
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})

34 changes: 34 additions & 0 deletions Makefile
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}

25 changes: 25 additions & 0 deletions README.md
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% стоимости.
17 changes: 17 additions & 0 deletions main.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#include <iostream>
Copy link
Collaborator

Choose a reason for hiding this comment

The 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;
}
45 changes: 45 additions & 0 deletions matrix_lib/CMakeLists.txt
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()
135 changes: 135 additions & 0 deletions matrix_lib/include/dmatrix.h
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 };
Copy link
Collaborator

Choose a reason for hiding this comment

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

тут енам класс, ниже просто енам. почему?

enum SLICE { ROW = 0, COL };
Copy link
Collaborator

Choose a reason for hiding this comment

The 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
*/
Copy link
Collaborator

Choose a reason for hiding this comment

The 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{});
Copy link
Collaborator

Choose a reason for hiding this comment

The 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");
Copy link
Collaborator

Choose a reason for hiding this comment

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

жестоко

  1. runtime_error
  2. причина. я вижу в терминале "Creation is impossible", и плачу, потому что не понимаю, что не так

Copy link
Collaborator

Choose a reason for hiding this comment

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

остальные ошибки у тебя в виде extern const и define

}
return DMatrix(rows, cols, fill_value);
}
Loading