Skip to content

Commit 55f0195

Browse files
committed
Address code review comments:
- add curly bracket - remove static_cast - fix format for the matrix - format output with tabs - properly sanitize user input - fix off-by-one error - remove extraneous assignment
1 parent 8394ead commit 55f0195

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

contents/gaussian_elimination/code/c++/gaussian_elimination.cpp

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
#include <cmath>
44
#include <iostream>
55
#include <vector>
6+
#include <iomanip>
67

78
void gaussian_elimination(std::vector<double>& a, int cols) {
89
assert(a.size() % cols == 0);
@@ -16,11 +17,12 @@ void gaussian_elimination(std::vector<double>& a, int cols) {
1617
int max_index = [&]() {
1718
int res = row;
1819
int max_element = a[col + row * cols];
19-
for (int r = row + 1; r < rows; ++r)
20+
for (int r = row + 1; r < rows; ++r) {
2021
if (max_element < std::abs(a[col + r * cols])) {
2122
max_element = std::abs(a[col + r * cols]);
2223
res = r;
2324
}
25+
}
2426
return res;
2527
}();
2628

@@ -61,10 +63,6 @@ std::vector<double> back_substitution(const std::vector<double>& a, int cols) {
6163
// Creating the solution Vector
6264
std::vector<double> soln(rows);
6365

64-
// initialize the final element
65-
soln[rows - 1] =
66-
a[cols - 1 + (rows - 1) * cols] / a[cols - 1 - 1 + (rows - 1) * cols];
67-
6866
for (int i = rows - 1; i >= 0; --i) {
6967
auto sum = 0.0;
7068
for (int j = cols - 2; j > i; --j) {
@@ -86,7 +84,7 @@ void gauss_jordan_elimination(std::vector<double>& a, int cols) {
8684
if (a[col + row * cols] != 0) {
8785

8886
// divide row by pivot and leaving pivot as 1
89-
for (int i = cols - 1; i >= static_cast<int>(col); --i)
87+
for (int i = cols - 1; i >= col; --i)
9088
a[i + row * cols] /= a[col + row * cols];
9189

9290
// subtract value from above row and set values above pivot to 0
@@ -104,16 +102,22 @@ void print_matrix(const std::vector<double>& a, int cols) {
104102
for (int i = 0; i < rows; ++i) {
105103
std::cout << "[";
106104
for (int j = 0; j < cols; ++j) {
107-
std::cout << a[j + i * cols] << " ";
105+
std::cout << std::fixed << a[j + i * cols] << "\t";
108106
}
109107
std::cout << "]\n";
110108
}
111109
}
112110

113111
int main() {
114-
std::vector<double> a = {2, 3, 4, 6, 1, 2, 3, 4, 3, -4, 0, 10};
112+
std::vector<double> a = { 2, 3, 4, 6,
113+
1, 2, 3, 4,
114+
3, -4, 0, 10 };
115115
const int cols = 4;
116-
assert(a.size() % cols == 0);
116+
if (a.size() % cols != 0)
117+
{
118+
std::cout << "The input dimentions are incorrect\n";
119+
return 1;
120+
}
117121

118122
gaussian_elimination(a, cols);
119123
print_matrix(a, cols);

0 commit comments

Comments
 (0)