I'm trying to write a program that shows all possible combinations of teams with characters A,B,C... and so on.
Input : (5,3)
5 is the group size and 3 is the team size.
choosing 3 out of {A,B,C,D,E}
Expected output : ABC,ABD,ABE,ACD,ACE,ADE,BCD,BCE,BDE,CDE
Below is the code I've written so far.
public class teamApp
{
public static void main(String[] args) {
int groupSize =5;
int teamSize = 3;
char start = 'A';
String sequence = "";
showTeam(sequence,start,groupSize,teamSize);
}
public static void showTeam(String sequence,char start, int n, int k)
{
if(n==0||k==0||k>n) {
System.out.println(sequence);
return;
} else {
showTeam(sequence+start,start++,n-1,k-1);
showTeam(sequence,start++,n-1,k);
}
}
}
I tried to use the (n,k) = (n-1,k-1)+(n-1,k) theorem. (where n=groupSize k=teamSize). My current output is
AAA
AAB
AAC
AA
ABB
ABC
AB
ACC
AC
A
BBB
BBC
BB
BCC
BC
B
CCC
CC
C
What am I doing wrong?
First of all, you should change
showTeam(sequence+start,start++,n-1,k-1);
showTeam(sequence,start++,n-1,k);
to
showTeam(sequence+start,(char)(start+1),n-1,k-1);
showTeam(sequence,(char)(start+1),n-1,k);
otherwise, only the second recursive call would get the incremented value of start (since start++ returns the original value of start).
Second of all, when the recursion unwinds, the partial sequences are also printed. To avoid that, add the following condition :
if (n==0||k==0||k>n) {
if (k==0) // this condition will make sure that only complete
// sequences of k elements will be printed
System.out.println(sequence);
} else {
showTeam(sequence+start,(char)(start+1),n-1,k-1);
showTeam(sequence,(char)(start+1),n-1,k);
}
Output :
ABC
ABD
ABE
ACD
ACE
ADE
BCD
BCE
BDE
CDE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With