首页 > 解决方案 > 仅使用一个字符在字符串列表上生成排列

问题描述

我正在尝试使用一次取一个字符的字符串列表来生成排列。下面是我想要的输入和输出代码。我们可以简单地迭代吗?我也没有找到确切的方法。

String[] lst = new String[]{"abc", "def", "ghi"}; //Given
String[] permutations = new String[]{ //To Generate
            "adg", "adh", "adi",
            "aeg", "aeh", "aei",
            "afg", "afh", "afi",
            "bdg", "bdh", "bdi",
            "beg", "beh", "bei",
            "bfg", "bfh", "bfi",
            "cdg", "cdh", "cdi",
            "ceg", "ceh", "cei",
            "cfg", "cfh", "cfi",
 };

更新:我不只是在寻找上面列表大小 = 3 的示例。它可以是任何大小,并且每个字符串可能恰好具有不同的长度。

例如:list = [ "ab", "abc", "defghi", "x", "einsigl"]

标签: java

解决方案


这是一种方法,它应该适用于任意长度的任意数量的单词(不包括 0)。

   String[] lst = new String[] {
        "abc",
        "def",
        "ghi"
    };
    int numWords = lst.length;
    int wordlen = lst[0].length();
    int numPerms = (int) Math.pow(wordlen, numWords);
    char[][] perms = new char[numPerms][numWords];
    char[][] chararr = Arrays.stream(lst)
      .map(String::toCharArray)
      .toArray(i -> new char[i][wordlen]);
    for (int i = 0; i < numWords; i++) {
        double permsLocal = Math.pow(wordlen, i + 1);
        int numRepeats = (int) Math.ceil((numPerms / permsLocal));
        int repeats = (int)(permsLocal / wordlen);
        for (int x = 0; x < repeats; x++) {
            char[] word = chararr[i];
            for (int j = 0; j < wordlen; j++) {
                char c = word[j];
                for (int k = 0; k < numRepeats; k++) {
                    perms[(x * wordlen * numRepeats) + k + j * numRepeats][i] = c;
                }
            }
        }
    }
    String[] permutations = Arrays.stream(perms)
      .map(String::new)
      .toArray(String[]::new);

输出:

[adg, adh, adi, aeg, aeh, aei, afg, afh, afi, bdg, bdh, bdi, beg, beh,
bei, bfg, bfh, bfi, cdg, cdh, cdi, ceg, ceh, cei, cfg, cfh, cfi]

repl.it 链接:https ://repl.it/repls/BoilingExcitingAttributes


推荐阅读