Jak obliczyć średnią wartość każdej kolumny w tablicy 2D?

Nov 30 2020

Próbuję obliczyć średnią wartość kolumn w tablicy 2D, ale nie mogę rozgryźć kodu. Funkcja powinna zwrócić średnią wartość z każdej kolumny. Nie mogę wydrukować wyniku w funkcji. Druk powinien być w funkcji głównej.

static double average_columns(double matrix[][]) {
    int i, j, sum = 0, average=0;
    for (i = 0; i < matrix.length; i++) {
        for (j = 0; j < matrix[i].length; j++) {
            sum=(int) (sum+matrix[i][j]);
        }
        average=sum/matrix[i].length;
        sum=0;
    }
    return average;
}

Odpowiedzi

1 Som Nov 30 2020 at 12:34

W ten sposób możesz obliczyć sumę i średnie z każdego wiersza i kolumny: Poniższy przykładowy kod wydrukuje sumę i średnie w ten sam sposób i nie zwróci żadnej wartości. Jeśli chcesz zwrócić rzeczywistą sumę i średnią, musisz zwrócić double [], który będzie zawierał wszystkie sumy lub średnie zamiast podwójnej.

KOD

public class Test {
    
    static int m = 3; 
    static int n = 3; 

    public static void main(String[] args) {
        
        int i,j;
        int [][]matrix = new int[m][n]; 
      
        int x = 1; // x fills up the value of the matrix
        for (i = 0; i < m; i++) 
            for (j = 0; j < n; j++) 
                matrix[i][j] = x++; 
      
        
        System.out.println("The matrix is : \n");
        for (i = 0; i < m; i++) {
            for (j = 0; j < n; j++) {
                System.out.print(matrix[i][j] + "    ");
            }
            System.out.println();
        }
        
        System.out.println("\nPrinting the avg of each col ::");
        average_columns(matrix);
        
        System.out.println("\nPrinting the avg of each row ::");
        average_rows(matrix);
        
        System.out.println("\nPrinting the sum of each col ::");
        sum_columns(matrix);
        
        System.out.println("\nPrinting the sum of each row ::");
        sum_rows(matrix);

    }
    
    public static void average_rows(int matrix[][]) {
        int i, j;
        double sum = 0, average = 0;
        for (i = 0; i < matrix.length; i++) {
            for (j = 0; j < matrix[i].length; j++) {
                sum=sum+matrix[i][j];
            }
            average=sum/matrix[i].length;
            System.out.println("Average of row " + (i+1) + " = " + average); 
            sum=0;
        }
    }
    
    public static void average_columns(int matrix[][]) {
        int i, j;
        double sum = 0, average = 0;
        for (i = 0; i < matrix.length; i++) {
            for (j = 0; j < matrix[i].length; j++) {
                sum=sum+matrix[j][i];
            }
            average=sum/matrix[i].length;
            System.out.println("Average of column " + (i+1) + " = " + average);
            sum=0;
        }
    }
    
    public static void sum_columns(int matrix[][]) { 
          
        int i,j;
        double sum = 0;       
        for (i = 0; i < matrix.length; ++i) { 
            for (j = 0; j < matrix.length; ++j) { 
                sum = sum + matrix[j][i]; 
            } 
            System.out.println("Sum of column " + (i+1) + " = " + sum); 
            sum = 0; 
        } 
    } 
    
    public static void sum_rows(int matrix[][]) { 
          
        int i,j;
        double sum = 0;   
        for (i = 0; i < matrix.length; ++i) { 
            for (j = 0; j < matrix.length; ++j) { 
                sum = sum + matrix[i][j]; 
            } 
            System.out.println( "Sum of row " + (i+1) + " = " + sum); 
            sum = 0; 
        } 
    } 


}

WYNIK

The matrix is : 

1    2    3    
4    5    6    
7    8    9    

Printing the avg of each col ::
Average of column 1 = 4.0
Average of column 2 = 5.0
Average of column 3 = 6.0

Printing the avg of each row ::
Average of row 1 = 2.0
Average of row 2 = 5.0
Average of row 3 = 8.0

Printing the sum of each col ::
Sum of column 1 = 12.0
Sum of column 2 = 15.0
Sum of column 3 = 18.0

Printing the sum of each row ::
Sum of row 1 = 6.0
Sum of row 2 = 15.0
Sum of row 3 = 24.0
dreamcrash Nov 30 2020 at 15:41

Jeśli założysz NxNmacierz, możesz rozwiązać za pomocą strumieni:

double[][] matrix = { { 1, 5, 15}, { 1, 2, 2}, { 25, 109, 150} };

List<Double> column_average = Arrays.stream(IntStream.range(0, matrix[0].length)
            .mapToObj(c1 -> Arrays.stream(matrix).mapToDouble(doubles -> doubles[c1]).toArray())
            .toArray(double[][]::new))
            .map(i -> Arrays.stream(i).average().getAsDouble())
            .collect(Collectors.toList());

lub bardziej czytelny

 double[][] matrix_transpose = IntStream.range(0, matrix[0].length)
            .mapToObj(c -> Arrays.stream(matrix).mapToDouble(doubles -> doubles[c]).toArray())
            .toArray(double[][]::new);

    List<Double> column_average = Arrays.stream(matrix_transpose)
            .map(col -> Arrays.stream(col).average().getAsDouble())
            .collect(Collectors.toList());

Wykonujesz transpozycję macierzy, a następnie używasz Arrays.stream(...).average().getAsDouble()do obliczenia średnich z tablic.

ArvindKumarAvinash Nov 30 2020 at 12:13
  1. Musisz zwrócić a double[]zamiast a doublez funkcji.
  2. Ponieważ liczby są typu, doubletyp sumpowinien być double.

Jeśli wszystkie rzędy mają jednakową długość:

  1. Ponieważ chcesz dodać wartości każdej kolumny, powinieneś dodać matrix[j][i](zamiast matrix[i][j]) do sumi odpowiednio average[i]będzie sum / matrix.length.

Próbny:

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;
    }
}

Wynik:

[5.333333333333333, 9.0, 12.666666666666666]

Jeśli rzędy mają różną długość:

  1. Najpierw należy znaleźć maksymalną długość rzędów, która stanie się rozmiarem pliku double[] average.
  2. Na koniec użyj 2-poziomowej zagnieżdżonej pętli, aby obliczyć wartości average[]. Pętla zewnętrzna dobiegnie do, average.lengtha pętla wewnętrzna do liczby rzędów. Podczas przetwarzania każdej kolumny użyj licznika (np. int count), Aby śledzić liczbę wartości, do których są dodawane sum. Na końcu wewnętrznej pętli average[i] = sum / count.

Próbny:

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;
    }
}

Wynik:

[5.333333333333333, 9.0, 17.5, 25.0]