From f749b2c921e21249a8ee192aed0fc44ace20a60b Mon Sep 17 00:00:00 2001 From: Palash Tyagi <23239946+Magnus167@users.noreply.github.com> Date: Sun, 6 Jul 2025 17:38:24 +0100 Subject: [PATCH] Add method to retrieve a specific row from the matrix and corresponding tests --- src/matrix/mat.rs | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/matrix/mat.rs b/src/matrix/mat.rs index bf4265b..dbae21a 100644 --- a/src/matrix/mat.rs +++ b/src/matrix/mat.rs @@ -179,6 +179,21 @@ impl Matrix { self.cols -= 1; } + #[inline] + pub fn row(&self, r: usize) -> Vec { + assert!( + r < self.rows, + "row index {} out of bounds for {} rows", + r, + self.rows + ); + let mut row_data = Vec::with_capacity(self.cols); + for c in 0..self.cols { + row_data.push(self[(r, c)].clone()); // Clone each element + } + row_data + } + /// Deletes a row from the matrix. Panics on out-of-bounds. /// This is O(N) where N is the number of elements, as it rebuilds the data vec. pub fn delete_row(&mut self, row: usize) { @@ -1130,6 +1145,21 @@ mod tests { matrix[(0, 3)] = 99; } + #[test] + fn test_row() { + let ma = static_test_matrix(); + assert_eq!(ma.row(0), &[1, 4, 7]); + assert_eq!(ma.row(1), &[2, 5, 8]); + assert_eq!(ma.row(2), &[3, 6, 9]); + } + + #[test] + #[should_panic(expected = "row index 3 out of bounds for 3 rows")] + fn test_row_out_of_bounds() { + let ma = static_test_matrix(); + ma.row(3); + } + #[test] fn test_column() { let matrix = static_test_matrix_2x4();