The task is described here Creating combination of numbers or here Permutations of integer array algorithm.
I decided to solve this problem in this way: From first number to the last check the possibility of permutation:
Create arraLists of the first permutation and of the difference
del1 and rem0
Bool is an object with two parametrs: st - start and end
It`s new permutation
I create new Bool, that at the start have the same start and end, like it is one number. So, we cant use this number anymore before starting new permutation with another start number. And we remove it from the list of numbers rem . And start create permutation with checking.
for (int index = 0; index < arr.length; index++) {
List<Integer> del1 = new ArrayList<Integer>();
List<Integer> rem0 = new ArrayList<Integer>();
for (int i = 0; i < del.length; i++) {
del1.add(del[i]);
}
for (int i = 0; i < arr.length; i++) {
rem0.add(arr[i]);
}
Bool start = new Bool(arr[index], arr[index]);
rem0.remove(index);
check(start, del1, rem0);
}
Checking:
ucet - number of "good" permutations, if the difference of new permutation is the same, as the first, it is "good".
So, I for the ending number I add difference number and if it = number in the list of possible numbers - I add this number to the end of permutation, remove it from the list of possible and remove difference prom the list of differences(by creating new lists). And then continue creating.
private static void check(Bool start, List<Integer> del2, List<Integer> rem) {
if (del2.isEmpty()) {
ucet++;
}
for (int index = 0; index<rem.size(); index++) {
for (int i = 0; i<del2.size(); i++) {
if(start.end+del2.get(i)==rem.get(index)){
List<Integer> del3 = new ArrayList<Integer>();
List<Integer> rem2 = new ArrayList<Integer>();
del3=del2;rem2=rem;
Bool con=new Bool(start.st,rem.get(index));
rem2.remove(index);
del3.remove(i);
check(con,del3,rem2);
}
}
}
}
But I have one bug, that I cant understand. Its IndexOutOfBoundsException. In the string if(start.end+del2.get(i)==rem.get(index)){ .
And it causes del2.get(i).
But the problem is, that i<del2.size().
Can you help me to deal with it? Thanks
1 4 2 5 7 6 9 8 3and first difference3 -2 3 2 -1 3 -1 -5 1. Exception wasException in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2