Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions contents/thomas_algorithm/code/javascript/thomas.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
function thomas(a, b, c, x) {
let y = [];
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could be const.


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

for (let i = 1; i < a.length; i++) {
let scale = 1.0 / (b[i] - a[i] * y[i - 1]);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could also be const.

You also don't have to use 1.0. JavaScript doesn't differentiate between 1 and 1.0.

y[i] = c[i] * scale;
x[i] = (x[i] - a[i] * x[i - 1]) * scale;
}

for (let i = a.length - 2; i >= 0; i--)
x[i] -= y[i] * x[i + 1];
}

let a = [0.0, 2.0, 3.0];
let b = [1.0, 3.0, 6.0];
let c = [4.0, 5.0, 0.0];
let x = [7.0, 5.0, 3.0];

console.log("The system,");
console.log("[1.0 4.0 0.0][x] = [7.0]");
console.log("[2.0 3.0 5.0][y] = [5.0]");
console.log("[0.0 3.0 6.0][z] = [3.0]");
console.log("has the solution:\n");

thomas(a, b, c, x);

for (let i = 0; i < 3; i++)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You could use for (const value of x) { here. Also, you could just print the array as a whole: console.log("has the solution: ", x)

Copy link
Contributor Author

@Yordrar Yordrar Oct 9, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done, went for the console.log("solution: ", x) as it is simpler

console.log("[" + x[i] + "]");
2 changes: 2 additions & 0 deletions contents/thomas_algorithm/thomas_algorithm.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,8 @@ You will find this algorithm implemented [in this project](https://scratch.mit.e
[import, lang:"nim"](code/nim/thomas_algorithm.nim)
{% sample lang="cpp" %}
[import, lang:"c_cpp"](code/c++/thomas.cpp)
{% sample lang="js" %}
[import, lang:"javascript"](code/javascript/thomas.js)
{% endmethod %}

<script>
Expand Down