# Easy Laplace det

Apr 12th, 2021
635
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. #include <iostream>
2. #include <vector>
3. #include <cmath>
4.
5. std::vector<std::vector<double>> compute_minor(std::vector<std::vector<double>> matrix, int skip_i, int skip_j) {
6.   std::vector<std::vector<double>> v_minor(matrix.size() - 1, std::vector<double>(matrix.size() - 1, 0));
7.
8.   for(int i = 0, mi = 0; i < matrix.size(); i++) {
9.     if(i == skip_i) continue;
10.     for(int j = 0, mj = 0; j < matrix.size(); j++) {
11.       if(j == skip_j) continue;
12.       v_minor.at(mi).at(mj++) = matrix.at(i).at(j);
13.     }
14.     mi++;
15.   }
16.
17.   return v_minor;
18. }
19.
20. double det(std::vector<std::vector<double>> matrix) {
21.   if(matrix.size() == 1) {
22.     return matrix.at(0).at(0);
23.   }
24.
25.   int determinant = 0;
26.   for(int j = 0; j < matrix.size(); j++) {
27.     int sign = j & 1 ? -1 : 1;
28.     determinant += sign * matrix.at(0).at(j) * det(compute_minor(matrix, 0, j));
29.   }
30.
31.
32.   return determinant;
33. }
34.
35. int main () {
36.   std::vector<std::vector<double>> matrix = { { 1, 2, 1, 1}, { 1, 22, 2, 3 }, { 5, 5, 3, 3 }, { 2, 8, 1, 1 } };
37.   double d = det(matrix);
38.   std::cout << "Det: " << d << std::endl;
39.
40.   return 0;
41. }
RAW Paste Data