Question

I am currently trying to count the number of times that a value occurs in each column of a 10 x 10 matrix with Java.

I can make it count the times in each row, but I am having a rough time with the column counts.

Thanks for your help, I am new to this site and to Java.

import java.util.Random;
import static java.lang.System.*;

public class Problem710 {

    public static void main(String[] args) {
        int[][] randArr = new int[10][10];
        double count = 0;
        for (int i = 0; i < randArr.length; ++i) {
            for (int j = 0; j < randArr[0].length; ++j) {
                randArr[i][j] = getRandInt(0, 1);
                count += randArr[i][j];

                out.print(randArr[i][j]);

            }
            out.println();
        }


        double averagePerRow = count / 10;
        out.println(averagePerRow);

    }

    public static int getRandInt(int min, int max) {
        Random rand = new Random();
        return rand.nextInt(max - min + 1);
    }
}
Was it helpful?

Solution

The wording is not clear to me, but if you don't want to know occurrences for the whole matrix, but each individual column, then use this:

int[][] matrix = new int[10][10];
int counter = 0;
int column = 0; // which column
int what = 10;
for(int i = 0; i < matrix.lenght; i++){
   if(matrix[i][column] == what) counter++
}

EDIT:

let's rewrite the matrix, so that 1 means true (there's the number you're looking for) and 0 means false. So for instance which has 1s only in the last row

|0 0 0 0|
|0 0 0 0|
|0 0 0 0|
|1 1 1 1| 
  • the average for rows is (0+0+0+4)/4 = 1

  • the average for columns is (1+1+1+1)/4 = 1

I really can't see how the average could be different.

OTHER TIPS

an approach would be to convert the columns to rows and count it as usual ! That should do it ! This is how you exchange row and cols ...

    int [] [] lol =


        {
            {1,1,1,1,1},
            {2,2,2,2,2},
            {3,3,3,3,3},
            {4,4,4,4,4},
            {5,5,5,5,5}



        };
    int [][]  dup = new int [lol.length][lol[0].length];
    for (int i = 0; i < lol.length; i++) {
        for (int j = 0; j < lol[0].length; j++) {
            dup[j][i] = lol[i][j];
        }
    }
}

}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top