1

Say I have a 2D array:

1.007, 0.003, 0.003
0.0095, 2.003, 0.007
1.005, 0.008, 0.001
0.003, 6.884, 0.007

How can I go through the columns such that I get an average of the numbers greater than 1? Such as: (1.007+1.005)/2 = 1.006

[1.006, 4.4435, 0]

I wrote this so far. Been working on it for days, but I can't get it to work.

double sum=0;
for(int j = 0; j <data[0].length; ++j) { // col
    for( int i = 0; i < data.length; ++i) { // row
        if (data[i][j]>=1){
            sum=sum+data[i][j];
            System.out.println(sum);
            // j+=1;
        }
    }
}

data is my 2D array.

Thanks!

2
  • 1
    Could you elaborate on how the numbers '[1.006, 4.4435, 0]' are computed? For example, what numbers sum to 1.006? Commented Oct 29, 2015 at 22:04
  • Edited my answer according to your edits of question Commented Oct 29, 2015 at 22:22

2 Answers 2

1

If you need to go through columns, switch the for-loop order

public class ArrayExample {

    public static void main(String[] args) {
        double[][] data = {
                {1.007, 0.003, 0.003},
                {0.0095, 2.003, 0.007},
                {1.005, 0.008, 0.001},
                {0.003, 6.884, 0.007}
        };

        double sum = 0;

        for (int i = 0; i < data.length; i++) {
            for (int j = 0; j < data[0].length; j++) {
                if (data[i][j] >= 1.0) {
                    sum += data[i][j];
                    System.out.println(sum);
                }
            }
        }
    }
}

Gives

1.007
3.01
4.015
10.899000000000001
Sign up to request clarification or add additional context in comments.

Comments

1

Edited according last edit of question:

  double[][] data = {
                {1.007, 0.003, 0.003},
                {0.0095, 2.003, 0.007},
                {1.005, 0.008, 0.001},
                {0.003, 6.884, 0.007}
        };

        double sum;
        int count;

        for (int j = 0; j < data[0].length; j++) {
            sum = 0;
            count = 0;
            for (int i = 0; i < data.length; i++) {
                if (data[i][j] >= 1.0) {
                    sum += data[i][j];
                    count++;
                }
            }
            if (count!=0){
                System.out.print(sum/count + " ");
            } else {
                System.out.println(0);
            }

        }
    }

Result: 1.0059999999999998 4.4435 0

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.