feat: add display trait to matrix

This commit is contained in:
Zhongheng Liu 2025-01-22 12:57:22 +02:00
commit 9a3a05ce55
Signed by: steven
GPG key ID: 805A28B071DAD84B

View file

@ -1,10 +1,32 @@
use std::str::FromStr; use std::{fmt::Display, str::FromStr};
/// Matrix /// Matrix
pub struct Matrix { pub struct Matrix {
pub nrows: usize, pub nrows: usize,
pub ncols: usize, pub ncols: usize,
pub data: Vec<Vec<i32>>, pub data: Vec<Vec<i32>>,
} }
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 Matrix { impl Matrix {
pub fn new(data: Vec<Vec<i32>>) -> Matrix { pub fn new(data: Vec<Vec<i32>>) -> Matrix {
Matrix { Matrix {