On my question user @deadshot
give me answer.
I decided to little change the program.
I add one object - ArrayList<int[]> combinations
, which will store array int[]
with numbers (size this array is always 3).
I add to combinations
arrays (array[]
) using the method add()
.
package com.company;
import java.util.*;
public class Main {
static int POINTS_ON_LINE = 3;
public static void main(String[] args) {
int[] points = new int[]{1, 2, 3, 4};
System.out.println("no repetitions:");
p1(points, POINTS_ON_LINE);
}
public static void p1(int[] arr, int pointsOnLine) {
List<int[]> combinations = new ArrayList<>();
int lengthArray = arr.length, i;
int[] index = new int[pointsOnLine];
int[] temp = new int[pointsOnLine];
for (i = 0; i < pointsOnLine; i++) {
index[i] = i;
}
if (pointsOnLine < lengthArray) {
for (int j : index) {
temp[j] = arr[j];
}
boolean flag;
while (true) {
System.out.println("Add array: " + Arrays.toString(temp));
combinations.add(temp);
flag = false;
for (i = pointsOnLine - 1; i >= 0; i--) {
if (index[i] != i + lengthArray - pointsOnLine) {
flag = true;
break;
}
}
if (!flag) {
break;
}
index[i] += 1;
for (int j = i + 1; j < pointsOnLine; j++) {
index[j] = index[j - 1] + 1;
}
for (i = 0; i < pointsOnLine; i++) {
temp[i] = arr[index[i]];
}
}
System.out.println("End");
}
System.out.println("Result");
for(int[] q : combinations) {
System.out.println(Arrays.toString(q));
}
}
}
Why is the result like this:
no repetitions:
Add array: [1, 2, 3]
Add array: [1, 2, 4]
Add array: [1, 3, 4]
Add array: [2, 3, 4]
End
Result:
[2, 3, 4]
[2, 3, 4]
[2, 3, 4]
[2, 3, 4]
Why object combinations
contain:
[2, 3, 4]
[2, 3, 4]
[2, 3, 4]
[2, 3, 4]
But object combinations
should be contain this:
[1, 2, 3]
[1, 2, 4]
[1, 3, 4]
[2, 3, 4]