The array size is <= 16. The difference is defined as:
diff[i] = array[i+1] - array[i];
I need to find the number of permutations of the original array, which have a difference that is a permutation of the difference of the original array.
This is my code:
public class Main {
Scanner scan = new Scanner(System.in);
int N;
int [] array_base;
int [] first_diff;
int result;
public static void main(String[] args) {
Main main = new Main();
main.read();
main.run();
}
void read() {
N = scan.nextInt();
array_base = new int [N];
for (int i = 0; i<N; i++) {
array_base[i] = scan.nextInt();
}
first_diff = first_difference();
}
int [] first_difference() {
int [] temp = new int [N-1];
for (int i=0; i < N-1; i++) {
temp[i] = array_base[i+1] - array_base[i];
}
return temp;
}
void run() {
permute(array_base,0);
System.out.println(Integer.toString(result));
}
public void permute(int[] array, int k)
{
for(int i=k; i<array.length; i++)
{
int temp;
temp = array[i];
array[i] = array[k];
array[k] = temp;
permute(array, k+1);
int temp2;
temp2 = array[i];
array[i] = array[k];
array[k] = temp2;
}
if (k == array.length-1)
{
calculate(array);
}
}
void calculate(int [] array) {
int [] diff_values = new int [array.length-1];
for (int i = 0; i < array.length-1; i++) {
diff_values[i] = array[i+1] - array[i];
}
compare(diff_values);
}
void compare(int [] values) {
boolean [] used_new = new boolean [values.length];
boolean [] used_first = new boolean [values.length];
for (int i = 0; i < values.length; i++) {
used_new[i] = false;
used_first[i] = false;
}
for (int i = 0; i < values.length; i++) {
for (int j = 0; j < values.length; j++) {
if (used_new[j]) {
}
else if (first_diff[i] == values[j]) {
used_new[j] = true;
used_first[i] = true;
break;
}
}
if (used_first[i] == false) break;
}
if (areAllTrue(used_new) && areAllTrue(used_first)) {
result += 1;
}
}
public boolean areAllTrue(boolean[] array)
{
for(boolean b : array) if(!b) return false;
return true;
}
}
I do, however, see that this code is not fast as it could be. Could anyone give me some advice on how to speed it up?