2014-09-06 47 views
2

我想要獲得與輸入arrayList長度相同的ArrayList的所有可能的排列組合。即1,2,3的ArrayList將導致123,132,213,231,321,312,不包括諸如1,2,12,13等的較短排列。這是我迄今爲止的代碼:獲取一個ArrayList的所有可能的排列的ArrayList

public void getAllPermutations(ArrayList<coordinate> coords) { 
     ArrayList<coordinate> sub = new ArrayList<coordinate>(); 
     permutateSub(sub, coords); 
    } 

    private ArrayList<ArrayList<coordinate>> permutateSub(ArrayList<coordinate> sub, 
      ArrayList<coordinate> coords) { 
     int n = coords.size(); 
     if(n == 0) System.out.println(sub); 
     else { 
      if(sub.size()==n) { 
      System.out.println(sub); 
      for(int i = 0; i<n; i++) { 
       ArrayList<coordinate> a = new ArrayList<coordinate>(sub); 
       a.add(coords.get(i)); 
       ArrayList<coordinate> b = new ArrayList<coordinate>(coords); 
       b.remove(i); 
       permutateSub(a, b); 
      } 
     } 

    } 

座標是一個類,只有x,y,並被訪問以保存項目的2D點。

當前我正在使用此代碼將其打印到控制檯,但我也希望如果有人能夠闡明我如何將它存儲到ArrayList>中。謝謝。

+0

看起來這可能是http://stackoverflow.com/questions/4240080/generating-all-permutations-of-a-given-string – mkobit 2014-09-06 21:10:03

+0

有趣的副本,我看到方法'permutateSub'的聲明就好像它應該返回一個'ArrayList >'對象,但是我在函數的代碼中沒有看到'return'。 – 2014-09-06 21:20:05

+0

糟糕,我的錯誤。無論如何,它仍然會返回更短的排列。 – AHalbert 2014-09-06 21:26:34

回答

3

下面是做這件事:

public static void permutation(List<coordinate> nums) { 
    List<List<coordinate>> accum = new ArrayList<List<coordinate>>(); 
    permutation(accum, Arrays.<coordinate>asList(), nums); 
    System.out.println(accum); 
} 

private static void permutation(List<List<coordinate>> accum, List<coordinate> prefix, List<coordinate> nums) { 
    int n = nums.size(); 
    if (n == 0) { 
     accum.add(prefix); 
    } else { 
     for (int i = 0; i < n; ++i) { 
      List<coordinate> newPrefix = new ArrayList<coordinate>(); 
      newPrefix.addAll(prefix); 
      newPrefix.add(nums.get(i)); 
      List<coordinate> numsLeft = new ArrayList<coordinate>(); 
      numsLeft.addAll(nums); 
      numsLeft.remove(i); 
      permutation(accum, newPrefix, numsLeft); 
     } 
    } 
} 
+0

只是提到它,這是使用Java 8的功能。 – 2014-09-06 21:24:16

+0

謝謝您的貢獻!但是,它們不是整數列表,它們是座標列表。所以會出現幾個涉及List的錯誤。 – AHalbert 2014-09-06 21:25:11

+0

您可以用'座標'搜索並替換'Integer' – janos 2014-09-06 21:29:21

4

看看番石榴的Collections2 permutations方法。

實施例(source

public void permutations() { 
    List<Integer> vals = Ints.asList(new int[] {1, 2, 3}); 

    Collection<List<Integer>> orderPerm = Collections2.permutations(vals); 

    for (List<Integer> val : orderPerm) { 
     logger.info(val); 
    } 
} 

/* output: 
[1, 2, 3] 
[1, 3, 2] 
[3, 1, 2] 
[3, 2, 1] 
[2, 3, 1] 
[2, 1, 3] 
*/ 
+1

+1:無需重新發明輪子。無論如何,番石榴在許多情況下都會有所幫助。 – 2014-09-06 21:40:50

+0

未來,我一定會利用這個。非常感謝。 – AHalbert 2014-09-06 22:12:39

相關問題