java - 从锯齿状数组的每一行添加元素

标签 java arrays permutation jagged-arrays

我试图通过仅使用每行中的 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 jjagged.length 到 0.

关于java - 从锯齿状数组的每一行添加元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17777985/

相关文章:

python - 比提供的解决方案更快地获取排列索引和索引处的排列

将 bbcode 转换为 javadoc 的 Java IDE 插件或外部工具(ant、maven、独立)?

java - NiftyGui - 如何改变面板的大小

java - IText 7 - 删除 PDF 图层 (OCG)

javascript - jquery延迟函数与IF语句

arrays - 在 ruby​​ 中实现的算法将 1 添加到表示为数组的数字

php - 从 json_decode 获取数组结果

java - 使用 BouncyCaSTLe 签署消息摘要

arrays - [1 2 .. N] 排列的最长递增子序列

ruby - Python itertools 的 Ruby 等价物是什么,尤其是。组合/排列/groupby?