2015-05-07 32 views
1

親愛的朋友們,我有一個任務,我幾乎解決了它。但是我最近遇到了一個很大的問題,我無法在兩天內找到出路。如果你能幫助我,我會非常感激!如何在Java中排序子集

所以,假設用戶輸入5 (N)我立即創建這個序列得到的子集出來的:{1,2,3,4,5}

如果N = 4比的順序是這樣的:{1, 2, 3, 4}

比低於該代碼生成所有種類的子集的變化的:

public static int[] genarator(int N) 
{ 
    int[] generator = new int[(int) Math.pow(2, N)]; 
    int[] binDigit = new int[(int) Math.pow(2, N)]; 

    for (int i = 0; i < Math.pow(2, N); i++) 
     generator[i] = (i >> 1)^i; // Right Shifting 

    for (int i = 0; i < Math.pow(2, N); i++) 
    { 
     int one = 1; 
     binDigit[i] = 0; 
     while (generator[i] > 0) 
     { 
      binDigit[i] += (generator[i] % 2) * one; 
      generator[i] /= 2; 
      one = one * 10; 
     } 
    } 

    return binDigit; 
} 

而且它的方式返回結果這樣(在的情況下:N = 4 {1 ,2,3,4})這裏所示:

1 
1 2 
2 
2 3 
1 2 3 
1 3 
3 
3 4 
1 3 4 
1 2 3 4 
2 3 4 
2 4 
1 2 4 
1 4 
4 

但我的講師從我的程序要順序返回結果:

1 
2 
3 
4 
1 2 
1 3 
1 4 
2 3 
2 4 
3 4 
1 2 3 
1 2 4 
1 3 4 
2 3 4 
1 2 3 4 

我現在用TreeSet<Long>parseLong所以我可以得到真正的結果,直到1 < = N < = 9。但是每當用戶輸入10或更高時,它會變得瘋狂。

回顧一下,我的問題是我怎樣才能存儲我從int[] genarator(int N)得到的那些數字,並像我的講師所要求的那樣顯示它們?

生成器如何工作以及如何按錯誤順序獲取數字?代碼如下:

int N = read.nextInt(); 

     int[] sequence = new int[N]; 
     for (int i = 0; i < N; i++) 
      sequence[i] = i + 1; 

     int[] tempArray = new int[(int) Math.pow(2, N)]; 
     tempArray = genarator(N); 

     for (int i = 1; i < Math.pow(2, N); i++) 
     { 
      for (int j = 0; j < N; j++) 
      { 
       if (tempArray[i] % 10 == 1) 
       { 
        System.out.print(sequence[j] + " "); 
       } 
       tempArray[i] /= 10; 
      } 
      System.out.println(); 
     } 

謝謝你檢查,我爲這個太長的問題真的很抱歉。但我無法用簡短的解釋說清楚。

回答

1

你可以做的是創建一個可以與其他集合進行比較的集合抽象。請參閱Comparators上的Java教程。

//don't call this Set as there is already a Java Set 
    //interface that youdon't want to confuse yourself with 
    public class MySet implements Comparable<MySet>{ 

     int[] backingArray; 

     public MySet(int n) { 
      //initialize the Set 
      this.backingArray = generator(n); 
     } 

     public static Int[] generator(int n) { 
      //..whatever you do to generate your results 
     } 

     @Override 
     public int compareTo(MySet otherSet) { 
      //define how sets are compared (e.g what your professor is asking. 
      //In your example, if one set is shorter than another, 
      //it is considered 'smaller') 
     } 

    } 

Set<MySet> allSets = ....; 

,並簡單地調用Collections.sort(allSets);

+0

謝謝您的回答。現在我正試圖改進我的代碼,如上所示,並檢查您分享的關於比較器的鏈接。但是恐怕比較每個子集並使用這種方法對它們進行排序會有時間限制。 – doppler

+0

不幸的是,生成器似乎無法正確使用這種方式。引發許多問題。我假設它需要不同的算法。有沒有其他方法取決於我目前的輸出來排序呢?或者是否有可能將此解決方案實施到當前輸出? – doppler