Skip to content

Commit efcb278

Browse files
authored
Add Thomas Algorithm in Rust (#693)
1 parent 58438ce commit efcb278

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
fn thomas(a: &[f64], b: &[f64], c: &[f64], x: &[f64]) -> Vec<f64> {
2+
let size = a.len();
3+
let mut y = vec![0.0; size];
4+
let mut z = Vec::from(x);
5+
6+
y[0] = c[0] / b[0];
7+
z[0] = x[0] / b[0];
8+
9+
for i in 1..size {
10+
let scale = 1.0 / (b[i] - a[i] * y[i - 1]);
11+
y[i] = c[i] * scale;
12+
z[i] = (z[i] - a[i] * z[i - 1]) * scale;
13+
}
14+
15+
for i in (0..(size - 1)).rev() {
16+
z[i] -= y[i] * z[i + 1];
17+
}
18+
19+
z
20+
}
21+
22+
fn main() {
23+
let a = vec![0.0, 2.0, 3.0];
24+
let b = vec![1.0, 3.0, 6.0];
25+
let c = vec![4.0, 5.0, 0.0];
26+
let x = vec![7.0, 5.0, 3.0];
27+
28+
println!("The system");
29+
println!("[{:?} {:?} {:?}][x] = [{:?}]", a[0], b[0], c[0], &x[0]);
30+
println!("[{:?} {:?} {:?}][x] = [{:?}]", a[1], b[1], c[1], &x[1]);
31+
println!("[{:?} {:?} {:?}][x] = [{:?}]", a[2], b[2], c[2], &x[2]);
32+
println!("has the solution");
33+
34+
let y = thomas(&a, &b, &c, &x);
35+
36+
y.iter()
37+
.for_each(|i| println!("[{:>19}]", format!("{:18}", format!("{:?}", i))));
38+
}

contents/thomas_algorithm/thomas_algorithm.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,8 @@ You will find this algorithm implemented [in this project](https://scratch.mit.e
133133
[import, lang="ruby"](code/ruby/thomas.rb)
134134
{% sample lang="js" %}
135135
[import, lang:"javascript"](code/javascript/thomas.js)
136+
{% sample lang="rs" %}
137+
[import, lang:"rust"](code/rust/thomas.rs)
136138
{% endmethod %}
137139

138140
<script>

0 commit comments

Comments
 (0)