簡體   English   中英

列出一組元素的所有組合

[英]Listing all the combinations of the elements of a set

在集合的元素中,我想列出該集合的所有3個組合。 有辦法嗎?

如果是列表;

for(int i=0; i<list.size()-2; i++)
    for(int j=i+1; j<list.size()-1; j++)
        for(int k=j+1; k<list.size(); k++)
            System.out.println(list.get(i) + " " + list.get(j) + " " + list.get(k));

但是,如何在不將其轉換為列表的情況下使用集合呢?

首選是轉換為列表並使用代碼中的邏輯。 如果要執行此操作而不轉換為列表,則可以使用迭代器進行操作,如下所示:

Set<String> set = ...;
for (String a : set) {
    boolean bGo = false;
    for (String b : set) {
        if (bGo) {
            boolean cGo = false;
            for (String c : set) {
                if (cGo) {
                    System.out.println(a + " " + b + " " + c);
                } else if (b.equals(c)) {
                    cGo = true;
                }
            }
        } else if (a.equals(b)) {
            bGo = true;
        }
    }
}

上面的邏輯在外循環中自由迭代集合。 當它開始迭代第一個嵌套循環中的集合時,它將跳過元素,直到找到外部循環的當前元素為止(即直到a.equals(b) )。 之后,它將運行第三個嵌套循環,該循環將跳過集合中的所有數據,直到b為止,這時它將開始產生組合輸出。

這是有關ideone的演示。

您設置的是SortedSet嗎? 如果是這樣,您可以這樣做:

for (V x: mySet) {
  for (V y: mySet.tailSet(x, false)) {
    for (V z: mySet.tailSet(y, false)) {
      System.out.println(x + " " + y + " " + z);
    }
  }
}

暫無
暫無

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

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