diff --git a/src/lib.rs b/src/lib.rs index c2fc7f7..f83869b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -624,6 +624,21 @@ impl Grid { pub fn into_vec(self) -> Vec { self.data } + + /// Transpose the grid so that columns become rows in new grid. + pub fn transpose(&self) -> Grid { + let mut data = Vec::with_capacity(self.data.len()); + for c in 0..self.cols { + for r in 0..self.rows { + data.push(self[r][c].clone()); + } + } + Grid { + data, + cols: self.rows, + rows: self.cols, + } + } } impl Clone for Grid { @@ -1126,4 +1141,10 @@ mod test { let grid = Grid::init(1, 2, 3); assert_eq!(grid.size(), (1, 2)); } + + #[test] + fn transpose() { + let grid: Grid = grid![[1,2,3][4,5,6]]; + assert_eq!(format!("{:?}", grid.transpose()), "[[1, 4][2, 5][3, 6]]"); + } }