我试图通过仅使用每行中的 1 个元素来获取 n 行锯齿状二维字符串数组中的每个元素组合。
一个示例数组(每行代表数组中的一行):
“A”、“B”、“C”
“D”、“E”
"F","G","H","I","J"
对于上述数组,将有 30 种可能的组合。欢迎使用递归解决方案,但出于内存使用原因,我更喜欢迭代解决方案。
最佳答案
这是一个使用模数的有趣小方法:
public static void main(String args[]) {
iterate(new String[][]{{"a","b","c"},{"d","e"},{"f","g","h","i"}});
}
static void iterate(String[][] jagged) {
int count = 1;
int[] divisors = new int[jagged.length];
for (int j = 0; j < jagged.length; j++) {
divisors[j] = count;
count *= jagged[j].length;
}
for (int i = 0; i < count; i++) {
String[] combination = new String[jagged.length];
for (int j = 0; j < jagged.length; j++) {
int mod = jagged[j].length;
combination[j] = jagged[j][(i/divisors[j])%mod];
}
process(combination);
}
}
static void process(String[] combination) {
System.out.println(Arrays.toString(combination));
// Do whatever you want here. Process as you go to save memory,
// or add to a list to process later.
}
它的核心是 combination[j] = jagged[j][(i/divisors[j])%mod];
divisors[j]
是较早长度的乘积,即使用较低索引数组的可能组合数。 mod
是当前数组的长度。
如果你希望最后一个元素迭代得更快,第一个元素迭代得更慢,在计算divisors
/count
时将顺序颠倒过来,即count j
从 jagged.length
到 0.
关于java - 从锯齿状数组的每一行添加元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17777985/