简体   繁体   English

如何计算对角线之和之间的绝对差?

[英]How to calculate the absolute difference between the sum of diagonals?

Given a square matrix, calculate the absolute difference between the sums of its diagonals.给定一个方阵,计算其对角线之和之间的绝对差。

For example, the square matrix is shown below:例如,方阵如下所示:

1 2 3
4 5 6
9 8 9  

The left-to-right diagonal =15.从左到右的对角线=15。 The right to left diagonal = 17. Their absolute difference is 2. Please help with the code for Java.从右到左的对角线 = 17。它们的绝对差为 2。请帮助提供 Java 的代码。

Consider a matrix as an array of arrays of the size N*N.将矩阵视为大小为 N*N 的 arrays 数组。 The left-to-right diagonal the row and the column have the same index.行和列的从左到右的对角线具有相同的索引。 On the right to left diagonal the indexes sum up to N-1 .在从右到左的对角线上,索引总和为N-1 Once you sum them, you can then subtract them and apply the absolute value to it:将它们相加后,您可以减去它们并将绝对值应用于它:

int[][] matrix = ...; // 

int sum1 = 0;
int sum2 = 0;
for (int i = 0; i < matrix.length; ++i) {
    sum1 += matrix[i][i];
    sum2 += matrix[i][matrix.length - i - 1];
}
int result = Math.abs(sum1 - sum2);
import java.util.*;
public class Main
{
static int diagonalDiff(int arr[][])
{
    int leftSum=0;
    int rightSum=0;
    int n=arr.length;
    for(int i=0;i<arr.length-1;i++)
    {
        leftSum=leftSum+arr[i][i];
        rightSum=rightSum+arr[i][n-1-i];
    }
    return java.lang.Math.abs(leftSum-rightSum);
}
public static void main(String[] args)
{
    Scanner scan=new Scanner(System.in);
    System.out.print("Enter size");
    int n=scan.nextInt();
    int a[][]=new int[n][n];
    System.out.print("Enter array elements");
    for(int i=0;i<a.length-1;i++)
    {
        for(int j=0;j<=a[i].length-1;j++)
        {
            a[i][j]=scan.nextInt();
        }
    }
    System.out.print(diagonalDiff(a));
}
}
 public int diagonalDifferences(List<List<Integer>> list) {

    int rSum = 0;
    int lSum = 0;
    int i = 0;
    int j = 0;
    int dif = 0;
    for(i=0; i<list.size(); i++){
        for(j=0; j<list.get(0).size(); j++){
            if(i==j){
                lSum +=list.get(i).get(j);
            }
            if((i+j) == (list.get(0).size()-1)){
                rSum +=list.get(i).get(j);
            }
        }
    }
    
    dif = Math.abs(rSum - lSum);
    return dif;
}

Use Math.abs() to get the absolute difference between the diagonals使用 Math.abs() 获得对角线之间的绝对差

https://www.tutorialspoint.com/java/lang/math_abs_int.htm https://www.tutorialspoint.com/java/lang/math_abs_int.htm

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

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