Reputation: 1400
Given a sentence like "one two three four" how would I iterate the List of words in ordered permutation?
This is what I'm trying to achieve
"one"
"one two"
"one two three"
"one two three four"
"two"
"two three"
"two three four"
"three"
"three four"
"four"
I've split the words using space delimiter but cannot work out a method to iterate all the combinations with words kept in current order.
List<String> product_words = new ArrayList<String>(Arrays.asList(productname.split(" ")));
for (int x = 0; x < product_words.size(); x++) {
//stuck here
}
Thanks in advance
Upvotes: 0
Views: 661
Reputation: 18177
All you need is a double for
loop, and make sure to start the inner loop at the index of the outer loop (that will omit "one", after you've gone through all of its permutations).
ArrayList<String> product_words = new ArrayList<String>();
product_words.add("one");
product_words.add("two");
product_words.add("three");
product_words.add("four");
for (int i = 0; i < product_words.size(); i++) {
String s = "";
for (int j = i; j < product_words.size(); j++) {
s += product_words.get(j);
s += " ";
System.out.println(s);
}
}
Upvotes: 2