Skip to content Skip to sidebar Skip to footer

Generating Ordered Permutations Of A Given String

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

Solution 1:

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);
    }
}

Post a Comment for "Generating Ordered Permutations Of A Given String"