Exercise: Nested Arrays
Arrays can contain other arrays:
// Copyright 2023 Google LLC
// SPDX-License-Identifier: Apache-2.0
let array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
What is the type of this variable?
Use an array such as the above to write a function transpose that transposes a matrix (turns rows into columns):
Copy the code below to https://play.rust-lang.org/ and implement the function. This function only operates on 3×3 matrices.
// Copyright 2023 Google LLC
// SPDX-License-Identifier: Apache-2.0
fn transpose(matrix: [[i32; 3]; 3]) -> [[i32; 3]; 3] {
todo!()
}
fn main() {
let matrix = [
[101, 102, 103], // <-- the comment makes rustfmt add a newline
[201, 202, 203],
[301, 302, 303],
];
println!("Original:");
for row in matrix {
println!("{row:?}");
}
let transposed = transpose(matrix);
println!("\nTransposed:");
for row in transposed {
println!("{row:?}");
}
}