diff --git a/contents/thomas_algorithm/code/javascript/thomas.js b/contents/thomas_algorithm/code/javascript/thomas.js new file mode 100644 index 000000000..d6e2b89a8 --- /dev/null +++ b/contents/thomas_algorithm/code/javascript/thomas.js @@ -0,0 +1,29 @@ +function thomas(a, b, c, x) { + const result = []; + const y = []; + + y[0] = c[0] / b[0]; + result[0] = x[0] / b[0]; + + for (let i = 1; i < a.length; i++) { + const scale = 1 / (b[i] - a[i] * y[i - 1]); + y[i] = c[i] * scale; + result[i] = (x[i] - a[i] * result[i - 1]) * scale; + } + + for (let i = a.length - 2; i >= 0; i--) + result[i] -= y[i] * result[i + 1]; + + return result; +} + +let a = [0, 2, 3]; +let b = [1, 3, 6]; +let c = [4, 5, 0]; +let x = [7, 5, 3]; + +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)); diff --git a/contents/thomas_algorithm/thomas_algorithm.md b/contents/thomas_algorithm/thomas_algorithm.md index 885739421..11f74f159 100644 --- a/contents/thomas_algorithm/thomas_algorithm.md +++ b/contents/thomas_algorithm/thomas_algorithm.md @@ -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 %}