Skip to content

Instantly share code, notes, and snippets.

@shirts
Created October 22, 2023 04:52
Show Gist options
  • Save shirts/819e4157b0a5b92e47a2e519e02dab33 to your computer and use it in GitHub Desktop.
Save shirts/819e4157b0a5b92e47a2e519e02dab33 to your computer and use it in GitHub Desktop.
Rust transpose
pub fn transpose(matrix: [[i32; 3]; 3]) -> [[i32; 3]; 3] {
let mut transposed: [[i32; 3]; 3] = [[0; 3]; 3];
for i in 0..matrix.len() {
for j in 0..matrix[i].len() {
transposed[i][j] = matrix[j][i];
}
}
transposed
}
fn pretty_print(matrix: &[[i32; 3]; 3]) {
for row in matrix {
println!("{row:?}");
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn transpose_return_value() {
let matrix = [
[1, 4, 7],
[2, 5, 8],
[3, 6, 9]
];
assert_eq!(transpose(matrix), [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]);
}
}
fn main() {
let matrix = [
[101, 102, 103],
[201, 202, 203],
[301, 302, 303],
];
println!("matrix:");
pretty_print(&matrix);
println!("transposed:");
pretty_print(&transpose(matrix));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment