use core::panic; use fractions::Fraction; use std::fmt::{Debug, Display}; use std::ops::Add; use std::ops::Mul; use std::ops::Sub; #[derive(Debug, Eq, PartialEq)] pub enum MatrixError { IndexOutOfRange, RowOutOfRange, ColumnOutOfRange, NotSquared, InvalidDataSize, InvalidSizeForAdd, InvalidSizeForSub, InvalidSizeForMul, ZeroSize, } #[derive(PartialEq, Eq, Debug)] pub struct Matrix { rows: usize, columns: usize, data: Vec, } impl Matrix { pub fn new(rows: usize, columns: usize, default: Fraction) -> Self { Self { rows, columns, data: vec![default; rows * columns], } } pub fn get(&self, row: usize, column: usize) -> &Fraction { if row >= self.rows || column >= self.columns { panic!("Index given is out of range.") } let mut index = 0; index += row * self.columns; index += column; return &self.data[index]; } pub fn get_row(&self, row: usize) -> Vec { if row >= self.rows { panic!("Row index is out of bounds."); } let mut index = 0; let mut data = Vec::new(); index += self.columns * row; for i in 0..self.columns { data.push(self.data[index + i]); } return data; } pub fn get_column(&self, column: usize) -> Vec { if column >= self.columns { panic!("Column index is out of bounds."); } let index = column; let mut data = Vec::new(); for i in 0..self.rows { data.push(self.data[(i * self.columns) + index]) } return data; } pub fn get_diagonal(&self) -> Vec { if self.columns != self.rows { panic!("The matrix needs to be squared for getting diagonal.") } let mut data = Vec::new(); let mut index; for i in 0..self.columns { index = i + (i * self.columns); data.push(self.data[index]); } return data; } pub fn set(&mut self, row: usize, column: usize, data: Fraction) -> () { if row >= self.rows || column >= self.columns { panic!("Index given is out of range.") } let mut index = 0; index += row * self.columns; index += column; self.data[index] = data; return; } pub fn set_row(&mut self, row: usize, data: Vec) -> () { if row >= self.rows { panic!("Row index given is out of bounds.") } if data.len() != self.columns { panic!("Data is not the required size") } for i in 0..data.len() { self.set(row, i, data[i]); } } pub fn set_column(&mut self, column: usize, data: Vec) -> () { if column >= self.columns { panic!("Column index given is out of bouds.") } if data.len() != self.rows { panic!("Data is not the required size") } for i in 0..data.len() { self.set(i, column, data[i]); } } pub fn exchange_rows(&mut self, row1: usize, row2: usize) -> () { if row1 >= self.rows || row2 >= self.rows { panic!("Row index is out of bounds."); } //Get copy of row2 let temp = self.get_row(row2); let mut index1 = 0; let mut index2 = 0; //Move from row1 to row2 index1 += self.columns * row1; index2 += self.columns * row2; for i in 0..self.columns { self.data[index2 + i] = self.data[index1 + i]; self.data[index1 + i] = temp[i]; } } pub fn exchange_columns(&mut self, column1: usize, column2: usize) -> () { if column1 >= self.columns || column2 >= self.columns { panic!("Column index is out of bounds.") } //Get copy of column2 let temp = self.get_column(column2); for i in 0..self.rows { self.data[column2 + (i * self.columns)] = self.data[column1 + (i * self.columns)]; self.data[column1 + (i * self.columns)] = temp[i]; } } pub fn get_determinant(&self) -> Fraction { if self.rows != self.columns { panic!("Only nxn matrixes can have a determinant."); } let mut trig_matrix = Matrix { columns: self.columns, rows: self.rows, data: self.data.clone(), }; let mut sign = Fraction::new(1, 1).unwrap(); for i in 0..self.columns { let mut max_row = i; let mut max_value = trig_matrix.get(i, i).abs(); // We do parcial pivoting to avoid getting insane // numbers that may result in overflow with fractions for r in (i + 1)..self.rows { let val = trig_matrix.get(r, i).abs(); if val > max_value { max_value = val; max_row = r; } } // If there ain't no other thing but 0 then we're // fucked, determinant is zero if max_value.is_zero() { return Fraction::new(0, 1).unwrap(); } if max_row != i { trig_matrix.exchange_rows(i, max_row); sign = -sign; } let pivot = *trig_matrix.get(i, i); // The main gaussian elimination, not even I remember how // i did it in such a asimple way for x in (i + 1)..trig_matrix.rows { let m = (*trig_matrix.get(x, i) / pivot).unwrap(); let new_row = trig_matrix .get_row(x) .iter() .zip(trig_matrix.get_row(i).iter()) .map(|(a, b)| *a - m * *b) .collect::>(); trig_matrix.set_row(x, new_row); } } // YES, now we got ourselves a triangular matrix, now we just // take the product of the diagonal and multiply by sign, that's // the determinant :) let determinant = sign * trig_matrix .get_diagonal() .iter() .copied() .fold(Fraction::from(1i64), |acc, x| acc * x); return determinant; } } impl Add for Matrix { type Output = Self; fn add(self, other: Self) -> Self::Output { if self.data.len() != other.data.len() { panic!("Matrix size is inadecuate."); } let mut new_data = Vec::new(); for i in 0..self.data.len() { new_data.push(self.data[i] + other.data[i]); } Matrix { columns: self.columns, rows: self.rows, data: new_data, } } } impl Sub for Matrix { type Output = Self; fn sub(self, other: Self) -> Self::Output { if self.data.len() != other.data.len() { panic!("Matrix size is inadecuate."); } let mut new_data = Vec::new(); for i in 0..self.data.len() { new_data.push(self.data[i] - other.data[i]); } Matrix { columns: self.columns, rows: self.rows, data: new_data, } } } impl Mul for Matrix { type Output = Self; fn mul(self, other: Self) -> Self::Output { if self.columns != other.rows { panic!("Matrix dimentions are inadecuate."); } let mut new_data: Vec = Vec::new(); for i in 0..self.rows { let current_row = self.get_row(i); for k in 0..other.columns { let current_column = other.get_column(k); let mut new_value = Fraction::new(0, 1).unwrap(); for (a, b) in current_row.iter().zip(current_column.iter()) { new_value = new_value + (*a * *b); } new_data.push(new_value); } } Matrix { rows: self.rows, columns: other.columns, data: new_data, } } } impl Display for Matrix { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut display = String::new(); let mut index = 0; for _i in 0..self.columns { display += "{"; for _k in 0..self.rows { display += &format!(" {},", self.data[index]); index += 1; } display += " }\n"; } write!(f, "{}", display) } } #[cfg(test)] mod tests { use super::*; }