Skip to content

Commit 44181dc

Browse files
Wesley-Arringtonjiegillet
authored andcommitted
Adding Thomas Algorithm in Swift (#383)
* Adding Thomas Algorithm in Swift * Changed function to pass by value
1 parent 7f7fd3b commit 44181dc

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
func thomas(a: [Double], b: [Double], c: [Double], d: [Double]) -> [Double] {
2+
var a = a
3+
var b = b
4+
var c = c
5+
var d = d
6+
7+
// set the initial elements
8+
c[0] = c[0] / b[0]
9+
d[0] = d[0] / b[0]
10+
11+
let n = d.count // number of equations to solve
12+
for i in 1..<n {
13+
// scale factor for c and d
14+
let scale = 1 / (b[i] - c[i-1] * a[i])
15+
16+
c[i] = c[i] * scale
17+
d[i] = (d[i] - a[i] * d[i-1]) * scale
18+
}
19+
20+
// do the back substitution
21+
for i in stride(from: n-2, to: -1, by: -1) {
22+
d[i] = d[i] - c[i] * d[i+1]
23+
}
24+
25+
return d
26+
}
27+
28+
func main() {
29+
let a = [0.0, 2.0, 3.0]
30+
let b = [1.0, 3.0, 6.0]
31+
let c = [4.0, 5.0, 0.0]
32+
let d = [7.0, 5.0, 3.0]
33+
34+
print(thomas(a: a, b: b, c: c, d: d))
35+
}
36+
37+
main()

contents/thomas_algorithm/thomas_algorithm.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,8 @@ You will find this algorithm implemented [in this project](https://scratch.mit.e
111111
[import, lang:"java"](code/java/thomas.java)
112112
{% sample lang="hs" %}
113113
[import, lang:"haskell"](code/haskell/thomas.hs)
114+
{% sample lang="swift" %}
115+
[import, lang:"swift"](code/swift/thomas.swift)
114116
{% endmethod %}
115117

116118
<script>

0 commit comments

Comments
 (0)