Dada una array de n X n . La tarea es calcular la diferencia absoluta entre las sumas de su diagonal.
Ejemplos:
Input : mat[][] = 11 2 4 4 5 6 10 8 -12 Output : 15 Sum of primary diagonal = 11 + 5 + (-12) = 4. Sum of secondary diagonal = 4 + 5 + 10 = 19. Difference = |19 - 4| = 15. Input : mat[][] = 10 2 4 5 Output : 7
Calcular las sumas a través de las dos diagonales de una array cuadrada. A lo largo de la primera diagonal de la array, índice de fila = índice de columna, es decir, mat[i][j] se encuentra en la primera diagonal si i = j. A lo largo de la otra diagonal, índice de fila = n – 1 – índice de columna, es decir, mat[i][j] se encuentra en la segunda diagonal si i = n-1-j. Al usar dos bucles, recorremos toda la array y calculamos la suma a través de las diagonales de la array.
A continuación se muestra la implementación de este enfoque:
C++
// C++ program to find the difference // between the sum of diagonal. #include <bits/stdc++.h> #define MAX 100 using namespace std; int difference(int arr[][MAX], int n) { // Initialize sums of diagonals int d1 = 0, d2 = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // finding sum of primary diagonal if (i == j) d1 += arr[i][j]; // finding sum of secondary diagonal if (i == n - j - 1) d2 += arr[i][j]; } } // Absolute difference of the sums // across the diagonals return abs(d1 - d2); } // Driven Program int main() { int n = 3; int arr[][MAX] = { {11, 2, 4}, {4 , 5, 6}, {10, 8, -12} }; cout << difference(arr, n); return 0; }
Java
// JAVA Code for Find difference between sums // of two diagonals class GFG { public static int difference(int arr[][], int n) { // Initialize sums of diagonals int d1 = 0, d2 = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // finding sum of primary diagonal if (i == j) d1 += arr[i][j]; // finding sum of secondary diagonal if (i == n - j - 1) d2 += arr[i][j]; } } // Absolute difference of the sums // across the diagonals return Math.abs(d1 - d2); } /* Driver program to test above function */ public static void main(String[] args) { int n = 3; int arr[][] = { {11, 2, 4}, {4 , 5, 6}, {10, 8, -12} }; System.out.print(difference(arr, n)); } } // This code is contributed by Arnav Kr. Mandal.
Python3
# Python3 program to find the difference # between the sum of diagonal. def difference(arr, n): # Initialize sums of diagonals d1 = 0 d2 = 0 for i in range(0, n): for j in range(0, n): # finding sum of primary diagonal if (i == j): d1 += arr[i][j] # finding sum of secondary diagonal if (i == n - j - 1): d2 += arr[i][j] # Absolute difference of the sums # across the diagonals return abs(d1 - d2); # Driver Code n = 3 arr = [[11, 2, 4], [4 , 5, 6], [10, 8, -12]] print(difference(arr, n)) # This code is contributed # by ihritik
C#
// C# Code for find difference between // sums of two diagonals using System; public class GFG { // Function to calculate difference public static int difference(int[,] arr, int n) { // Initialize sums of diagonals int d1 = 0, d2 = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // finding sum of primary diagonal if (i == j) d1 += arr[i, j]; // finding sum of secondary diagonal if (i == n - j - 1) d2 += arr[i, j]; } } // Absolute difference of the // sums across the diagonals return Math.Abs(d1 - d2); } // Driver Code public static void Main() { int n = 3; int[,] arr ={{11, 2, 4}, {4 , 5, 6}, {10, 8, -12}}; Console.Write(difference(arr, n)); } } // This code is contributed by shiv_bhakt.
PHP
<?php // PHP program to find the difference // between the sum of diagonal. function difference($arr, $n) { // Initialize sums of diagonals $d1 = 0; $d2 = 0; for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n; $j++) { // finding sum of // primary diagonal if ($i == $j) $d1 += $arr[$i][$j]; // finding sum of // secondary diagonal if ($i == $n - $j - 1) $d2 += $arr[$i][$j]; } } // Absolute difference of the sums // across the diagonals return abs($d1 - $d2); } // Driver Code { $n = 3; $arr = array(array(11, 2, 4), array(4 , 5, 6), array(10, 8, -12)); echo difference($arr, $n); return 0; } // This code is contributed by nitin mittal. ?>
Javascript
<script> // Javascript Code for Find difference between sums // of two diagonals function difference(arr,n) { // Initialize sums of diagonals let d1 = 0, d2 = 0; for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { // finding sum of primary diagonal if (i == j) d1 += arr[i][j]; // finding sum of secondary diagonal if (i == n - j - 1) d2 += arr[i][j]; } } // Absolute difference of the sums // across the diagonals return Math.abs(d1 - d2); } /* Driver program to test above function */ let n = 3; let arr = [ [11, 2, 4], [4 , 5, 6], [10, 8, -12] ]; document.write(difference(arr, n)); // This code is contributed Bobby </script>
15
Complejidad de tiempo: O(n*n)
Espacio auxiliar: O(1) usando espacio constante para inicializar sumas diagonales
Podemos optimizar la solución anterior para que funcione en O(n) usando los patrones presentes en los índices de las celdas.
C++
// C++ program to find the difference // between the sum of diagonal. #include <bits/stdc++.h> #define MAX 100 using namespace std; int difference(int arr[][MAX], int n) { // Initialize sums of diagonals int d1 = 0, d2 = 0; for (int i = 0; i < n; i++) { // d1 store the sum of diagonal from // top-left to bottom-right d1 += arr[i][i]; // d2 store the sum of diagonal from // top-right to bottom-left d2 += arr[i][n-i-1]; } // Absolute difference of the sums // across the diagonals return abs(d1 - d2); } // Driven Program int main() { int n = 3; int arr[][MAX] = { {11, 2, 4}, {4 , 5, 6}, {10, 8, -12} }; cout << difference(arr, n); return 0; }
Java
// JAVA Code for Find difference between sums // of two diagonals class GFG { public static int difference(int arr[][], int n) { // Initialize sums of diagonals int d1 = 0, d2 = 0; for (int i = 0; i < n; i++) { d1 += arr[i][i]; d2 += arr[i][n-i-1]; } // Absolute difference of the sums // across the diagonals return Math.abs(d1 - d2); } /* Driver program to test above function */ public static void main(String[] args) { int n = 3; int arr[][] = { {11, 2, 4}, {4 , 5, 6}, {10, 8, -12} }; System.out.print(difference(arr, n)); } } // This code is contributed by Arnav Kr. Mandal.
Python3
# Python3 program to find the difference # between the sum of diagonal. def difference(arr, n): # Initialize sums of diagonals d1 = 0 d2 = 0 for i in range(0, n): d1 = d1 + arr[i][i] d2 = d2 + arr[i][n - i - 1] # Absolute difference of the sums # across the diagonals return abs(d1 - d2) # Driver Code n = 3 arr = [[11, 2, 4], [4 , 5, 6], [10, 8, -12]] print(difference(arr, n)) # This code is contributed # by ihritik
C#
// C# Code for find difference between // sums of two diagonals using System; public class GFG { //Function to find difference public static int difference(int[,] arr, int n) { // Initialize sums of diagonals int d1 = 0, d2 = 0; for (int i = 0; i < n; i++) { d1 += arr[i, i]; d2 += arr[i, n - i - 1]; } // Absolute difference of the sums // across the diagonals return Math.Abs(d1 - d2); } // Driver Code public static void Main() { int n = 3; int[,] arr ={{11, 2, 4}, {4 , 5, 6}, {10, 8, -12}}; Console.Write(difference(arr, n)); } } // This code is contributed by shiv_bhakt.
PHP
<?php // PHP program to find the difference // between the sum of diagonal. function difference($arr, $n) { // Initialize sums of diagonals $d1 = 0; $d2 = 0; for ($i = 0; $i < $n; $i++) { $d1 += $arr[$i][$i]; $d2 += $arr[$i][$n-$i-1]; } // Absolute difference of the sums // across the diagonals return abs($d1 - $d2); } // Driver Code { $n = 3; $arr =array(array(11, 2, 4), array(4, 5, 6), array(10, 8, -12)); echo difference($arr, $n); return 0; } // This code is contributed by nitin mittal. ?>
Javascript
<script> // JAVA SCRIPT Code for Find difference between sums // of two diagonals function difference(arr,n) { // Initialize sums of diagonals let d1 = 0, d2 = 0; for (let i = 0; i < n; i++) { d1 += arr[i][i]; d2 += arr[i][n-i-1]; } // Absolute difference of the sums // across the diagonals return Math.abs(d1 - d2); } /* Driver program to test above function */ let n = 3; let arr = [[11, 2, 4], [4 , 5, 6], [10, 8, -12]]; document.write(difference(arr, n)); // This code is contributed by sravan kumar Gottumukkala </script>
15
Complejidad de tiempo: O(n)
Espacio auxiliar: O(1 ) usando espacio constante para inicializar sumas diagonales
Este artículo es una contribución de Anuj Chauhan . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks.
Publicación traducida automáticamente
Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA