1

I am trying to get all possible permutations of an array of numbers and store it in an ArrayList but always getting same permutation with all elements of the arraylist as the default one {1, 4, 9, 11} any help please ?`

public static void main (String[] args) throws java.lang.Exception
{ 
 int [] my_numbers = {1,4,9,11};
 ArrayList<int []> permutation_results = new ArrayList<int []>();
 arrayPermutations(permutation_results,my_numbers,0);
}
public static void arrayPermutations(ArrayList<int []> result ,int[] 
numbers, int index){
 if(index >= numbers.length - 1){ 
 result.add(numbers);
 return;
 }
 for(int i = index; i < numbers.length; i++){ 
 int t = numbers[index];
 numbers[index] = numbers[i];
 numbers[i] = t;
 arrayPermutations(result, numbers, index+1);
 t = numbers[index];
 numbers[index] = numbers[i];
 numbers[i] = t;
 }
}
asked Nov 4, 2017 at 7:24
1
  • please check you basic around pass by reference and pass by value Commented Nov 4, 2017 at 7:33

1 Answer 1

1

You need to pass a copy of the array to the recursive call:

arrayPermutations(result, numbers.clone(), index + 1);

Otherwise all calls modify the same int[] instance, and so the same instance gets added to the result list multiple times.

answered Nov 4, 2017 at 7:27
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.