简体   繁体   English

二维数组将一行中的所有数字相加,对角线索引除外

[英]2D Array sum all numbers in a row except for the diagonal index

I was wrecking my brain for a while now and finally gave up.我现在正在破坏我的大脑一段时间,最后放弃了。

Say, this is my array:说,这是我的数组:

   int[][] arr =   {{ 144, 2, 3, 2, 5},
                    {2, 36, 1, 2, 1},
                    {0, 0, 9, 0, 3},
                    {4, 4, 4, 225, 3},
                    {1, 1, 1, 1, 16}};

I need to calculate the sum of all of the numbers except for the arr[i][i] and then compare it's power of two to the said number.我需要计算除arr[i][i]之外的所有数字的总和,然后将它的二次幂与所述数字进行比较。

For example, 144 is the arr[0][0] in the first loop.例如, 144是第一个循环中的arr[0][0] I need to take (2 + 3 + 2 + 5)^2 and check if it's equal to 144 (it is).我需要取(2 + 3 + 2 + 5)^2并检查它是否等于144 (它是)。 I was happy when I did it with the first row, but then got stuck on idea of taking every now except the arr[i][i] number, which in the second row is 36 .当我在第一行做这件事时我很高兴,但后来却陷入了除了arr[i][i]数字之外的所有想法,第二行是36

I got nothing until now, only wrong assumptions.直到现在我什么都没有,只有错误的假设。 I'm still learning 2D arrays but the subject doesn't sit well.我还在学习 2D arrays 但这个主题不太好。

public class TwoDArray {

    public static void SquareNum(final int[][] arr) {
    double sqaureSum = 0;
    int total = 0;
    for (int i = 0; i < arr[i].length - 1; i++) {
        total = 0;
        for (int j = 0; j < arr[i].length; j++) {
            }
            ???
        }
    }
    public static void main(final String[] args) {
        final int[][] arr =   {{ 144, 2, 3, 2, 5},
                            {2, 36, 1, 2, 1},
                            {0, 0, 9, 0, 3},
                            {4, 4, 4, 225, 3},
                            {1, 1, 1, 1, 16}};
    SquareNum(arr);
    }
}

Any leads on how I can achieve this?关于我如何实现这一目标的任何线索?

Thanks:)谢谢:)

Here's the code with my suggestions in the comments above added.这是我在上面的评论中添加的建议的代码。 I've also shown how I'd do the output as you described.我还展示了如何按照您的描述执行 output。

class TwoDArray {

    public static void SquareNum(final int[][] arr) {
        String output = "The row numbers where the condition is true are: ";
        int total = 0;
        for (int i = 0; i < arr[i].length; i++) {
            total = 0;
            for (int j = 0; j < arr[i].length; j++) {
                total += arr[i][j];
            }
            double squareSum = Math.pow(total - arr[i][i], 2);
            if (squareSum == arr[i][i])
            {
                output += i + " ";
            }
        }
        System.out.println(output);
    }
    public static void main(final String[] args) {
        final int[][] arr =   {{ 144, 2, 3, 2, 5},
                {2, 36, 1, 2, 1},
                {0, 0, 9, 0, 3},
                {4, 4, 4, 225, 3},
                {1, 1, 1, 1, 16}};
        SquareNum(arr);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM