【问题标题】:Get ArrayList of all possible permutations of an ArrayList获取 ArrayList 的所有可能排列的 ArrayList
【发布时间】:2014-09-06 21:07:17
【问题描述】:

我正在尝试获取与输入 arrayList 长度相同的 ArrayList 的所有可能排列。 IE。 1,2,3 的 ArrayList 将导致 123、132、213、231、321、312,不包括较短的排列,如 1、2、12、13... 等。这是我到目前为止的代码:

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 中,我将不胜感激。谢谢。

【问题讨论】:

  • 看起来这可能是stackoverflow.com/questions/4240080/…的副本
  • 有趣的是,我看到方法 permutateSub 的声明好像它应该返回一个 ArrayList&lt;ArrayList&lt;coordinate&gt;&gt; 对象,但我在函数代码的任何地方都没有看到 return
  • 糟糕,我的错误。无论如何,它仍然会返回更短的排列。

标签: java permutation


【解决方案1】:

看看 Guava 的 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:无需重新发明轮子。无论如何,番石榴在许多情况下都会有所帮助。
  • 以后我一定会用到这个的。非常感谢。
【解决方案2】:

这是一种方法:

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);
        }
    }
}

【讨论】:

  • 顺便提一下,这是使用 Java 8 的特性。
  • 感谢您的贡献!但是,它们不是整数列表,而是坐标列表。所以会弹出几个涉及 List 的错误。
  • 您可以搜索并替换Integercoordinate
  • @IngoBürk 你为什么不提一下 Java 8 正在使用的功能
  • @AHalbert 你可能导入了错误的List 接口/类。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-15
  • 1970-01-01
  • 2011-08-06
  • 1970-01-01
  • 1970-01-01
  • 2018-08-07
  • 1970-01-01
相关资源
最近更新 更多