All possible combinations of an array

前端 未结 7 624
甜味超标
甜味超标 2020-11-30 05:51

I have an string array

{\"ted\", \"williams\", \"golden\", \"voice\", \"radio\"}

and I want all possible combinations of these keywords in

相关标签:
7条回答
  • 2020-11-30 06:43

    I know this question is old, but i didn't find an answer that fullfill my needs. So using the idea of power sets, and ordered permutations of the guava library, im able to obtain an array of all the combinations of elements inside my original array.

    What i wanted was this:

    If i have an array with three strings

    ArrayList<String> tagsArray = new ArrayList<>(Array.asList("foo","bar","cas"));
    

    I want to have all the posible combinations of the elements inside an array:

    {"foo","bar","cas","foobar","foocas","barfoo","barcas","casfoo","casbar","foobarcas","casbarfoo","barcasfoo" . . . . . }
    

    So for getting to this result i implemented the next code, using the google's guava lib:

      import static com.google.common.collect.Collections2.orderedPermutations;
      import static java.util.Arrays.asList;
    
      public void createTags(){
    
        Set<String> tags =  new HashSet<>();
        tags.addAll(tagsArray);
        Set<Set<String>> tagsSets = Sets.powerSet(tags);
    
        for (Set<String> sets : tagsSets) {
            List<String> myList = new ArrayList<>();
            myList.addAll(sets);
            if (!myList.isEmpty()) {
                for (List<String> perm : orderedPermutations(myList)) {
                    System.out.println(perm);
                    String myTag = Joiner.on("").join(perm);
                    tagsForQuery.add(myTag);
                }
            }
        }
    
        for (String hashtag : tagsForQuery) {
            System.out.println(hashtag);
        }
    }
    

    I hope this help somebody, this wasn't for a homework, but for a android app.

    0 讨论(0)
提交回复
热议问题