I have two arrays (with same length), the size is variable.
To do simplest example I have two arrays with length=3.
Persons -> P1, P2, P3
Seats -> Sa, Sb, Sc
I need generate all combinations Cn
If person P1 take Sa,
is possible that:
- person
P2takeSbthenP3will takeSc. The combination will beP1Sa, P2Sb, P3Sc. - or Person
P2takeScthenP3will takeSb. The combination will beP1Sa, P2Sc, P3Sb.
Now Here all possible combinations.
C0 -> P1Sa, P2Sb, P3Sc
C1 -> P1Sa, P2Sc, P3Sb
C2 -> P1Sb, P2Sa, P3Sc
C3 -> P1Sb, P2Sc, P3Sa
C4 -> P1Sc, P2Sa, P3Sb
C5 -> P1Sc, P2Sb, P3Sa
This is my bad design.
private void recursiveSeatPerson(String c, List<String> p, List<String> s) {
if (p.size() > 1) {
for (int i = 0; i < s.size(); i++) {
String combination = p.get(0)+s.get(i) + ", " + c;
System.out.print(combination);
List<String> new_s = new ArrayList<>();
for (int index_s = 0; index_s < s.size(); index_s++) {
if (index_s != i) {
new_s.add(s.get(i));
}
}
List<String> new_p = new ArrayList<>();
for (int index_p = 1; index_p < p.size(); index_p++) {
new_p.add(p.get(index_p));
}
recursiveSeatPerson(combination, new_p, new_s);
}
} else {
System.out.print(c + p.get(0)+s.get(0) + " ");
System.out.println();
}
}
This is my Testing.
List<String> persons = Arrays.asList("P1", "P2", "P3");
List<String> seats = Arrays.asList("Sa", "Sb", "Sc");
recursiveSeatPerson("", persons, seats);
This is my results:
P1Sa, P2Sa, P1Sa, P2Sa, P1Sa, P3Sa
P2Sa, P1Sa, P2Sa, P1Sa, P3Sa
P1Sb, P2Sb, P1Sb, P2Sb, P1Sb, P3Sb
P2Sb, P1Sb, P2Sb, P1Sb, P3Sb
P1Sc, P2Sc, P1Sc, P2Sc, P1Sc, P3Sc
P2Sc, P1Sc, P2Sc, P1Sc, P3Sc
Now sending empty String like argument in this line:
recursiveSeatPerson("", new_p, new_s);
This is the bad result (again).
P1Sa, P2Sa, P3Sa
P2Sa, P3Sa
P1Sb, P2Sb, P3Sb
P2Sb, P3Sb
P1Sc, P2Sc, P3Sc
P2Sc, P3Sc
How solve my code?