0

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]]
2
  • When I use k += 3 it only gets 0 + 3 + 6 + 9 then it breaks and goes into the next arraylist. It never gets 1 + 4 + 7 + 10 and 3 + 5 + 8 + 11 Commented Nov 16, 2019 at 14:39
  • @dasblinkenlight Sample input/output implies each sub-array is 3N long and should be filtered into 3 sums [sum(k%3==0), sum(k%3==1), sum(k%3==2)] Commented Nov 16, 2019 at 14:42

1 Answer 1

1

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());
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.