commit
8381f2c3fb
1 changed files with 21 additions and 0 deletions
21
src/lib.rs
21
src/lib.rs
|
@ -624,6 +624,21 @@ impl<T: Clone> Grid<T> {
|
|||
pub fn into_vec(self) -> Vec<T> {
|
||||
self.data
|
||||
}
|
||||
|
||||
/// Transpose the grid so that columns become rows in new grid.
|
||||
pub fn transpose(&self) -> Grid<T> {
|
||||
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<T: Clone> Clone for Grid<T> {
|
||||
|
@ -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<u8> = grid![[1,2,3][4,5,6]];
|
||||
assert_eq!(format!("{:?}", grid.transpose()), "[[1, 4][2, 5][3, 6]]");
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue