Here's a way to do it recursively with minimal storage, and without needing to make copies, by passing a closure to handle each partition as it is generated:
fn iterate_all_subdivisions<'a, T, F>(head: &mut Vec<&'a [T]>, rest: &'a [T], f: &mut F)
where
F: FnMut(&[&[T]]),
{
if rest.len() == 0 {
f(head);
} else {
for i in 1..=rest.len() {
let (next, tail) = rest.split_at(i);
head.push(next);
iterate_all_subdivisions(head, tail, f);
head.pop();
}
}
}
fn main() {
let v: Vec<i32> = vec![1, 2, 3];
iterate_all_subdivisions(&mut Vec::new(), &v, &mut |x| println!("{:?}", x));
}
This will output:
[[1], [2], [3]]
[[1], [2, 3]]
[[1, 2], [3]]
[[1, 2, 3]]
If you do want to accumulate all the partitions into a Vec
, you could do it like this:
fn main() {
let v: Vec<i32> = vec![1, 2, 3];
let mut results: Vec<Vec<Vec<i32>>> = Vec::new();
iterate_all_subdivisions(&mut Vec::new(), &v, &mut |x| {
results.push(x.iter().map(|y| y.to_vec()).collect());
});
println!("{:?}", results);
}
This will output
[[[1], [2], [3]], [[1], [2, 3]], [[1, 2], [3]], [[1, 2, 3]]]