I am working on a program,I have tried to find a way how to find all possible permutations of an array elements in Java, but it didn't work .
My code is:
public class Permutation {
public static void main(String[] args) {
int[] list = new int[3];
System.out.println("enter the elements of array");
Scanner sc = new Scanner(System.in);
for (int i = 0; i < list.length; i++) {
list[i] = sc.nextInt();
}
System.out.println(Arrays.toString(list));
int n = list.length;
permutation(list, n, 0);
}
public static void permutation(int[] list, int n, int l) {
if (l == n - 1) {
printArray(n, list);
return;
}
for (int i = 1; i < n; i++) {
swap(list, list[i], list[l]);
permutation(list, n, l + 1);
swap(list, list[i], list[l]);
}
}
public static void swap(int[] list, int x, int y) {
int temp = list[x];
list[x] = list[y];
list[y] = temp;
}
public static void printArray(int n, int[] list) {
for (int i = 0; i < list.length; i++) {
System.out.print(list[i]);
}
}
}
This code is continuously throws an error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at Permutation.swap(Permutation.java:34)
at Permutation.permutation(Permutation.java:27)
at Permutation.permutation(Permutation.java:28)
at Permutation.main(Permutation.java:15)
I'm not able to understand what to do in this program so that it'll produce desired output.
And what is the meaning of this error which is thrown by program??