数组的所有可能组合

时间:2022-10-29 21:23:58

I have an string array

我有一个字符串数组

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

and I want all possible combinations of these keywords in the following form:

我想把这些关键字的所有可能组合成如下形式:

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

I've been going for hours with no effective result (side effect of high-level programming ??).

我已经连续工作了好几个小时都没有取得任何有效的成果(高级编程的副作用?)

I know the solution should be obvious but I'm stuck, honestly ! Solutions in Java/C# are accepted.

我知道解决方案应该是显而易见的,但我却被卡住了,老实说!接受Java/ c#中的解决方案。

EDIT:

编辑:

  1. It's not a homework
  2. 这不是一个作业
  3. "ted williams" and "williams ted" are considered the same, so I want "ted williams" only
  4. “ted williams”和“williams ted”被认为是一样的,所以我只想要“ted williams”。

EDIT 2: after reviewing the link in the answer, it turns out that Guava users can have the powerset method in com.google.common.collect.Sets

编辑2:在查看了答案中的链接后,发现番石榴用户可以在com.google.common. collection . set中使用powerset方法

5 个解决方案

#1


15  

EDIT: As FearUs pointed out, a better solution is to use Guava's Sets.powerset(Set set).

编辑:正如费卢斯指出的,更好的解决方案是使用番石榴。powerset(集合)。

EDIT 2: Updated links.

编辑2:更新链接。


Quick and dirty translation of this solution:

快速和肮脏的翻译这个解决方案:

public static void main(String[] args) {

    List<List<String>> powerSet = new LinkedList<List<String>>();

    for (int i = 1; i <= args.length; i++)
        powerSet.addAll(combination(Arrays.asList(args), i));

    System.out.println(powerSet);
}

public static <T> List<List<T>> combination(List<T> values, int size) {

    if (0 == size) {
        return Collections.singletonList(Collections.<T> emptyList());
    }

    if (values.isEmpty()) {
        return Collections.emptyList();
    }

    List<List<T>> combination = new LinkedList<List<T>>();

    T actual = values.iterator().next();

    List<T> subSet = new LinkedList<T>(values);
    subSet.remove(actual);

    List<List<T>> subSetCombination = combination(subSet, size - 1);

    for (List<T> set : subSetCombination) {
        List<T> newSet = new LinkedList<T>(set);
        newSet.add(0, actual);
        combination.add(newSet);
    }

    combination.addAll(combination(subSet, size));

    return combination;
}

Test:

测试:

$ java PowerSet ted williams golden
[[ted], [williams], [golden], [ted, williams], [ted, golden], [williams, golden], [ted, williams, golden]]
$

#2


3  

Here's a hint:

这里有一个提示:

All-Subsets(X) = {union for all y in X: All-Subsets(X-y)} union {X}

#3


3  

I just faced this problem and wasn't really happy with the StackExchange answers posted, so here's my answer. This returns all combinations from an array of Port objects. I'll leave it to the reader to adapt to whatever class you're using (or make it generic).

我刚刚遇到了这个问题,对StackExchange贴出的答案不太满意,下面是我的答案。这将返回端口对象数组中的所有组合。我将留给读者去适应您使用的任何类(或使它成为通用的)。

This version does not use recursion.

这个版本不使用递归。

public static Port[][] combinations ( Port[] ports ) {

    List<Port[]> combinationList = new ArrayList<Port[]>();
    // Start i at 1, so that we do not include the empty set in the results
    for ( long i = 1; i < Math.pow(2, ports.length); i++ ) {
        List<Port> portList = new ArrayList<Port>();
        for ( int j = 0; j < ports.length; j++ ) {
            if ( (i & (long) Math.pow(2, j)) > 0 ) {
                // Include j in set
                portList.add(ports[j]);
            }
        }
        combinationList.add(portList.toArray(new Port[0]));
    }
    return combinationList.toArray(new Port[0][0]);
}

#4


1  

