Added determinant for matrices of any size

This commit is contained in:
2019-12-13 19:06:16 +03:00
parent 30ddecfa3c
commit 07c4eacf1a
2 changed files with 29 additions and 5 deletions

View File

@@ -57,12 +57,26 @@ class BoolSquareMatrix {
return (_values >> index(row, col)) % 2;
}
STORAGE get_determinant() {
if ( SIZE == 2 ) {
if constexpr ( SIZE == 2 ) {
return at(0,0) * at(1,1) - at(0,1) * at(1,0);
} else if ( SIZE == 3 ) {
return at(0,0) * at(1,1) * at(2,2) + at(0,1) * at(1,2) * at(2,0)
+ at(0,2) * at(1,0) * at(2,1) - at(0,2) * at(1,1) * at(2,0)
- at(0,1) * at(1,0) * at(2,2) - at(0,0) * at(1,2) * at(2,1);
} else if constexpr ( SIZE == 4 or SIZE == 3 ) {
int cur_modifier = 1;
STORAGE res = 0;
for (STORAGE remove_ind = 0; remove_ind < SIZE; ++remove_ind) {
STORAGE tmp_vector_value = 0;
for (STORAGE i = 1; i < SIZE; ++i) {
for (STORAGE j = 0; j < SIZE; ++j) {
if ( j == remove_ind )
continue;
tmp_vector_value *= 2;
tmp_vector_value += at(i, j);
}
}
BoolSquareMatrix<STORAGE, SIZE - 1> tmp_matix(tmp_vector_value);
res += cur_modifier * tmp_matix.get_determinant() * at(0, remove_ind);
cur_modifier *= -1;
}
return res;
}
}

View File

@@ -59,6 +59,16 @@ void test_function() {
assert(minus_i_matrix.string("") == "001010100");
assert(minus_i_matrix.get_determinant() == uint16_t(-1));
BoolSquareMatrix<uint16_t, 4> ones_matrix_4(0b1111111111111111),
i_matrix_4(0b1000010000100001),
minus_i_matrix_4(0b0001001001001000);
assert(ones_matrix_4.string("") == "1111111111111111");
assert(ones_matrix_4.get_determinant() == 0);
assert(i_matrix_4.string("") == "1000010000100001");
assert(i_matrix_4.get_determinant() == 1);
assert(minus_i_matrix_4.string("") == "0001001001001000");
assert(minus_i_matrix_4.get_determinant() == 1);
cout << "self-test passed" << endl;
}