I have a method which performs permutation of an ArrayList elements, I give an ArrayList as parameter where to store the permutations. However, it's always adding the same item.
I think the issue about this is the ArrayList reference.
public class TSP {
static ArrayList permute(ArrayList<Integer> arr, int k, ArrayList<ArrayList<Integer>> resultados) {
for(int i = k; i < arr.size(); i++){
java.util.Collections.swap(arr, i, k);
permute(arr, k+1, resultados);
java.util.Collections.swap(arr, k, i);
}
if (k == arr.size() -1){
System.out.println("Permute method: "+arr.toString());
resultados.add(arr);
}
return resultados;
}
public static void main (String[] args) {
ArrayList<Integer> ciudades = new ArrayList<>();
ciudades.add(1);
ciudades.add(2);
ciudades.add(3);
ArrayList<ArrayList<Integer>> resultados = new ArrayList();
resultados = permute(ciudades, 0, resultados);
for (ArrayList<Integer> resultado : resultados) {
System.out.println(resultado.toString());
}
}
}
The output from execution is:
Permute method: [1, 2, 3]
Permute method: [1, 3, 2]
Permute method: [2, 1, 3]
Permute method: [2, 3, 1]
Permute method: [3, 2, 1]
Permute method: [3, 1, 2]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
So everything's working OK inside the algorithm but only the first permutation is added. Why?