- Joined
- Feb 3, 2009
- Messages
- 3,292
Hello, I've struggled on google for a while and wasn't able to find the exact thing I need, only a close approximation which is insufficient.
So I'd like to ask here, for a conceptual way to write all combinations from an input string, example:
Input: ABC (Needs to work for any length)
Output:
A
B
C
AA
AB
AC
BA
BB
BC
CA
CB
CC
AAA
AAB
AAC
ABA
ABB
ABC
ACA
ACB
ACC
BAA
BAB
BAC
BBA
BBB
BBC
BCA
BCB
BCC
CAA
CAB
CAC
CBA
CBB
CBC
CCA
CCB
CCC
Bellow is the code of the program which does a similar thing, but not fully what I need:
Which outputs:
A
B
C
AB
AC
BC
ABC
So I'd like to ask here, for a conceptual way to write all combinations from an input string, example:
Input: ABC (Needs to work for any length)
Output:
A
B
C
AA
AB
AC
BA
BB
BC
CA
CB
CC
AAA
AAB
AAC
ABA
ABB
ABC
ACA
ACB
ACC
BAA
BAB
BAC
BBA
BBB
BBC
BCA
BCB
BCC
CAA
CAB
CAC
CBA
CBB
CBC
CCA
CCB
CCC
Bellow is the code of the program which does a similar thing, but not fully what I need:
Code:
public class StringPermutation {
String input; //input String
StringBuffer output; //Holds the output
/*
* Generates combinations by applying the
* concept of recursion
*/
private void nextCombination(int position, int remainder)
{
output.append(input.charAt(position));
if (remainder == 1) {
System.out.println(output);
} else {
for (int i = position + 1; i + remainder - 1 <= input.length(); i++)
nextCombination(i, remainder - 1);
}
output.deleteCharAt(output.length() - 1);
}
public void generateCombinations(String input)
{
output = new StringBuffer();
this.input = input;
int inputStrLength = input.length();
for (int i = 1; i <= inputStrLength; i++)
for (int j = 0; j + i <= inputStrLength; j++)
nextCombination(j, i);
}
/**
* @param args
*/
public static void main(String[] args) {
new StringPermutation().generateCombinations("ABC");
}
}
Which outputs:
A
B
C
AB
AC
BC
ABC