I'm visiting some code that I wrote for one of my finals projects and wanted to know whether there were a more optimal, more elegant way to do this so it does not look so "hard-coded".
The problem was that I needed to calculate the Determinant of a matrix, and, at the time (some of it was rushed) I did not know of a better way, using loops or re-usable code that could make the code a little better. Here is the code:
namespace Determinant {
template<int X>
float determinant(std::vector<Vector> &data)
{
float deter = 0.0;
if(X == 2)
{
float a = data[0][0];
float b = data[1][0];
float c = data[1][1];
deter = (a + c) * (a + c) -4 * (a*c-b*b);
}else if(X == 3)
{
float determinant1 = (data[1][1] * data[2][2]) - (data[2][1] * data[1][2]);
float determinant2 = (data[1][0] * data[2][2]) - (data[2][0] * data[1][2]);
float determinant3 = (data[1][0] * data[2][1]) - (data[2][0] * data[1][1]);
deter = (data[0][0] * determinant1) - (data[0][1] * determinant2) + (data[0][2] * determinant3);
}
return deter;
}
}
As you can see the Determinant is very hard-coded which is probably not the right way -- But are there any other alternatives that isn't hard-coded? I want to start to use a design pattern, as I feel one would be useful here but can't seem to figure out which one.