So I have a Vec<Vec<T>> where the first vector groups by hours of day and the inner vector by days of week. I would like to transpose somehow the vectors to have it first by days then by hours. Is there a simple way to do it in Rust?
EDIT: I mean, I know how to do it with 2 for loops but is there a smarter/shorter way to do it functionally
You can use some iterators:
fn transpose<T>(v: Vec<Vec<T>>) -> Vec<Vec<T>>
where
T: Clone,
{
assert!(!v.is_empty());
(0..v[0].len())
.map(|i| v.iter().map(|inner| inner[i].clone()).collect::<Vec<T>>())
.collect()
}
As user4815162342 comments, here is a version without Clone:
fn transpose2<T>(v: Vec<Vec<T>>) -> Vec<Vec<T>> {
assert!(!v.is_empty());
let len = v[0].len();
let mut iters: Vec<_> = v.into_iter().map(|n| n.into_iter()).collect();
(0..len)
.map(|_| {
iters
.iter_mut()
.map(|n| n.next().unwrap())
.collect::<Vec<T>>()
})
.collect()
}
Playground
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With