This problem is equivalent to the one of generating all possible permutations of a set of n
numbers, where n
is the number of words in a sentence.
Convert the sentence to an ArrayList<String> words
of words and then generate permutations of an array {0,1,...,n-1}
so that each permutation arr
represents the permutation of words in the sentence: words[arr[0]], ..., words[arr[n-1]]
.
As for the problem of computing all permutations of an array, there are plenty of examples of that here on SO.
Below is an example of a code for generating all permutations of a list (taken from this answer by @YevgenYampolskiy). That code computes all permutations of a List<Integer>
and can easily be adapted to compute permutations of a List<String>
(ArrayList<String>
implements List<String>
).
public class Permute{
static void permute(java.util.List<Integer> arr, int k){
for(int i = k; i < arr.size(); i++){
java.util.Collections.swap(arr, i, k);
permute(arr, k+1);
java.util.Collections.swap(arr, k, i);
}
if (k == arr.size() -1){
System.out.println(java.util.Arrays.toString(arr.toArray()));
}
}
public static void main(String[] args){
Permute.permute(java.util.Arrays.asList(3,4,6,2,1), 0);
}
}