c++使用vector求矩阵的A(行列式)

c++使用vector求矩阵的A(行列式)

  • 直接上代码
#include <vector>
#include <iostream>
using namespace std;


bool Iseven(int num)
{
    //用位与运算来判断奇偶(最快的判断奇偶的方法)
    return ((num & 1) == 0);
}

bool PowerIsPosition(vector<double>& vec)
{
    //count即为逆序数,初始化为0
    int count = 0;
    for (int i = 0; i < (int)vec.size(); i++)
    {
        for (int j = i + 1; j < (int)vec.size(); j++)
        {
            if (vec[i] > vec[j])
            {
                count += 1;
            }
        }
    }
    return (Iseven(count));
}

void swap(vector<double>& vec, int i, int j)
{
    int temp = vec[i];
    vec[i] = vec[j];
    vec[j] = temp;
}

void Perm(vector<double>& vec, vector<vector<double> >& vec_seq, int current_index)
{
    if (current_index == ((int)vec.size() - 1))
    {
        vec_seq.push_back(vec);
    }
    else
    {
        for (int i = current_index; i < (int)vec.size(); i++)
        {
            swap(vec, i, current_index);
            Perm(vec, vec_seq, current_index + 1);
            swap(vec, i, current_index);
        }
    }
}

vector<double> inivec(int n)
{
    vector<double> vec;
    for (int i = 0; i < n; i++)
        vec.push_back(i);
    return vec;
}

double calculate(vector<vector<double>> array)
{
    //计算行列式
    int n = array.size();
    vector<vector<double> > vec_que;
    vector<double> vec = inivec(n);
    vector<double> vec_elem;
    Perm(vec, vec_que, 0);
    //最终结果,初始化为0
    double result = 0;
    //依次为vec_que中取出行列式
    for (int i = 0; i < (int)vec_que.size(); i++)
    {
        vec_elem = vec_que[i];
        //mi即为前面(-1)的n次幂,最后结果为-1或者1
        double mi = PowerIsPosition(vec_elem) ? 1 : (-1);
        double temp = mi;
        //row号初始化为0之后依次加1
        int row = 0;
        //col号依次从vec_elem中取出
        for (int j = 0; j < (int)vec_elem.size(); j++)
        {
            int col = vec_elem[j];
            temp *= array[row++][col];
        }
        result += temp;
    }
    return result;
}


int main() {
    vector<vector<double>> nums1 = {
        {1, 2, 3},
        {4, 15, 6},
        {7, 8, 8}
    };
    double w = calculate(nums1);
    cout << w << endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值