Heap's Algorithm implementation in list of lists

僤鯓⒐⒋嵵緔 提交于 2021-02-10 06:14:54

问题


I'm using Heap's algorithm to create a list-of-lists containing each permutation of said list. Each permutation will be its own list. It works properly when I print it within the algorithm, but it doesn't work properly when I try to add it to my list-of-lists and they are all the same array (4, 1, 2, 3). I commented out the print that I tested to make sure it was working.

My current code:

public static ArrayList<int[]> lists = new ArrayList<>();

public static void main(String[] args) {
    int[] list = {1,2,3,4};
    heapsAlgorithm(4,list);
    for(int i = 1; i <= lists.size(); i++) {
        System.out.println("List " + i + ": " + Arrays.toString(lists.get(i-1)));
    }
}

public static void heapsAlgorithm(int n, int[] list) {
    if (n == 1) {
        lists.add(list);
        //System.out.println(Arrays.toString(list));
    }
    else {
        for(int i = 0; i < n; i++) {
            heapsAlgorithm(n - 1, list);
            if ( n % 2 == 0) {
                int swap = list[i];
                list[i] = list[n-1];
                list[n-1] = swap;
            }
            else {
                int swap = list[0];
                list[0] = list[n-1];
                list[n-1] = swap;
            }
        }
    }
}

Working:

[1, 2, 3, 4]
[2, 1, 3, 4]
[3, 1, 2, 4]
[1, 3, 2, 4]
[2, 3, 1, 4]
[3, 2, 1, 4]
[4, 2, 3, 1]
[2, 4, 3, 1]
[3, 4, 2, 1]
[4, 3, 2, 1]
[2, 3, 4, 1]
[3, 2, 4, 1]
[4, 1, 3, 2]
[1, 4, 3, 2]
[3, 4, 1, 2]
[4, 3, 1, 2]
[1, 3, 4, 2]
[3, 1, 4, 2]
[4, 1, 2, 3]
[1, 4, 2, 3]
[2, 4, 1, 3]
[4, 2, 1, 3]
[1, 2, 4, 3]
[2, 1, 4, 3]

Incorrect output:

List 1: [4, 1, 2, 3]
List 2: [4, 1, 2, 3]
List 3: [4, 1, 2, 3]
List 4: [4, 1, 2, 3]
List 5: [4, 1, 2, 3]
List 6: [4, 1, 2, 3]
List 7: [4, 1, 2, 3]
List 8: [4, 1, 2, 3]
List 9: [4, 1, 2, 3]
List 10: [4, 1, 2, 3]
List 11: [4, 1, 2, 3]
List 12: [4, 1, 2, 3]
List 13: [4, 1, 2, 3]
List 14: [4, 1, 2, 3]
List 15: [4, 1, 2, 3]
List 16: [4, 1, 2, 3]
List 17: [4, 1, 2, 3]
List 18: [4, 1, 2, 3]
List 19: [4, 1, 2, 3]
List 20: [4, 1, 2, 3]
List 21: [4, 1, 2, 3]
List 22: [4, 1, 2, 3]
List 23: [4, 1, 2, 3]
List 24: [4, 1, 2, 3]

I assume I am using my ArrayList wrong, but I'm not sure where. Any suggestions?


回答1:


You are need to copy your int array.

You have an mutable instance of your array and list of arrays that you assume you to keep your permutations. Basically, what's happening:

  1. You do permutation.
  2. You add permutation to your ArrayList.
  3. You do another permutation on THE SAME object.
  4. You add object to ArrayList that ALREADY in this list.

At the end you have ArrayList with 20 times added the same int array.



来源:https://stackoverflow.com/questions/46245677/heaps-algorithm-implementation-in-list-of-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!