Merge pull request #4 from J-F-Liu/master

Add transpose() method
This commit is contained in:
Armin Becher 2021-07-23 12:21:44 +02:00 committed by GitHub
commit 8381f2c3fb
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -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]]");
}
}