Why do elements inside a List modify themselves?

Viewed 71

I want to get different array elements combinations (permutations) of an array to a List. I swap the first and the last element of the array through a for loop and the combination (permutation) is added to the List. Then the second and the element before the last is swapped and added to the List, so and so forth. Suppose the array is arr[1,2,3,4,5,6,7], the first element added to the List would be arr[7,2,3,4,5,6,1]. The second element would be arr[7,6,3,4,5,2,1]. But what I end up getting is something like arr[7,6,5,4,3,2,1] for all the elements in the List.

The problem is that the elements added to the List are also modified correspondingly with the current modification of the array. I end up getting similar array elements in the List. What I want is different permutations or arrays with different combinations of elements. Can you please help me with this?

private List<Gate[]> generateSolutions(Gate[] solution) {
    List<Gate[]> sList= new ArrayList<>();
    int i, j;
    for (i = 0, j = solution.length - 1; i < solution.length / 2; i++, j--) {
        Gate temp;
        temp = solution[i];
        solution[i] = solution[j];
        solution[j] = temp;
        sList.add(solution);
    }
    return sList;
}
1 Answers
import java.util.ArrayList;
import java.util.List;

/**
 * Dev Parzival
 * Date : 27/10/2020 Time : 22:40
 * I have a confidence about my life that comes from standing tall on my own two feet.
 */
public class Permutation {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>(10);

        //Make sure that the list has unique numbers
        for(int i=0;i<3;i++)
            list.add(i+1);

        int n =list.size();
        Permutation permutation = new Permutation();

        //Generater permutation
        permutation.permute(list, 0, n-1);
    }

    private void permute(ArrayList<Integer> list, int l, int r) {
        //When l is equal to one less than the length of the list we will display it.
        if (l == r)
            System.out.println(list);
        else{
            //The l valuse specifies which position we want to fix
            for (int i = l; i <= r; i++) {
                //After diciding the position we fix it by swapping it.
                swap(list,l,i);
                //Here we are fixing l+1 th number
                permute(list, l+1, r);
                //Swapping it back to its original position so initial order is maintained
                swap(list,l,i);
            }
        }
    }

    //Swap function will swap ith and jth numbers of the list
    private void swap(List<Integer> list, int i, int j) {
        int temp=list.get(i);
        list.set(i,list.get(j));
        list.set(j,temp);
    }

}

Above code is used for generating permutation.

Related