Exercise: Nested Arrays

Arrays can contain other arrays:

  1. #![allow(unused)]
  2. fn main() {
  3. let array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
  4. }

What is the type of this variable?

Use an array such as the above to write a function transpose which will transpose a matrix (turn rows into columns):

8.5. Exercise: Nested Arrays - 图1

Copy the code below to https://play.rust-lang.org/ and implement the function. This function only operates on 3x3 matrices.

  1. // TODO: remove this when you're done with your implementation.
  2. #![allow(unused_variables, dead_code)]
  3. fn transpose(matrix: [[i32; 3]; 3]) -> [[i32; 3]; 3] {
  4.     unimplemented!()
  5. }
  6. #[test]
  7. fn test_transpose() {
  8.     let matrix = [
  9.         [101, 102, 103], //
  10.         [201, 202, 203],
  11.         [301, 302, 303],
  12.     ];
  13.     let transposed = transpose(matrix);
  14.     assert_eq!(
  15.         transposed,
  16.         [
  17.             [101, 201, 301], //
  18.             [102, 202, 302],
  19.             [103, 203, 303],
  20.         ]
  21.     );
  22. }
  23. fn main() {
  24.     let matrix = [
  25.         [101, 102, 103], // <-- the comment makes rustfmt add a newline
  26.         [201, 202, 203],
  27.         [301, 302, 303],
  28.     ];
  29.     println!("matrix: {:#?}", matrix);
  30.     let transposed = transpose(matrix);
  31.     println!("transposed: {:#?}", transposed);
  32. }