Добавление диагональных значений в двумерный массив - PullRequest
2 голосов
/ 04 июля 2011

У меня есть следующий 2d массив

        int [][] array = {{ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9},
                          {10, 11, 12, 13, 14, 15, 16, 17, 18, 19},
                          {20, 21, 22, 23, 24, 25, 26, 27, 28, 29},
                          {30, 31, 32, 33, 34, 35, 36, 37, 38, 39},
                          {40, 41, 42, 43, 44, 45, 46, 47, 48, 49},
                          {50, 51, 52, 53, 54, 55, 56, 57, 58, 59},
                          {60, 61, 62, 63, 64, 65, 66, 67, 68, 69},
                          {70, 71, 72, 73, 74, 75, 76, 77, 78, 79},
                          {80, 81, 82, 83, 84, 85, 86, 87, 88, 89},
                          {90, 91, 92, 93, 94, 95, 96, 97, 98, 99}};

У меня есть этот код, чтобы найти сумму всех значений в массиве.Как я могу изменить его, чтобы добавить только диагональные значения, начиная с 0 (0 + 11 + 22 + 33 и т. Д.)?

 public static int arraySum(int[][] array)
{
    int total = 0;

    for (int row = 0; row < array.length; row++)
    {
        for (int col = 0; col < array[row].length; col++)
            total += array[row][col];
    }

    return total;
}

Ответы [ 12 ]

12 голосов
/ 04 июля 2011

Поскольку диагонали находятся на идеальном квадрате, вам понадобится всего одна петля для добавления диагоналей.


Добавление диагонали из оригинала:

public static int arraySum(int[][] array){
    int total = 0;

    for (int row = 0; row < array.length; row++)
    {

        total += array[row][row];
    }

    return total;
}

Добавить обе диагонали:

Добавление диагонали от orgin: (обратите внимание, что это добавляет центр дважды ... Вы можете вычесть один, если необходимо)

public static int arraySum(int[][] array){
    int total = 0;

    for (int row = 0; row < array.length; row++)
    {
        total += array[row][row] + array[row][array.length - row-1];
    }

    return total;
}
5 голосов
/ 04 июля 2011
public static int arraySum(int[][] array)
{
    int total = 0;

    for (int index = 0; index < array.length; index++)
    {
            total += array[index][index];
    }

    return total;
}

Это, конечно, предполагает размеры m x m.

2 голосов
/ 17 июля 2016

Вот мое решение -

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int a[][] = new int[n][n];
    for(int a_i=0; a_i < n; a_i++){
        for(int a_j=0; a_j < n; a_j++){
            a[a_i][a_j] = in.nextInt();
        }
    }
    int l_sum = 0;
    for(int i = 0; i<n ; i++){
        l_sum+=a[i][i];
    }
    int r_sum = 0;
    for(int j = 0; j<n ; j++){
        r_sum+=a[j][n-1-j];
    }

    int sum = l_sum + r_sum;

    System.out.println(sum);
   }
 }
2 голосов
/ 10 июня 2016
import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int leftStartDiagnol = 0;
        int rightStartDiagnol = n;
        int leftTotal = 0;
        int rightTotal = 0;
        int a[][] = new int[n][n];
        for (int a_i = 0; a_i < n; a_i++) {
            for (int a_j = 0; a_j < n; a_j++) {
                a[a_i][a_j] = in.nextInt();
            }
        }
        for (int a_i = 0; a_i < n; a_i++) {
            boolean leftNotFound = true;
            boolean rightNotFound = true;
            rightStartDiagnol = --rightStartDiagnol;

            for (int a_j = 0; a_j < n; a_j++) {
                if (leftStartDiagnol == a_j && leftNotFound) {
                    leftTotal = leftTotal + a[a_i][a_j];
                    leftNotFound = false;
                }
                if (rightStartDiagnol == a_j && rightNotFound) {
                    rightTotal = rightTotal + a[a_i][a_j];
                    rightNotFound = false;
                }
            }
            leftStartDiagnol = ++leftStartDiagnol;
        }
        int data = leftTotal - rightTotal;
        System.out.println(Math.abs(data));
    }
}
1 голос
/ 19 августа 2017

Вот мое решение.Проверьте это.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int a[][] = new int[n][n];
    int total1=0;
    int total2=0;

    for(int a_i=0; a_i < n; a_i++){
        for(int a_j=0; a_j < n; a_j++){
            a[a_i][a_j] = in.nextInt();
        }
        total1+= a[a_i][a_i];
        total2+=a[a_i][n-1-a_i];
    }
    System.out.println(Math.abs(total1-total2));
}

}

1 голос
/ 10 ноября 2016
import java.io.*;
import java.util.*;
public class DigArraySum {
public static void main(String[] args) {
    Scanner s=new Scanner(System.in);
    int n=Integer.parseInt(s.nextLine()); //array size
    int[][] a=new int[n][n];  // new array
    for (int i=0;i<n;i++) {
      String str=s.nextLine();
      String[] tempArray=str.split(" ");
      for (int j=0;j<n;j++) {
        a[i][j]=Integer.parseInt(tempArray[j]);
      }
    }
    int x=0;//primary diagonal sum
    int y=0;//secondary diagonal sum
    int sum=0;//total sum
    for (int i=0;i<n;i++) {
      x += a[i][i];
    }
    for (int p=0;p<n;p++) {
      int k=a.length-p-1;
      y+=a[p][a.length-p-1];
      k+=-1;
    }
    sum=x-y;
    System.out.println(Math.abs(sum));
    }
  }

Пояснение: например матрица 3 * 3: 3 // Размер массива

11 2 4

4 5 6

10 8 -12

Первичная диагональ: 11 5 -12

Сумма по основной диагонали : 11 + 5 - 12 = 4

Вторичная диагональ: 4 5 10 Сумма по вторичной диагонали : 4 + 5 + 10 = 19

Общая сумма: | 4 + 19 | = 23

0 голосов
/ 04 июля 2019
public class matrix {

    public static void main(String[] args) {
        int sum=0;
        int a[][]= new int[][]{{2,3,4},{4,5,6},{5,5,5}};

        for(int i=0;i<=2;i++)
        {
            sum=sum+a[i][i];
        }

        System.out.println(sum);
    }

}
0 голосов
/ 25 января 2019

разница между суммами его диагоналей в котлине:

val total = (0 until array.size).sumBy { array[it][it] - array[it][array.size - it - 1] }

если вы хотите абсолютную разницу:

return Math.abs(total)
0 голосов
/ 23 ноября 2018

Если вы хотите добавить обе диагонали в двумерный массив, то вот моя программа.

static int diagonalDifference(int[][] arr) {


   int r=arr.length;


  int sum1=0;
             int sum2=0;

         int j=0;
       for(int i=0;i<r;i++)`
       {
         sum1=sum1+arr[i][j];
         j++;
       }
          j--;
      for(int i=0;i<r;i++)
        {
          sum2=sum2+arr[i][j];
          j--;
        }
          int sum=sum1+sum2; 
          return sum;
}
0 голосов
/ 06 октября 2018

Вот код, который я сделал, чтобы найти сумму первичных диагональных чисел и вторичных диагональных чисел

static int diagSum(int[][] arr) {
    int pd=0;
    int sd=0;
    int sum=0; 
    for(int i=0;i<=arr.length-1;i++){
       pd=pd+arr[i][i];
    } 

    for (int k=0,l=arr.length-1; k<arr.length&&l>=0 ; k++,l--) {
        sd=sd+arr[k][l];
    }

    sum=pd+sd;
    return sum;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...