- You need to return a
double[]
instead of a double
from the function.
- Since the numbers are of type,
double
, the type of sum
should be double
.
If all the rows are of equal length:
- Since you want to add the values of each column, you should add
matrix[j][i]
(instead of matrix[i][j]
) to sum
and accordingly average[i]
will be sum / matrix.length
.
Demo:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// Test
double[][] nums = { { 10, 15, 20 }, { 1, 2, 3 }, { 5, 10, 15 } };
System.out.println(Arrays.toString(averageColumns(nums)));
}
static double[] averageColumns(double matrix[][]) {
int i, j;
double[] average = new double[matrix.length];
for (i = 0; i < matrix.length; i++) {
double sum = 0;
for (j = 0; j < matrix[i].length; j++) {
sum += matrix[j][i];
}
average[i] = sum / matrix.length;
}
return average;
}
}
Output:
[5.333333333333333, 9.0, 12.666666666666666]
If the rows are of different length:
- You should first find the maximum of the length of rows which will become the size of the
double[] average
.
- Finally, use a 2-level nested loop to calculate the values for
average[]
. The outer loop will run up to average.length
and the inner loop will run up to the number of rows. While processing each column, use a counter (e.g. int count
) to keep track of the number of values which are added to sum
. At the end of the inner loop, average[i] = sum / count
.
Demo:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// Test
double[][] nums = { { 10, 15, 20 }, { 1, 2 }, { 5, 10, 15, 25 } };
System.out.println(Arrays.toString(averageColumns(nums)));
}
static double[] averageColumns(double matrix[][]) {
// Find the maximum of the length of rows
int max = matrix[0].length;
for (int i = 0; i < matrix.length; i++) {
if (matrix[i].length > max) {
max = matrix[i].length;
}
}
int i, j;
double[] average = new double[max];
for (i = 0; i < average.length; i++) {
double sum = 0;
int count = 0;
for (j = 0; j < matrix.length; j++) {
if (matrix[j].length - 1 >= i) {
sum += matrix[j][i];
count++;
}
}
average[i] = sum / count;
}
return average;
}
}
Output:
[5.333333333333333, 9.0, 17.5, 25.0]