Skip to content

Commit

Permalink
Fix warnings and remove VLA on C++ Thomas algorithm (algorithm-archiv…
Browse files Browse the repository at this point in the history
…ists#932)

* Fix warnings and remove VLA

* Simplified the reverse for-loop and changed endl to '\n'

Co-authored-by: James Schloss <[email protected]>
  • Loading branch information
ShadowMitia and leios authored Jan 15, 2022
1 parent 9b58757 commit 7acfce9
Showing 1 changed file with 34 additions and 32 deletions.
66 changes: 34 additions & 32 deletions contents/thomas_algorithm/code/cpp/thomas.cpp
Original file line number Diff line number Diff line change
@@ -1,43 +1,45 @@
#include <cstddef>
#include <iostream>
#include <vector>
#include <cstring>

void thomas(std::vector<double> const a, std::vector<double> const b, std::vector<double> const c, std::vector<double>& x) {
int size = a.size();
double y[size];
memset(y, 0, size * sizeof(double));

y[0] = c[0] / b[0];
x[0] = x[0] / b[0];

for (size_t i = 1; i < size; ++i) {
double scale = 1.0 / (b[i] - a[i] * y[i - 1]);
y[i] = c[i] * scale;
x[i] = (x[i] - a[i] * x[i - 1]) * scale;
}

for (int i = size - 2; i >= 0; --i) {
x[i] -= y[i] * x[i + 1];
}
void thomas(
std::vector<double> const& a,
std::vector<double> const& b,
std::vector<double> const& c,
std::vector<double>& x) {
auto y = std::vector<double>(a.size(), 0.0);

y[0] = c[0] / b[0];
x[0] = x[0] / b[0];

for (std::size_t i = 1; i < a.size(); ++i) {
const auto scale = 1.0 / (b[i] - a[i] * y[i - 1]);
y[i] = c[i] * scale;
x[i] = (x[i] - a[i] * x[i - 1]) * scale;
}

for (std::size_t i = a.size() - 2; i < a.size(); --i) {
x[i] -= y[i] * x[i + 1];
}
}

int main() {
std::vector<double> a = {0.0, 2.0, 3.0};
std::vector<double> b = {1.0, 3.0, 6.0};
std::vector<double> c = {4.0, 5.0, 0.0};
std::vector<double> x = {7.0, 5.0, 3.0};
const std::vector<double> a = {0.0, 2.0, 3.0};
const std::vector<double> b = {1.0, 3.0, 6.0};
const std::vector<double> c = {4.0, 5.0, 0.0};
std::vector<double> x = {7.0, 5.0, 3.0};

std::cout << "The system" << std::endl;
std::cout << "[1.0 4.0 0.0][x] = [7.0]" << std::endl;
std::cout << "[2.0 3.0 5.0][y] = [5.0]" << std::endl;
std::cout << "[0.0 3.0 6.0][z] = [3.0]" << std::endl;
std::cout << "has the solution" << std::endl;
std::cout << "The system\n";
std::cout << "[1.0 4.0 0.0][x] = [7.0]\n";
std::cout << "[2.0 3.0 5.0][y] = [5.0]\n";
std::cout << "[0.0 3.0 6.0][z] = [3.0]\n";
std::cout << "has the solution:\n";

thomas(a, b, c, x);
thomas(a, b, c, x);

for (size_t i = 0; i < 3; ++i) {
std::cout << "[" << x[i] << "]" << std::endl;
}
for (auto const& val : x) {
std::cout << "[" << val << "]\n";
}

return 0;
return 0;
}

0 comments on commit 7acfce9

Please sign in to comment.