diff --git a/contents/thomas_algorithm/code/javascript/thomas.js b/contents/thomas_algorithm/code/javascript/thomas.js new file mode 100644 index 000000000..f9aa1da9a --- /dev/null +++ b/contents/thomas_algorithm/code/javascript/thomas.js @@ -0,0 +1,31 @@ +function thomas(a, b, c, x) { + const y = []; + + y[0] = c[0] / b[0]; + x[0] = x[0] / b[0]; + + for (let i = 1; i < a.length; i++) { + const 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 (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++) + console.log("[" + x[i] + "]"); diff --git a/contents/thomas_algorithm/thomas_algorithm.md b/contents/thomas_algorithm/thomas_algorithm.md index 2b73868e1..70a4c682e 100644 --- a/contents/thomas_algorithm/thomas_algorithm.md +++ b/contents/thomas_algorithm/thomas_algorithm.md @@ -131,6 +131,8 @@ You will find this algorithm implemented [in this project](https://scratch.mit.e [import, lang:"kotlin"](code/kotlin/thomas.kt) {% sample lang="ruby" %} [import, lang="ruby"](code/ruby/thomas.rb) +{% sample lang="js" %} +[import, lang:"javascript"](code/javascript/thomas.js) {% endmethod %}