我怎样才能找到所有包含1元的从一个可变数目的可变长度的阵列的排列?
我有一个数组 U
阵列 D
是长短不一的。我需要能够返回数组索引的所有排列,将选择不同的排列由来自每套1元。我还要求该alorithm被重新presented作为一个对象,它仅记住最后排列,并返回下一个排列用get_next方法
I have an array U
of arrays D
that vary in length. I need to be able to return all permutations of array indices that would select a different permutation consisting of 1 element from each set. I also require that this alorithm gets represented as an object that only remembers the last permutation, and returns the next permutation with a get_next method.
例如, U = [array_of_size_n1,array_of_size_n2,array_of_size_n3]
会有 N1 * N2 * N3
排列,每个 3 元素长。
For instance, U = [array_of_size_n1, array_of_size_n2, array_of_size_n3]
There would be n1*n2*n3
permutations, each 3 elements long.
编辑:的组数也各不相同。
如果您使用的是蟒蛇,这是标准库的一部分: itertools.product
。但是,假设你没有,这里是一个伪code版本。
If you're using python, this is part of the standard library: itertools.product
. But assuming you're not, here's a pseudocode version.
// Create an initialised array of indexes.
int[] index0(arrays) {
// We require all arrays to be non-empty.
for a in arrays {
assert len(a) != 0;
}
return new int[len(arrays)];
}
// Increment the indices. Returns false when the indices wrap round to the start.
bool next_index(indices, arrays) {
for (i = len(indices) - 1; i >= 0; --i) {
indices[i] += 1
if indices[i] < len(arrays[i]) {
return true;
}
indices[i] = 0;
}
return false;
}
您可以使用它像这样(假设没有你的阵列是空的)。这个例子打印出的数组元素的每个组合。
You can use it like this (assuming none of your arrays are empty). This example prints out every combination of elements from the arrays.
indices = index0(arrays);
{
for (i = 0; i < len(arrays); ++i) {
print arrays[i][indices[i]];
}
print
} while next_index(indices);