计算不同 sets 的排列组合
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* inputs: [
* [1, 2],
* ['a', 'b'],
* ['x', 'y']
* ]
*/
function cartesian(...sets) {
return sets.reduce(
(acc, set) => {
const result = []
acc.forEach(a => {
set.forEach(b => {
result.push([...a, b])
})
})
return result
},
[[]]
)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
fn cartesian_product_multiple<T>(sets: &[Vec<T>]) -> Vec<Vec<T>>
where
T: Clone,
{
let mut result = vec![vec![]]; // 初始化结果为包含一个空向量
for set in sets {
let mut new_result = Vec::new();
for r in &result {
for item in set {
let mut new_pair = r.clone();
new_pair.push(item.clone());
new_result.push(new_pair);
}
}
result = new_result;
}
result
}