public
anonymous / gist:1250309
Created

  • Download Gist
gistfile1.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
package javaapplication_01;
 
import java.util.ArrayList;
import java.util.List;
 
/**
* @author Jiri
*/
public class StringPairGroups {
public static class Pair {
public String s1, s2;
public Pair(String s1, String s2) {
this.s1 = s1; this.s2 = s2;
}
public String toString() {
return s1 + s2;
}
}
public static class Group {
public List<Pair> pairs = new ArrayList<Pair>();
public Group(Pair p) {pairs.add(p);}
}
public List<Group> getGroups(String[] strings, int order) {
List<Group> groups = new ArrayList<Group>();
for (int i = 0; i < strings.length; ++i) {
for (int j = 0; j < strings.length; ++j) {
if (i != j) {
Pair p = new Pair(strings[i], strings[j]);
if (order == 1) {
groups.add(new Group(p));
}
else {
String[] strings2 = new String[strings.length - 2];
for (int k = 0, k2 = 0; k < strings.length; ++k) {
if (k != i && k != j) {
strings2[k2++] = strings[k];
}
}
List<Group> groups2 = getGroups(strings2, order - 1);
for (int k = 0; k < groups2.size(); ++k) {
Group g = new Group(p);
groups.add(g);
Group g2 = groups2.get(k);
g.pairs.addAll(g2.pairs);
}
}
}
}
}
return groups;
}
 
public List<Group> getAllGroups(String[] strings) {
List<Group> groups = new ArrayList<Group>();
for (int order = 1; order <= strings.length/2; ++order) {
List<Group> groups2 = getGroups(strings, order);
groups.addAll(groups2);
}
return groups;
}
 
public void printGroups(List<Group> groups) {
for (int i = 0; i < groups.size(); ++i) {
System.out.print((i + 1) + ": ");
List<Pair> pairs = groups.get(i).pairs;
for (int j = 0; j < pairs.size(); ++j) {
if (j > 0) {System.out.print(", ");}
System.out.print(pairs.get(j));
}
System.out.println();
}
}
 
public static void main(String[] args) {
String strings[] = {"A", "B", "C", "D", "E", "F"};
StringPairGroups G = new StringPairGroups();
List<Group> groups = G.getAllGroups(strings);
G.printGroups(groups);
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.