import
java.util.ArrayList;
import java.util.List;
import
org.apache.commons.lang3.ArrayUtils;
import
org.apache.commons.lang3.StringUtils;
public class PossibleStrings
{
public static void main(String[] args) {
PossibleStrings
possibleStrings = new
PossibleStrings();
possibleStrings.processAndPrint("abc");
}
public void
processAndPrint(String text) {
int length = text.length();
char[] array = new char[length];
text.getChars(0, length, array, 0);
System.out.println("Possible
Strings:");
List<String>
list =
possibleStrings(new ArrayList<String>(), StringUtils.EMPTY, array);
for (String string : list) {
System.out.println(string);
}
System.out.println("All
Possible Strings:");
int maxWordLength = 3;
list =
allPossibleStrings(new ArrayList<String>(), StringUtils.EMPTY, array, maxWordLength);
for (String string : list) {
System.out.println(string);
}
}
private List<String>
possibleStrings(List<String> list, String prefix, char array[]) {
int length = array.length;
if (length == 0) {
list.add(prefix);
return list;
}
for (int index = 0; index < length; index++) {
possibleStrings(list, prefix + array[index], ArrayUtils.remove(array, index));
}
return list;
}
private List<String>
allPossibleStrings(List<String> list, String prefix, char array[], int wordLength) {
if (wordLength == 0) {
return list;
}
int length = array.length;
String
newPrefix = null;
for (int index = 0; index < length; index++) {
newPrefix = prefix + array[index];
list.add(newPrefix);
allPossibleStrings(list, newPrefix, array, wordLength-1);
}
return list;
}
}
Output:
Possible Strings:
abc
acb
bac
bca
cab
cba
All Possible Strings:
a
aa
aaa
aab
aac
ab
aba
abb
abc
ac
aca
acb
acc
b
ba
baa
bab
bac
bb
bba
bbb
bbc
bc
bca
bcb
bcc
c
ca
caa
cab
cac
cb
cba
cbb
cbc
cc
cca
ccb
ccc
No comments:
Post a Comment