The question says "I know how to do it with 2 for loops but is there a smarter/shorter way to do it functionally", however that it is probably the best answer for the title. Here's a two-for
-loop solution that avoids T: Clone
and avoids allocating a scratch Vec
for iterators:
fn transpose<T>(original: Vec<Vec<T>>) -> Vec<Vec<T>> {
assert!(!original.is_empty());
let mut transposed = (0..original[0].len()).map(|_| vec![]).collect::<Vec<_>>();
for original_row in original {
for (item, transposed_row) in original_row.into_iter().zip(&mut transposed) {
transposed_row.push(item);
}
}
transposed
}
Someone could probably make it more "functional" than I, but this is already a bit difficult to read, try as I might.
T
, maybe aDateTime
? Can you show an example of input with the desired output? – Tragic