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);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…