package rnd;

import java.util.ArrayList;

public class Rnd {
    public static void main(String args[]) {
        String a[] = {"ted", "williams", "golden", "voice", "radio"};
        ArrayList<String> result =new ArrayList<>();
        for(int i =0 ;i< a.length; i++){
            String s = "";
            for(int j =i ; j < a.length; j++){
                s += a[j] + " " ;
                result.add(s);
            }
        }
    }
}

#5


0  

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:

为了得到这个结果,我使用谷歌的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.

我希望这能帮助一些人,这不是家庭作业,而是android应用。

#1


15  

EDIT: As FearUs pointed out, a better solution is to use Guava's Sets.powerset(Set set).

编辑:正如费卢斯指出的,更好的解决方案是使用番石榴。powerset(集合)。

EDIT 2: Updated links.

编辑2:更新链接。


Quick and dirty translation of this solution:

快速和肮脏的翻译这个解决方案:

public static void main(String[] args) {

    List<List<String>> powerSet = new LinkedList<List<String>>();

    for (int i = 1; i <= args.length; i++)
        powerSet.addAll(combination(Arrays.asList(args), i));

    System.out.println(powerSet);
}

public static <T> List<List<T>> combination(List<T> values, int size) {

    if (0 == size) {
        return Collections.singletonList(Collections.<T> emptyList());
    }

    if (values.isEmpty()) {
        return Collections.emptyList();
    }

    List<List<T>> combination = new LinkedList<List<T>>();

    T actual = values.iterator().next();

    List<T> subSet = new LinkedList<T>(values);
    subSet.remove(actual);

    List<List<T>> subSetCombination = combination(subSet, size - 1);

    for (List<T> set : subSetCombination) {
        List<T> newSet = new LinkedList<T>(set);
        newSet.add(0, actual);
        combination.add(newSet);
    }

    combination.addAll(combination(subSet, size));

    return combination;
}

Test:

测试:

$ java PowerSet ted williams golden
[[ted], [williams], [golden], [ted, williams], [ted, golden], [williams, golden], [ted, williams, golden]]
$

#2


3  

Here's a hint:

这里有一个提示:

All-Subsets(X) = {union for all y in X: All-Subsets(X-y)} union {X}

#3


3  

I just faced this problem and wasn't really happy with the StackExchange answers posted, so here's my answer. This returns all combinations from an array of Port objects. I'll leave it to the reader to adapt to whatever class you're using (or make it generic).

我刚刚遇到了这个问题,对StackExchange贴出的答案不太满意,下面是我的答案。这将返回端口对象数组中的所有组合。我将留给读者去适应您使用的任何类(或使它成为通用的)。

This version does not use recursion.

这个版本不使用递归。

public static Port[][] combinations ( Port[] ports ) {

    List<Port[]> combinationList = new ArrayList<Port[]>();
    // Start i at 1, so that we do not include the empty set in the results
    for ( long i = 1; i < Math.pow(2, ports.length); i++ ) {
        List<Port> portList = new ArrayList<Port>();
        for ( int j = 0; j < ports.length; j++ ) {
            if ( (i & (long) Math.pow(2, j)) > 0 ) {
                // Include j in set
                portList.add(ports[j]);
            }
        }
        combinationList.add(portList.toArray(new Port[0]));
    }
    return combinationList.toArray(new Port[0][0]);
}

#4


1  

package rnd;

import java.util.ArrayList;

public class Rnd {
    public static void main(String args[]) {
        String a[] = {"ted", "williams", "golden", "voice", "radio"};
        ArrayList<String> result =new ArrayList<>();
        for(int i =0 ;i< a.length; i++){
            String s = "";
            for(int j =i ; j < a.length; j++){
                s += a[j] + " " ;
                result.add(s);
            }
        }
    }
}

#5


0  

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:

为了得到这个结果,我使用谷歌的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.

我希望这能帮助一些人,这不是家庭作业,而是android应用。