I am trying to implement a program to find all possible combinations of a word with length 3 or more. I have implemented algo with prints all the combinations like for example: for word "digital" it will print digitla diitgla ... and so on. But I also need words with length 3 or more in the output. For example: dig, dit, git, and so on.
Can anyone help me what code shall I include to get the above output?
public class PermTest {
public static void main(String[] args) throws Exception {
String str = "digital";
StringBuffer strBuf = new StringBuffer(str);
doPerm(strBuf,str.length());
}
private static void doPerm(StringBuffer str, int index){
if(index <= 0)
System.out.println(str);
else { //recursively solve this by placing all other chars at current first pos
doPerm(str, index-1);
int currPos = str.length()-index;
for (int i = currPos+1; i < str.length(); i++) {//start swapping all other chars with current first char
swap(str,currPos, i);
doPerm(str, index-1);
swap(str,i, currPos);//restore back my string buffer
}
}
}
private static void swap(StringBuffer str, int pos1, int pos2){
char t1 = str.charAt(pos1);
str.setCharAt(pos1, str.charAt(pos2));
str.setCharAt(pos2, t1);
}
}
Aucun commentaire:
Enregistrer un commentaire