fix: fixed row/column check in add
This commit is contained in:
parent
e0f006dcf4
commit
d59f83753e
2 changed files with 45 additions and 5 deletions
27
src/main.rs
27
src/main.rs
|
|
@ -1,8 +1,31 @@
|
|||
use std::io::stdin;
|
||||
|
||||
use types::matrix::Matrix;
|
||||
|
||||
mod types;
|
||||
fn handle_input() -> Matrix {
|
||||
let input = stdin();
|
||||
let c = true;
|
||||
let mut construct_string = String::from("");
|
||||
while c {
|
||||
let mut s = "".to_string();
|
||||
let _ = input.read_line(&mut s);
|
||||
if s == "exit\n" { break; }
|
||||
construct_string += &s;
|
||||
}
|
||||
// println!("Constructed \"{}\"", construct_string.trim_end());
|
||||
Matrix::from_str(construct_string.trim_end().to_string())
|
||||
}
|
||||
fn main() {
|
||||
// println!("Hello, world!");
|
||||
let m = Matrix::from_str("1,2,3\n4,5,6\n7,8,9".to_string());
|
||||
println!("Matrix:\n{}Has determinant:{}",m, m.determinant());
|
||||
let m1 = Matrix::from_str("1,2,3\n4,5,6\n7,8,9".to_string());
|
||||
let m2 = Matrix::from_str("1,1,1\n1,1,1".to_string());
|
||||
let m4d = Matrix::from_str("1,2,3,4\n5,6,7,8\n9,18,11,12\n13,14,15,15".to_string());
|
||||
println!("Matrix:\n{}Has determinant:{}",&m1, &m1.determinant());
|
||||
println!("det(m4d): {}", &m4d.determinant());
|
||||
let mi = handle_input();
|
||||
println!("m from input:\n{}", mi);
|
||||
// println!("row: {}, col: {}", mi.nrows, mi.ncols);
|
||||
// println!("row: {}, col: {}", m2.nrows, m2.ncols);
|
||||
println!("{}", &mi+&m2);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
use std::{fmt::Display, str::FromStr};
|
||||
use std::{fmt::Display, ops::Add, str::FromStr};
|
||||
/// Matrix
|
||||
pub struct Matrix {
|
||||
pub nrows: usize,
|
||||
|
|
@ -27,11 +27,28 @@ impl Display for Matrix {
|
|||
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 {
|
||||
pub fn new(data: Vec<Vec<i32>>) -> Matrix {
|
||||
Matrix {
|
||||
nrows: data[0].len(),
|
||||
ncols: data.len(),
|
||||
nrows: data.len(),
|
||||
ncols: data[0].len(),
|
||||
data,
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue