Skip to content

Commit 2125f5c

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
1 parent 8394ead commit 2125f5c

File tree

1 file changed

+14
-6
lines changed

1 file changed

+14
-6
lines changed

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

Lines changed: 14 additions & 6 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

@@ -65,7 +67,7 @@ std::vector<double> back_substitution(const std::vector<double>& a, int cols) {
6567
soln[rows - 1] =
6668
a[cols - 1 + (rows - 1) * cols] / a[cols - 1 - 1 + (rows - 1) * cols];
6769

68-
for (int i = rows - 1; i >= 0; --i) {
70+
for (int i = rows - 2; i >= 0; --i) {
6971
auto sum = 0.0;
7072
for (int j = cols - 2; j > i; --j) {
7173
sum += soln[j] * a[j + i * cols];
@@ -86,7 +88,7 @@ void gauss_jordan_elimination(std::vector<double>& a, int cols) {
8688
if (a[col + row * cols] != 0) {
8789

8890
// divide row by pivot and leaving pivot as 1
89-
for (int i = cols - 1; i >= static_cast<int>(col); --i)
91+
for (int i = cols - 1; i >= col; --i)
9092
a[i + row * cols] /= a[col + row * cols];
9193

9294
// subtract value from above row and set values above pivot to 0
@@ -104,16 +106,22 @@ void print_matrix(const std::vector<double>& a, int cols) {
104106
for (int i = 0; i < rows; ++i) {
105107
std::cout << "[";
106108
for (int j = 0; j < cols; ++j) {
107-
std::cout << a[j + i * cols] << " ";
109+
std::cout << std::fixed << a[j + i * cols] << "\t";
108110
}
109111
std::cout << "]\n";
110112
}
111113
}
112114

113115
int main() {
114-
std::vector<double> a = {2, 3, 4, 6, 1, 2, 3, 4, 3, -4, 0, 10};
116+
std::vector<double> a = { 2, 3, 4, 6,
117+
1, 2, 3, 4,
118+
3, -4, 0, 10 };
115119
const int cols = 4;
116-
assert(a.size() % cols == 0);
120+
if (a.size() % cols != 0)
121+
{
122+
std::cout << "The input dimentions are incorrect\n";
123+
return 1;
124+
}
117125

118126
gaussian_elimination(a, cols);
119127
print_matrix(a, cols);

0 commit comments

Comments
 (0)