Created
March 21, 2014 20:25
-
-
Save nebuta/9695608 to your computer and use it in GitHub Desktop.
Matrix determinant calculation by cofactor expansion by Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::int::pow; | |
use std::rand; | |
use std::rand::Rng; | |
struct Matrix { | |
p: ~[int], | |
height: uint, | |
width: uint | |
} | |
// 2D matrix with int elements | |
impl Matrix { | |
fn at(&self, row: uint, col: uint) -> int { | |
self.p[self.width * row + col] | |
} | |
fn dim(&self) -> (uint,uint) { | |
(self.width,self.height) | |
} | |
fn is_square(&self) -> bool { | |
self.width == self.height | |
} | |
fn det(&self) -> Option<int> { | |
if self.is_square() { | |
let (w,_) = self.dim(); | |
match w { | |
2 => | |
match self.p { | |
[a,b,c,d] => Some(a * d - b * c), | |
_ => None | |
}, | |
_ => Some({ | |
let mut s = 0i; | |
for j in range(0,w) { | |
match self.cofactor(0,j) { | |
Some(cf) => s += self.at(0,j) * cf, | |
_ => () | |
} | |
} | |
s | |
}) | |
} | |
} else { | |
None | |
} | |
} | |
fn cofactor(&self, i: uint, j: uint) -> Option<int> { | |
let vs: ~[int] = self.p.iter().enumerate().filter(|&(k,_)| k / self.width != i && k % self.width != j) | |
.map(|(_,&v)| v).collect(); | |
let rest = Matrix{p: vs,height: self.height-1, width: self.width-1}; | |
match rest.det() { | |
Some(d) => { | |
Some(pow(-1,i+j) * d) | |
}, | |
_ => { | |
None | |
} | |
} | |
} | |
} | |
fn mkRnd(dim: uint) -> Matrix { | |
let len = dim * dim; | |
let mut rng = rand::task_rng(); | |
let vs = range(0, len).map(|_| rng.gen_range::<int>(-5,5)).collect(); | |
Matrix{p: vs, width: dim, height: dim} | |
} | |
fn main(){ | |
let m = Matrix{p: ~[1,2,3], width: 1, height: 3}; | |
let ms: ~[Matrix] = range(3,10).map(|n| mkRnd(n as uint)).collect(); | |
for m in ms.iter() { | |
println!("{:?}",m.det()); | |
} | |
println!("{:?}",m.dim()); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment