I'm trying to implement this in Java but I don't how to. Any suggestions?
Examples.
input:
abc
output:
abc
acb
bac
bca
cab
cba
input:
aab
output:
aab
aba
baa
I'm trying to implement this in Java but I don't how to. Any suggestions?
Examples.
input:
abc
output:
abc
acb
bac
bca
cab
cba
input:
aab
output:
aab
aba
baa
This was the simplest way I could think of
String str= "abc";
ArrayList<String> letters = new ArrayList<String>();
HashSet<String> combinations = new HashSet<String>();
for(int i = 0; i<str.length();i++) {
//Break String into letters
letters.add(str.substring(i,i+1));
}
for(int i = (str.length()*2)+1;i>0;i--) {
//Will loop through maximum possible outcomes
String result = "";
String bin = Integer.toBinaryString(i);
//System.out.println(bin);
while(bin.length()<3) {
bin="0"+bin;
}
for(int b = bin.length();b>0;b--) {
if(bin.substring(b-1,b).equals("1"))result = result.concat(letters.get(b-1));
}
for(int b = bin.length();b>0;b--) {
if(bin.substring(b-1,b).equals("0"))result = result.concat(letters.get(b-1));
}
combinations.add(result);
}
System.out.println(str);
for(String c : combinations) {
System.out.println(c);
}
It uses binary to loop through an array of the original string then adds the result to a hash set to remove duplicates