2017-08-06 23 views
0

所以我正在做一些課程,我將作爲實踐,因爲教授離開他們看起來在線上的任務。然而,我目前的任務讓我難以找到如何找到所有n個數字的排列組合。他給了我們sudo代碼,但是我很難翻譯它。如何找到與java整數數組的排列

public void nextPerm(int[] a,int pivot,int suc){ 
    suc = 0; 
    pivot = 0; 
    for(int i = a.length-1;; i--){ 
     if(i+1 != a.length) 
      if(a[i] < a[i+1]){ 
       pivot = i; 
       break; 
      } else if(pivot == 0){ 
       reverseArray(a,pivot);//this just reverses the array from the right of the pivot point 
       System.out.println(a); 
     } 
    } 
    for(int i = a.length-1;;i--){ 
     if(a[i] > a[pivot]){ 
      suc = i; 
      break; 
     } 
    } 
    //swap pivot and suc 
    int place = a[pivot]; 
    a[pivot] = a[suc]; 
    a[place] = a[pivot]; 
    reverseArray(a,pivot); 
    System.out.println(Arrays.toString(a)); 


} 



private void reverseArray(int[] a,int pivot) {//make pivot the index which it will reverse to the right of 
    // TODO Auto-generated method stub 
    int[] place = new int[a.length-pivot-1]; 
    int counter = 0; 
    for(int i = a.length-1; i > pivot;i--){ 
     place[counter] = a[i]; 
     counter++; 
    } 
    counter = 0; 
    int[] hold = new int[a.length]; 
    for(int i = 0; i <= pivot;i++){ 
     hold[i] = a[i]; 
     counter++; 
    } 
    for(int i = 0; i < place.length;i++){ 
     hold[counter] = place[i]; 
     counter++; 
    } 

    System.out.println(Arrays.toString(hold)); 
} 

這是我到目前爲止。基本上每次我運行nextPerm時,它都會調整一個數組作爲另一個排列。欲瞭解更多信息,請查看此處的頁面:link to more info

摘要:nextPerm通過手動更改數組來一次查找所有可能的選項。如果我很不清楚,我很抱歉...我很新手。我也做過這方面的研究,但是我並沒有取得任何進展並且掙扎。先謝謝了。

+0

所以,你想使用查找下一個排列的邏輯來查找給定數字(作爲字符串給出)的所有可能的排列? – CodeHunter

+0

沒有給定int,但是基本上使用然後再次運行nextPerm來獲得下一個perm,它再次操作數組產生另一個置換 – Zoralikecury

+0

我不明白。你能提供你的輸入的例子嗎? – CodeHunter

回答

0

您只需將上一步獲得的輸出作爲輸入傳遞到下一步,直到您遍歷所有可能的排列。以下是相同的解釋和僞代碼。

可以說你有一個數組[1,2,3,4]。數組中4個元素可能的總排列次數爲4!假設所有元素都不同。所以,只需重複nextPerm 4的上述代碼即可!倍。

int fact = factorial(array.length); 
for(int i = 0;i<fact;i++){ 
    int[] b = nextPerm(array); 
    array = b; 
} 

假設您的nextPrem返回給您下一個排列的數組。

+0

....我一定是描述了我的問題不好,但我需要nextPerm的幫助,我很難讓它按照教授想要的方式工作。感謝下一個部分的幫助:)真的很感激它。 – Zoralikecury

+0

@Zoralikecury:希望這個鏈接可以幫助你更好。這找到了字符串的下一個字典排列。同樣的想法是你的教授在他給你的代碼中實現的。 https://stackoverflow.com/questions/1622532/algorithm-to-find-next-greater-permutation-of-a-given-string – CodeHunter