2016-03-15 98 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

相關問題