Is there a way to avoid the first loop in the method shrink? (if and while...)
The utility method shrink should reduce the elements of a double array by picking up elements from the original array "with a regular step respectively offset size"... but the first element should always be included, and the last element too, if possible.
public static double[] shrink(final double[] data, final int len) {
if (data.length == 0 || len < 1) {
throw new IllegalArgumentException("data.length == 0 || len < 1");
}
double[] d = new double[len];
double step = (double) data.length / len;
if (len > 1) {
int i = 1;
while (Math.round(step * (len - 1)) < data.length - 1) {
step = (double) (data.length + i) / len;
i++;
}
}
for (int i = 0; i < len; i++) {
int j = (int) Math.round(i * step);
d[i] = data[j];
}
return d;
}
public static void testShrink() {
double[] data1 = {1, 2, 3, 4, 5, 6};
for (int i = 1; i <= data1.length; i++) {
double[] data = new double[i];
System.arraycopy(data1, 0, data, 0, i);
for (int j = 1; j <= i; j++) {
double[] result = shrink(data, j);
System.out.println(i + " " + j + " " + Arrays.toString(result));
}
}
}
The output of the method testShrink should look like the following:
1 1 [1.0]
2 1 [1.0]
2 2 [1.0, 2.0]
3 1 [1.0]
3 2 [1.0, 3.0]
3 3 [1.0, 2.0, 3.0]
4 1 [1.0]
4 2 [1.0, 4.0]
4 3 [1.0, 2.0, 4.0]
4 4 [1.0, 2.0, 3.0, 4.0]
5 1 [1.0]
5 2 [1.0, 5.0]
5 3 [1.0, 3.0, 5.0]
5 4 [1.0, 2.0, 4.0, 5.0]
5 5 [1.0, 2.0, 3.0, 4.0, 5.0]
6 1 [1.0]
6 2 [1.0, 6.0]
6 3 [1.0, 3.0, 6.0]
6 4 [1.0, 3.0, 4.0, 6.0]
6 5 [1.0, 2.0, 3.0, 5.0, 6.0]
6 6 [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
I think, it's also a mathematical-like question.
round()is basically the dithered one, with a non-uniform step; but could be improved) \$\endgroup\$