java - 仅使用一个字符在字符串列表上生成排列
问题描述
我正在尝试使用一次取一个字符的字符串列表来生成排列。下面是我想要的输入和输出代码。我们可以简单地迭代吗?我也没有找到确切的方法。
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"]
解决方案
这是一种方法,它应该适用于任意长度的任意数量的单词(不包括 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]
推荐阅读
- selenium-chromedriver - 在最新的 91 和 92 Chrome Driver for Robot Framework 中,按键和滚动元素无法正常工作
- c++ - 如何使用构造函数链接给定类的先前值?
- c++ - 有没有办法在 C++ 中监控 gRPC 服务器的挂起请求
- flask - 如何使用烧瓶从谷歌图书 api 中获取图像链接
- python - 如何将训练过的网络的权重复制到pytorch中的另一个
- javascript - 使用确认模式删除数据
- spring-boot - @PreAuthorize 注释以错误的方式解析最后一个变量
- material-ui - Material-UI v5 Emotion 错误:您似乎在使用不带引号的 'content' 值,尝试将其替换为 `content: '""'`
- javascript - 更新到 Manifest 版本 3 时是否应更改 chrome 扩展命令(热键)名称?
- http-headers - Nginx auth_basic 可以不使用授权标头吗?