2015-05-07 23 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