簡體   English   中英

數組的所有可能組合

[英]All possible combinations of an array

我有一個字符串數組

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

我想要以下形式的這些關鍵字的所有可能組合:

{"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", 
 .... }

我已經花了幾個小時沒有有效的結果(高級編程的副作用??)。

我知道解決方案應該是顯而易見的,但老實說,我被卡住了! 接受 Java/C# 中的解決方案。

編輯

  1. 這不是家庭作業
  2. “ted williams”和“williams ted”被認為是一樣的,所以我只想要“ted williams”

編輯 2 :查看答案中的鏈接后,事實證明 Guava 用戶可以在 com.google.common.collect.Sets 中使用 powerset 方法

編輯:正如 FearUs 指出的那樣,更好的解決方案是使用 Guava 的Sets.powerset(Set set)

編輯 2:更新鏈接。


此解決方案的快速而骯臟的翻譯:

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

測試:

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

我剛剛遇到了這個問題並且對發布的 StackExchange 答案並不滿意,所以這是我的答案。 這將返回Port對象數組中的所有組合。 我會把它留給讀者去適應你正在使用的任何類(或使它成為通用的)。

此版本不使用遞歸。

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

有關更優化的版本,請參閱此頁面上 @Aison 的解決方案。

這里有一個提示:

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

我優化的解決方案是基於 Matthew McPeak 提供的解決方案。 此版本避免了不必要的數組副本。

public static <T> T[][] combinations(T[] a) {

    int len = a.length;
    if (len > 31)
        throw new IllegalArgumentException();

    int numCombinations = (1 << len) - 1;

    @SuppressWarnings("unchecked")
    T[][] combinations = (T[][]) java.lang.reflect.Array.newInstance(a.getClass(), numCombinations);

    // Start i at 1, so that we do not include the empty set in the results
    for (int i = 1; i <= numCombinations; i++) {

        @SuppressWarnings("unchecked")
        T[] combination = (T[]) java.lang.reflect.Array.newInstance(a.getClass().getComponentType(),
                Integer.bitCount(i));

        for (int j = 0, ofs = 0; j < len; j++)
            if ((i & (1 << j)) > 0)
                combination[ofs++] = a[j];

        combinations[i - 1] = combination;
    }

    return combinations;
}
import java.util.ArrayList;
import java.util.List;
public class AllPossibleCombinations {

public static void main(String[] args) {
    String[] a={"ted", "williams", "golden"};           
    List<List<String>> list = new AllPossibleElementCombinations().getAllCombinations(Arrays.asList(a));
    for (List<String> arr:list) {
        for(String s:arr){
            System.out.print(s);
        }
        System.out.println();
    }
}

public List<List<String>> getAllCombinations(List<String> elements) {
    List<List<String>> combinationList = new ArrayList<List<String>>();
    for ( long i = 1; i < Math.pow(2, elements.size()); i++ ) {
        List<String> list = new ArrayList<String>();
        for ( int j = 0; j < elements.size(); j++ ) {
            if ( (i & (long) Math.pow(2, j)) > 0 ) {
                list.add(elements.get(j));
            }
        }
        combinationList.add(list);
    }
    return combinationList;
}

}

輸出:

泰德

威廉姆斯

泰威廉姆斯

金的

泰戈爾登

威廉姆斯戈爾登

泰威廉姆斯戈爾登

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

我知道這個問題很老,但我沒有找到滿足我需求的答案。 因此,使用冪集的思想和番石榴庫的有序排列,我能夠獲得原始數組中所有元素組合的數組。

我想要的是這個:

如果我有一個包含三個字符串的數組

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

我想擁有數組中元素的所有可能組合:

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

所以為了得到這個結果,我使用谷歌的番石榴庫實現了下一個代碼:

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

我希望這對某人有所幫助,這不是用於家庭作業,而是用於 android 應用程序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM