java 查找数组中所有可能的对
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2392652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find all possible pairs in an array
提问by user169743
Its when I try to do stuff like this I realise I really need to go to university!
当我尝试做这样的事情时,我意识到我真的需要上大学!
Anyway I have an array of strings (275) I need to loop through them and create strings of all the possible pairs, in Java.
无论如何,我有一个字符串数组 (275),我需要遍历它们并在 Java 中创建所有可能对的字符串。
I've been learning about recursion but I cant find the answer for this.
我一直在学习递归,但我找不到答案。
回答by Bart Kiers
In case pairs aband baare different, do:
如果成对ab且ba不同,请执行以下操作:
for i=0 to array.length
for j=0 to array.length
if i == j skip
else construct pair array[i], array[j]
and if not, do something like this:
如果没有,请执行以下操作:
for i=0 to array.length-1
for j=i+1 to array.length
construct pair array[i], array[j]
Note that I am assuming the array holds unique strings!
请注意,我假设数组包含唯一的字符串!
回答by guest
I am providing an example that prints all possible n-tuples Strings, just set the attribute reqLen to 2 and it prints all possible pairs.
我提供了一个打印所有可能的 n 元组字符串的示例,只需将属性 reqLen 设置为 2,它就会打印所有可能的对。
public class MyString {
String[] chars = {"a", "b", "c"};
int reqLen = 2;
private void formStrings(String crtStr){
if (crtStr.length() == reqLen){
System.out.println(crtStr);
return;
}
else
for (int i = 0; i < chars.length; i++)
formStrings(crtStr + chars[i]);
}
public static void main(String[] args) {
new MyString().formStrings("");
}}
回答by Pindatjuh
It's a simple double-loop:
这是一个简单的双循环:
for(int x = 0; x < 275; x++) {
final String first = arrayOfStrings[x];
for(int y = 0; y < 275; y++) {
if(y == x) continue; // will properly increase y
final String second = arrayOfStrings[y];
// TODO: do stuff with first and second.
}
}
Edit: as the comments noted, if the elements [a, b, c]have only one aband thus not ba, (called combination), then the following code will work:
编辑:正如评论所指出的,如果元素[a, b, c]只有一个ab,因此没有ba,(称为组合),那么以下代码将起作用:
final ArrayList<String> collected = new ArrayList<String>();
for(int x = 0; x < 275; x++) {
for(int y = 0; y < 275; y++) {
if(y == x) continue; // will properly increase y
final String p1 = arrayOfStrings[x] + arrayOfStrings[y];
final String p2 = arrayOfStrings[y] + arrayOfStrings[x];
if(!collected.contains(p1) && !collected.contains(p2)) {
collected.add(p1);
}
}
}
// TODO: do stuff with collected

