Jump to content

Ordered partitions: Difference between revisions

Add Rust implementation
(Add Rust implementation)
Line 2,375:
[[2, 4], [], [1, 3]]
[[3, 4], [], [1, 2]]
</pre>
 
=={{header|Rust}}==
<lang rust>
use itertools::Itertools;
 
type NArray = Vec<Vec<Vec<usize>>>;
 
fn generate_partitions(args: &[usize]) -> NArray {
// calculate the sum of all partitions
let max = args.iter().sum();
 
// generate combinations with the given lengths
// for each partition
let c = args.iter().fold(vec![], |mut acc, arg| {
acc.push((1..=max).combinations(*arg).collect::<Vec<_>>());
acc
});
 
// create a cartesian product of all individual combinations
// filter/keep only where all the elements are there and exactly once
c.iter()
.map(|i| i.iter().cloned())
.multi_cartesian_product()
.unique()
.filter(|x| x.iter().cloned().flatten().unique().count() == max)
.collect::<Vec<_>>()
}
 
#[allow(clippy::clippy::ptr_arg)]
fn print_partitions(result: &NArray) {
println!("Partitions:");
for partition in result {
println!("{:?}", partition);
}
}
fn main() {
print_partitions(generate_partitions(&[2, 0, 2]).as_ref());
print_partitions(generate_partitions(&[1, 1, 1]).as_ref());
print_partitions(generate_partitions(&[2, 3]).as_ref());
print_partitions(generate_partitions(&[0]).as_ref());
}
</lang>
{{out}}
<pre>
Partitions:
[[1, 2], [], [3, 4]]
[[1, 3], [], [2, 4]]
[[1, 4], [], [2, 3]]
[[2, 3], [], [1, 4]]
[[2, 4], [], [1, 3]]
[[3, 4], [], [1, 2]]
Partitions:
[[1], [2], [3]]
[[1], [3], [2]]
[[2], [1], [3]]
[[2], [3], [1]]
[[3], [1], [2]]
[[3], [2], [1]]
Partitions:
[[1, 2], [3, 4, 5]]
[[1, 3], [2, 4, 5]]
[[1, 4], [2, 3, 5]]
[[1, 5], [2, 3, 4]]
[[2, 3], [1, 4, 5]]
[[2, 4], [1, 3, 5]]
[[2, 5], [1, 3, 4]]
[[3, 4], [1, 2, 5]]
[[3, 5], [1, 2, 4]]
[[4, 5], [1, 2, 3]]
Partitions:
[[]]
</pre>
 
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.