summaryrefslogtreecommitdiff
path: root/src/matrix.rs
blob: 9227917b15c5c808060d3b9f177708cc3cfe14f5 (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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
//! Matrix struct and relevant implementations.
//!
//! Example usage - addition of two matrices:
//! ```
//! use matrix::Matrix;
//! use std::str::FromStr;
//! let m1 = Matrix::from_str("1,2\n3,4").expect("Expect parse correct");
//! let m2 = Matrix::from_str("1,1\n1,1").expect("Expect parse correct");
//! let m_add = &m1 + &m2;
//! println!("m1 + m2 =\n{}", m_add);
//! ```
//! TODO:: Create matrix multiplication method

use std::{fmt::Display, ops::{Add, Mul, Sub}, str::FromStr};

use crate::error::{MatrixSetValueError, ParseMatrixError};
#[derive(Debug, PartialEq, Eq)]
pub struct Matrix {
    /// Number of rows in matrix.
    pub nrows: usize,
    
    /// Number of columns in matrix.
    pub ncols: usize,
    
    /// Data stored in the matrix, you should not access this directly
    data: Vec<Vec<i32>>,
}
impl Matrix {
    /// Matrix initialiser function.
    ///
    /// Accepts a new array of data as a list of rows.
    ///
    /// TODOs
    /// - Add row length check
    pub fn new(data: Vec<Vec<i32>>) -> Matrix {
        Matrix {
            nrows: data.len(),
            ncols: data[0].len(),
            data,
        }
    }
    /// Query one element at selected position.
    ///
    /// Returns `None` if index is out of bounds.
    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)
    }

    /// Update one element at selected position.
    ///
    /// Returns `Err()` if index is out of bounds.
    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(())
    }

    /// Checks if this is a square matrix.
    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)
    }

    /// Evaluates any N-by-N matrix.
    ///
    /// This function panics if the matrix is not square!
    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();
            tmp += mult * eval;
        }
        tmp
    }

    /// Evaluates the tranpose of the matrix.
    ///
    /// Each row becomes a column, each column becomes a row.
    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,
        }
    }
}

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<'a, 'b> Sub<&'b Matrix> for &'a Matrix {
    type Output = Matrix;
    fn sub(self, rhs: &'b Matrix) -> Self::Output {
        todo!()
    }
    }
impl<'a, 'b> Mul<&'b Matrix> for &'a Matrix {
    type Output = Matrix;
    fn mul(self, rhs: &'b Matrix) -> Self::Output {
        fn reduce(lhs: &Matrix, rhs: &Matrix, at_r: usize, at_c: usize) -> i32 {
            let mut tmp = 0;
            for i in 0..lhs.ncols {
                tmp += lhs.get(at_r, i).unwrap() * rhs.get(i, at_c).unwrap();
            }
            tmp
        }
        let mut d: Vec<Vec<i32>> = Vec::new();
        if self.ncols != rhs.nrows {
            println!("LHS: \n{}RHS: \n{}", self, rhs);
            println!("LHS nrows: {} ;; RHS ncols: {}", self.nrows, rhs.ncols);
            panic!()
        }
        for i in 0..self.nrows {
            let mut r: Vec<i32> = Vec::new();
            for j in 0..rhs.ncols {
                r.push(reduce(self, rhs, i, j));
            }
            d.push(r);
        }
        Matrix::new(d)
    }
}

impl From<Vec<i32>> for Matrix {
    fn from(value: Vec<i32>) -> Self {
        Matrix {
            nrows: value.len(),
            ncols: 1,
            data: vec![value],
        }
    }
}