DEV Community

Discussion on: Daily Challenge #72 - Matrix Shift

Collapse
 
brightone profile image
Oleksii Filonenko • Edited

Rust:

fn shift<T: Clone>(matrix: Vec<Vec<T>>, n: usize) -> Vec<Vec<T>> {
    match matrix.get(1).map(|row| row.len()) {
        None => matrix,
        Some(len) => {
            let mut flat = matrix.into_iter().flatten().collect::<Vec<_>>();
            flat.rotate_right(n);
            flat.chunks_exact(len).map(|chunk| chunk.to_vec()).collect()
        }
    }
}

The match allows for this test to pass:

#[test]                                                                    
fn test_empty_1() {                                                        
    assert_eq!(shift(Vec::<Vec<char>>::new(), 1), Vec::<Vec<char>>::new());
}