Reputation: 3
I have been given a list of data points that I have added into an arraylist of arraylist. The challenege I am now facing is that I must add every nth element by dim in this case 4 -1 =3 elements. Therefore I need to add element 0 + 3, 1 + 4 and 2 + 5.
Here is the view of the arraylist of arraylife
[[-0.2499999999998725, 0.09887005649714048, 0.12499999999997119, 0.2499999999998725, 0.34887005649701297, 0.3749999999998437, -0.09887005649714048, -0.34887005649701297, 0.02612994350283071, -0.12499999999997119, -0.3749999999998437, -0.02612994350283071],
[0.027777777777828083, -0.2504708097928492, -0.2638888888887171, -0.027777777777828083, -0.2782485875706773, -0.29166666666654517, 0.2504708097928492, 0.2782485875706773, -0.013418079095867896, 0.2638888888887171, 0.29166666666654517, 0.013418079095867896],
[-0.40277777777757906, 0.15442561205268038, 0.1805555555555111, 0.40277777777757906, 0.5572033898302594, 0.5833333333330901, -0.15442561205268038, -0.5572033898302594, 0.02612994350283071, -0.1805555555555111, -0.5833333333330901, -0.02612994350283071]]
for(int i = 0; i < ai.size(); i++) {
for(int k = 0; k < ai.get(i).size(); k++) {
System.out.println(k +" " + ai.get(i).get(k));
}
System.out.println("BREAK");
}
Here you can see I added every third element. So its 0 + 3 + 6 + 9, 1 + 4 + 7 + 10 and 3 + 5 + 8 + 11. The expect output should be a single number Expect output
[[-0.22387005649, -0.2761299435, 0.5][arraylist two answer][ arraylist three answer]]
Upvotes: 0
Views: 106
Reputation: 3081
You need three sums:
for(List<Double> subList: ai) {
int k = 0;
double[] sums = {0d, 0d, 0d};
for(Double d: subList) {
sums[k++ % 3] += d; // Redirect d into one of three sums
}
List<Double> sumsAsList = Arrays.stream(sums).boxed().collect(Collectors.toList());
}
Upvotes: 1