I am trying to get all permutations of strings(words) in a java array list with two words.Following is the code i tried but i am not getting all permutations of words in the list.
for (int y = 0; y<newList.size(); y++){
String first = newList.get(y);
String second = "";
if(y+1<newList.size()){
second = newList.get(y+1);
}
ArrayList<String> tmpArr = new ArrayList<String>();
tmpArr.add(first);
tmpArr.add(second);
ArrayList<String> retArray = combine(tmpArr);
for (int c = 0; c <retArray.size(); c++) {
System.out.println(retArray.get(c));
}
}
public static ArrayList<String> combine(ArrayList<String> arr){
ArrayList<String> retArr = new ArrayList<String>();
if(arr.size()==0){
retArr.add("");
return retArr;
}
ArrayList<String> tmpArr = (ArrayList<String>)arr.clone();
tmpArr.remove(0);
for(String str1 : combine(tmpArr)){
for(String str2 : arr){
retArr.add(str2+","+str1);
if(retArr.size() == 10)
return retArr;
}
}
return retArr;
}
Please let me know how to correct the code to get all permutations of words in the list with size 2(all permutations of words with two words as output)
For example if the input data is as follows Input - [visit,party,delegation]
Expected Output - [visit,party visit,delegation party,visit party,delegation delegation,visit delegation,party]
Current Output - [visit,party, party,party, party,delegation, delegation,delegation,]
ifstatement in yourforloop should be a loop fromy+1through the end of the list. I've posted simple code in an answer.