2016-03-15 146 views
0

我正在尝试编写一个代码,该代码生成一个包含给定int数组的所有可能排列的列表。调用静态类中的非静态方法 - java

我有found online a method(下面的代码中的“nextPermutation”)允许这样做,我试图将它实现为基本代码,但它不起作用。

问题是,当我试图动态地将包含新排列的数组添加到列表中时,已经存储在列表中的所有先前排列都被替换为新排列。

我想这个问题在某种程度上与我的“nextPermutation”是非静态的事实有关,但我不知道我应该怎么做来修复它。

有什么建议吗?

package lang_dist; 

import java.util.ArrayList; 
import java.util.Arrays; 
import java.util.List; 

public class lang_dist { 

    public boolean nextPermutation(int[] array) { 
     // Find longest non-increasing suffix 
     int i = array.length - 1; 
     while (i > 0 && array[i - 1] >= array[i]) 
      i--; 
     // Now i is the head index of the suffix 


     // Are we at the last permutation already? 
     if (i <= 0) 
      return false; 

     // Let array[i - 1] be the pivot 
     // Find rightmost element that exceeds the pivot 
     int j = array.length - 1; 
     while (array[j] <= array[i - 1]) 
      j--; 
     // Now the value array[j] will become the new pivot 
     // Assertion: j >= i 

     // Swap the pivot with j 
     int temp = array[i - 1]; 
     array[i - 1] = array[j]; 
     array[j] = temp; 

     // Reverse the suffix 
     j = array.length - 1; 
     while (i < j) { 
      temp = array[i]; 
      array[i] = array[j]; 
      array[j] = temp; 
      i++; 
      j--; 
     } 

     // Successfully computed the next permutation 
     return true; 
    } 

    public static void main(String[] args) 
    { 


    int[] array = {0, 0, 1, 1, 1, 1}; 


    List<int[]> rowList = new ArrayList<int[]>(); 
    List<int[]> results = new ArrayList<int[]>(); 

    lang_dist d=new lang_dist(); 

    while (d.nextPermutation(array)){ 

     System.out.println("Permutation:" + Arrays.toString(array)); 

     results = Arrays.asList(array); 

     rowList.add(results.get(0)); 


    }; 

    System.out.println("---"); 
    for (int[] row : rowList) { 
     System.out.println("Row = " + Arrays.toString(row)); 
    } 
    } 


} 
+1

有* *静态方法和有*例如*方法。创建一个'lang_dist'('new')的实例并在其上调用你的方法。 –

+0

是的,这就是我试图处理'lang_dist d = new lang_dist(); \t while(d.nextPermutation(array)){...'上面的代码,但它不能解决问题。或者这不是创建实例的正确方法? 对不起,我对java很陌生,我可能会错过一些非常明显的东西.. – yamayama

回答

1

(主要)问题是,您将结果存储在每个排列的同一个数组中。因此,rowList包含对同一阵列的n个引用。

要(快速)解决问题,你需要创建一个新的阵列,每置换:

results = Arrays.asList(array.clone());

此外,results这里是多余的,使用rowListresults来存储您的排列。

我建议你看看:Are arrays passed by value or passed by reference in Java?Is Java "pass-by-reference" or "pass-by-value"?

+0

谢谢,现在更清晰了。 – yamayama