summaryrefslogtreecommitdiff
path: root/src/types/matrix.rs
blob: 2973ce1236ceed47cd2dbf79573a700d11fd9414 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
use std::{fmt::Display, ops::Add, str::FromStr};

use super::matrix_err::{MatrixSetValueError, ParseMatrixError};
/// A Matrix struct
///
/// 
#[derive(Debug, PartialEq, Eq)]
pub struct Matrix {
    pub nrows: usize,
    pub ncols: usize,
    pub data: Vec<Vec<i32>>,
}


impl FromStr for Matrix {
    type Err = ParseMatrixError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut d: Vec<Vec<i32>> = Vec::new();
        let rows_iter = s.split('\n');
        for txt in rows_iter {
            let mut r: Vec<i32> = Vec::new();
            for ch in txt.split(',') {
                let parsed = match i32::from_str(ch) {
                    Ok(n) => Ok(n),
                    Err(_e) => Err(ParseMatrixError),
                };
                r.push(parsed?);
            }
            d.push(r);
        }
       Ok(Matrix::new(d))
    }
}

impl Display for Matrix {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut builder = String::new();
        for (i, r) in self.data.iter().enumerate() {
            let mut row_str = if i == 0 || i == self.nrows - 1 {
                "+".to_string()
            } else {
                "|".to_string()
            };
            for (j, n) in r.iter().enumerate() {
                row_str += &format!("{}{}", n, if j == self.ncols - 1 { "" } else { "," });
            }
            row_str += if i == 0 || i == self.nrows - 1 {
                "+\n"
            } else {
                "|\n"
            };
            builder += &row_str;
        }
        write!(f, "{}", builder)
    }
}
impl<'a, 'b> Add<&'b Matrix> for &'a Matrix {
    type Output = Matrix;
    fn add(self, rhs: &'b Matrix) -> Self::Output {
        if (self.nrows != rhs.nrows) || (self.ncols != rhs.ncols) { panic!("Cannot add two matrices with different dimensions"); }
        let mut x = Matrix {
            nrows: self.nrows,
            ncols: self.ncols,
            data: self.data.clone(),
        };
        for (i, r) in rhs.data.iter().enumerate() {
            for (j, n) in r.iter().enumerate() {
                x.data[i][j] += n;
            }
        } 
        x
    }
}


impl Matrix {

    /// Matrix initialiser function
    pub fn new(data: Vec<Vec<i32>>) -> Matrix {
        Matrix {
            nrows: data.len(),
            ncols: data[0].len(),
            data,
        }
    }
    pub fn get(&self, row_index: usize, column_index: usize) -> Option<i32> {
        let r = self.data.get(row_index)?;
        let n = r.get(column_index)?;
        Some(*n)
    }
    pub fn set(&mut self, row_index: usize, column_index: usize, new_data: i32) -> Result<(), MatrixSetValueError> {
        self.data[row_index][column_index] = new_data;
        Ok(())
    }
    pub fn is_square(&self) -> bool {
        self.nrows == self.ncols
    }
    fn splice(&self, at_index: usize) -> Matrix {
        let mut data: Vec<Vec<i32>> = Vec::new();
        for i in 0..self.data.len() {
            if i == 0 {
                continue;
            }
            let mut r: Vec<i32> = Vec::new();
            for j in 0..self.data[i].len() {
                if j == at_index {
                    continue;
                }
                r.push(self.data[i][j]);
            }
            data.push(r);
        }
        Matrix::new(data)
    }
    pub fn determinant(&self) -> i32 {
        if !self.is_square() { panic!() };
        if self.nrows == 2 && self.ncols == 2 {
            return self.data[0][0] * self.data[1][1] - self.data[0][1] * self.data[1][0];
        }
        let mut tmp = 0;
        for (i, n) in self.data[0].iter().enumerate() {
            let mult = if i % 2 == 0 { -*n } else { *n };
            let eval = self.splice(i).determinant();
            // println!("tmp result: {}", mult * eval);
            tmp += mult * eval;
            // println!("tmp: {}", tmp);
        }
        tmp
    }
    pub fn transpose(&self) -> Matrix {
        let mut new_data = Vec::<Vec<i32>>::new();
        for i in 0..self.nrows {
            let mut new_row = Vec::<i32>::new();
            for j in 0..self.ncols {
                new_row.push(self.data[j][i]);
            }
            new_data.push(new_row);
        }
        Matrix {
            nrows: self.ncols,
            ncols: self.nrows,
            data: new_data,
        }
    }
}