0

How do I get the average for each array in an array?

For example the array is:

double[][] a = {{1,2},{10,20},{-5,5}};

And the result should be:

{1.5, 15, 0}
MarvinJWendt
  • 2,357
  • 1
  • 10
  • 36

1 Answers1

-1

You can do this with this code:

  public static double[] average(double[][] arr) {
    ArrayList<Double> ret = new ArrayList<>(); // Array where we will add the averages
    for (double[] doubles : arr) {
      ret.add(Arrays.stream(doubles).average().getAsDouble()); // Add the average of every sub-array to the list above
    }
    return ret.stream().mapToDouble(n -> n).toArray(); // Return the ArrayList as a double array
  }
MarvinJWendt
  • 2,357
  • 1
  • 10
  • 36