rust files + matrix implementation

This commit is contained in:
Sam Hadow 2025-04-02 14:22:54 +02:00
parent 949ca79e9e
commit 0543464d56
4 changed files with 73 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/target

8
Cargo.toml Normal file
View File

@ -0,0 +1,8 @@
[package]
name = "approximate-gcd"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

5
src/main.rs Normal file
View File

@ -0,0 +1,5 @@
mod matrix;
fn main() {
println!("");
}

59
src/matrix.rs Normal file
View File

@ -0,0 +1,59 @@
type Element = f64;
use std::ops::{Index, IndexMut};
#[derive(Debug, PartialEq)]
pub struct Matrix {
pub n: usize,
values: Vec<Element>,
}
impl Matrix {
pub fn new(n: usize, values: Vec<Element>) -> Option<Self> {
if n.pow(2) == values.len() {
Some(Matrix { n, values })
} else {
None
}
}
}
impl Index<(usize, usize)> for Matrix {
type Output = f64;
fn index(&self, index: (usize, usize)) -> &Self::Output {
&self.values[(self.n * index.0) + index.1]
}
}
impl IndexMut<(usize, usize)> for Matrix {
fn index_mut(&mut self, index: (usize, usize)) -> &mut Self::Output {
&mut self.values[(self.n * index.0) + index.1]
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn simple_matrix() {
assert_eq!(
Matrix {
n: 2,
values: Vec::from([1.0, 2.0, 3.0, 4.0])
},
Matrix::new(2, Vec::from([1.0, 2.0, 3.0, 4.0])).unwrap()
);
assert!(Matrix::new(3, Vec::from([1.0, 2.0])).is_none());
}
#[test]
fn indexes() {
let mut m = Matrix::new(2, vec![1.0, 2.0, 3.0, 4.0]).unwrap();
assert_eq!(m[(0, 0)], 1.0);
assert_eq!(m[(1, 0)], 3.0);
m[(1, 0)] = 5.0;
assert_eq!(m[(1, 0)], 5.0);
}
}