Skip to content

Commit 84aaa36

Browse files
sklanberquist
authored andcommitted
Added thomas algorithm in kotlin (algorithm-archivists#539)
1 parent 50c05b0 commit 84aaa36

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
private fun thomas(a: DoubleArray, b: DoubleArray, c: DoubleArray, d: DoubleArray): DoubleArray {
2+
val cPrime = c.clone()
3+
val x = d.clone()
4+
val size = a.size
5+
cPrime[0] /= b[0]
6+
x[0] /= b[0]
7+
for (i in 1 until size) {
8+
val scale = 1.0 / (b[i] - cPrime[i - 1] * a[i])
9+
cPrime[i] *= scale
10+
x[i] = (x[i] - a[i] * x[i - 1]) * scale
11+
}
12+
for (i in (size - 2) downTo 0) {
13+
x[i] -= cPrime[i] * x[i + 1]
14+
}
15+
return x
16+
}
17+
18+
fun main(args: Array<String>) {
19+
val a = doubleArrayOf(0.0, 2.0, 3.0)
20+
val b = doubleArrayOf(1.0, 3.0, 6.0)
21+
val c = doubleArrayOf(4.0, 5.0, 0.0)
22+
val x = doubleArrayOf(7.0, 5.0, 3.0)
23+
val solution = thomas(a, b, c, x)
24+
25+
println("System:")
26+
println("[%.1f, %.1f, %.1f][x] = [%.1f]".format(b[0], c[0], 0f, x[0]))
27+
println("[%.1f, %.1f, %.1f][y] = [%.1f]".format(a[1], b[1], c[1], x[1]))
28+
println("[%.1f, %.1f, %.1f][z] = [%.1f]\n".format(0f, a[2], b[2], x[2]))
29+
println("Solution:")
30+
for (i in solution.indices) {
31+
println("[% .5f]".format(solution[i]))
32+
}
33+
}

contents/thomas_algorithm/thomas_algorithm.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,8 @@ You will find this algorithm implemented [in this project](https://scratch.mit.e
125125
[import, lang:"lua"](code/lua/thomas.lua)
126126
{% sample lang="crystal" %}
127127
[import, lang:"crystal"](code/crystal/thomas.cr)
128+
{% sample lang="kotlin" %}
129+
[import, lang:"kotlin"](code/kotlin/thomas.kt)
128130
{% endmethod %}
129131

130132
<script>

0 commit comments

Comments
 (0)