From 365cacbd42cdf82126a1ee92edaf1f6c2e6a67a3 Mon Sep 17 00:00:00 2001 From: Gleb Koval Date: Tue, 31 May 2022 22:54:52 +0100 Subject: [PATCH] reshape-the-matrix --- reshape-the-matrix/sol_functional.rs | 20 ++++++++++++++++++++ reshape-the-matrix/sol_loops.rs | 17 +++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 reshape-the-matrix/sol_functional.rs create mode 100644 reshape-the-matrix/sol_loops.rs diff --git a/reshape-the-matrix/sol_functional.rs b/reshape-the-matrix/sol_functional.rs new file mode 100644 index 0000000..c52de94 --- /dev/null +++ b/reshape-the-matrix/sol_functional.rs @@ -0,0 +1,20 @@ +// This is a more functional solution that I think +// is a bit easier to read, but does iterate over +// the matrix twice (two `Iter.collect()`s). So without +// compiler optimisations it might be a bit slower. +// +// I don't actually know whether this is true or not. +impl Solution { + pub fn matrix_reshape(mat: Vec>, r: i32, c: i32) -> Vec> { + let (m, n) = (mat.len(), mat[0].len()); + if m*n != (r*c) as usize || m == r as usize{ + return mat; + } + mat.into_iter() + .flatten() + .collect::>() + .chunks(c as usize) + .map(|row| row.to_vec()) + .collect::>() + } +} \ No newline at end of file diff --git a/reshape-the-matrix/sol_loops.rs b/reshape-the-matrix/sol_loops.rs new file mode 100644 index 0000000..d40ab58 --- /dev/null +++ b/reshape-the-matrix/sol_loops.rs @@ -0,0 +1,17 @@ +// A solution using loops and still pretty +// easy to understand, and iterates over the +// matrix only once. +impl Solution { + pub fn matrix_reshape(mat: Vec>, r: i32, c: i32) -> Vec> { + let (m, n) = (mat.len(), mat[0].len()); + let (r, c) = (r as usize, c as usize); + if m*n != r*c || m == r { + return mat; + } + let mut reshaped_matrix = vec![vec![0; c]; r]; + for idx in (0..m*n) { + reshaped_matrix[idx / c][idx % c] = mat[idx / n][idx % n]; + } + reshaped_matrix + } +} \ No newline at end of file