summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorZhongheng Liu <z.liu@outlook.com.gr>2025-01-22 12:57:22 +0200
committerZhongheng Liu <z.liu@outlook.com.gr>2025-01-22 12:57:22 +0200
commit9a3a05ce557f868f4d8db2938d5a1450404ca92b (patch)
tree71b9c0a0d0d2cd6321738677467f958c5eda0a45
parent8bb435ab105e3f7f1374059dfd9365132167646d (diff)
downloadmatrix-rs-9a3a05ce557f868f4d8db2938d5a1450404ca92b.tar.gz
matrix-rs-9a3a05ce557f868f4d8db2938d5a1450404ca92b.tar.bz2
matrix-rs-9a3a05ce557f868f4d8db2938d5a1450404ca92b.zip
feat: add display trait to matrix
-rw-r--r--src/types/matrix.rs24
1 files changed, 23 insertions, 1 deletions
diff --git a/src/types/matrix.rs b/src/types/matrix.rs
index ff292fc..371d5df 100644
--- a/src/types/matrix.rs
+++ b/src/types/matrix.rs
@@ -1,10 +1,32 @@
-use std::str::FromStr;
+use std::{fmt::Display, str::FromStr};
/// Matrix
pub struct Matrix {
pub nrows: usize,
pub ncols: usize,
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 {
pub fn new(data: Vec<Vec<i32>>) -> Matrix {
Matrix {