```
#include <conio.h>
#include <iostream>
#include <vector>
using namespace std;
class Permute
{
vector<int> set;
vector<vector<int> > all;
public:
void Print()
{
unsigned size = all.size();
for(unsigned i = 0; i < size; i++)
{
unsigned size_i = all[i].size();
for(unsigned j = 0; j < size_i; j++)
cout<< all[i][j] << " ";
cout<< "\n";
}
}
//-------------------------------------------
void Run()
{
unsigned size = set.size();
if(size == 0)
return;
if(size == 1)
{
all.push_back(set);
return;
}
unsigned i = 0; /* sweeper item can be any number between 0 & size - 1 */
vector<int> subset;
for(unsigned j = 0; j < size; j++)
{
if(i != j)
subset.push_back(set[j]);
}
Permute P(subset);
unsigned allsize = P.Size();
for(unsigned k = 0; k < allsize; k++)
{
unsigned size_k = P[k].size();
for(unsigned m = 0; m <= size_k; m++)
{
P[k].insert(P[k].begin() + m,set[i]);
all.push_back(P[k]);
P[k].erase(P[k].begin() + m);
}
}
}
//-------------------------------------------
unsigned Size()
{
return all.size();
}
//-------------------------------------------
vector<int>& operator [](unsigned i)
{
if(Size() <= i)
i = Size() - 1;
return all[i];
}
public:
Permute(vector<int> set)
: set(set)
{
Run();
}
};
int Sign(vector<int> v) // sign of the permutation
{
unsigned returns = 0;
unsigned size = v.size();
for(unsigned i = 0; i < size; i++)
for(unsigned j = i + 1; j < size; j++)
{
if(v[j] < v[i])
returns++;
}
if(returns % 2 == 0)
return 1;
else
return -1;
}
template<const int n> // n by n matrix
double Determinant(double a[n][n]) // determinant
{
vector<int> v;
for(unsigned i = 0; i < n; i++)
v.push_back(i);
Permute P(v);
unsigned size = P.Size();
double sum = 0;
for(unsigned k = 0; k < size; k++)
{
double prod = Sign(P[k]);
for(unsigned i = 0; i < n; i++)
prod *= a[i][P[k][i]];
sum += prod;
}
return sum;
}
int main()
{
double a[3][3] =
{
{0, 0, 1},
{5,-2, 6},
{1, 1, 2}
};
cout<< Determinant<3>(a);
_getch();
}
```

Recommended Topics