Suma de elementos alternos de una array N x N

Dada una array NxN. La tarea es encontrar la suma de los elementos alternos de la array dada. 
Por ejemplo, en una array de 2 x 2, los elementos alternativos son { A[0][0], A[1, 1] } y { A[1][0], A[0][1] }.
Ejemplos: 
 

Input: mat[][] = { { 1, 2},
                   { 3, 4} }
Output : Sum of alternate elements : 5, 5
Explanation: The alternate elements are {1, 4} 
and {2, 3} so their sum are 5, 5.

Input : mat[][] = { { 1, 2, 3 },
                    { 4, 5, 6 },
                    { 7, 8, 9 } }
Output : Sum of alternate elements :25, 20

La idea es recorrer la array y también llevar un contador. Agregaremos los elementos cuyo valor de contador es par en una variable y con valor de contador impar en otra y finalmente imprimiremos las dos sumas en un recorrido completo de la array.
A continuación se muestra la implementación del enfoque anterior: 
 

C++

// C++ program to print sum of alternate
// elements of a N x N matrix
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the sum of alternate
// elements of a matrix
void sumAlternate(int* arr, int n)
{
    int sum1 = 0, sum2 = 0;
 
    // check the alternate elements
    for (int i = 0; i < n * n; i++) {
 
        // count the elements at even places
        if (i % 2 == 0)
            sum1 += *(arr + i);
 
        else // count the elements at odd places
            sum2 += *(arr + i);
    }
 
    cout << "Sum of alternate elements : " << sum1
         << ", " << sum2 << endl;
}
 
// Driver code
int main()
{
    int mat[3][3] = { { 1, 2, 3 },
                      { 4, 5, 6 },
                      { 7, 8, 9 } };
    int n = 3;
 
    // find the sum of alternate elements
    sumAlternate(&mat[0][0], n);
 
    return 0;
}

Java

// Java program to print sum of alternate
// elements of a N x N matrix
 
class GFG
{
        // Function to find the sum of alternate
        // elements of a matrix
        static void sumAlternate(int [][] mat, int n)
        {
            int sum1 = 0, sum2 = 0;
            int cnt=0;
            // check the alternate elements
            for (int i = 0; i < n; i++) {
         
                for(int j=0;j<n ;j++)
                {
                    if (cnt % 2 == 0)
                        sum1 += mat[i][j];
             
                    else // count the elements at odd places
                        sum2 += mat[i][j];
                 
                   cnt++;
                }
            }
         
            System.out.println("Sum of alternate elements : " + sum1 + ", " + sum2);
        }
         
        // Driver code
        public static void main(String [] args)
        {
            int [][]mat = { { 1, 2, 3 },
                            { 4, 5, 6 },
                            { 7, 8, 9 } };
            int n = 3;
         
            // find the sum of alternate elements
            sumAlternate(mat, n);
         
             
        }
 
}
 
// This code is contributed by ihritik

Python 3

# Python 3 program to print sum of
# alternate elements of a N x N matrix
 
# Function to find the sum of
# alternate elements of a matrix
def sumAlternate(arr, n):
 
    sum1 = 0
    sum2 = 0
 
    # check the alternate elements
    i = 0
    while i < n * n :
 
        # count the elements at
        # even places
        if (i % 2 == 0):
            sum1 += (arr + i)
 
        else: # count the elements
              # at odd places
            sum2 += (arr + i)
             
        i += 1
 
    print("Sum of alternate elements : " +
             str(sum1) + ", " + str(sum2))
 
# Driver code
if __name__ == "__main__":
    mat = [[ 1, 2, 3 ],
        [4, 5, 6 ],
        [7, 8, 9 ]]
    n = 3
 
    # find the sum of alternate elements
    sumAlternate(mat[0][0], n)
 
# This code is contributed
# by ChitraNayal

C#

// C# program to print sum of alternate
// elements of a N x N matrix
using System;
class GFG
{
// Function to find the sum of
// alternate elements of a matrix
static void sumAlternate(int[,] mat,
                         int n)
{
    int sum1 = 0, sum2 = 0;
    int cnt = 0;
     
    // check the alternate elements
    for (int i = 0; i < n; i++)
    {
 
        for(int j = 0; j < n; j++)
        {
            if (cnt % 2 == 0)
                sum1 += mat[i, j];
     
            else // count the elements
                 // at odd places
                sum2 += mat[i, j];
         
        cnt++;
        }
    }
 
    Console.WriteLine("Sum of alternate elements : " +
                                  sum1 + ", " + sum2);
}
 
// Driver code
public static void Main()
{
    int[,] mat = { { 1, 2, 3 },
                    { 4, 5, 6 },
                    { 7, 8, 9 } };
    int n = 3;
 
    // find the sum of alternate elements
    sumAlternate(mat, n);
}
}
 
// This code is contributed
// by Akanksha Rai(Abby_akku)

Javascript

<script>
// Javascript program to print sum of alternate
// elements of a N x N matrix
 
// Function to find the sum of alternate
// elements of a matrix
function sumAlternate(arr, n)
{
    var sum1 = 0, sum2 = 0;
    var cnt = 0;
 
    // check the alternate elements
    for (var i = 0; i < n ; i++) {
 
        for (var j = 0; j < n ; j++) {
        // count the elements at even places
        if (cnt % 2 == 0)
            sum1 += arr[i][j];
 
        else // count the elements at odd places
            sum2 += arr[i][j];
        cnt++;
        }
    }
 
    document.write( "Sum of alternate elements : " + sum1
        + ", " + sum2 );
}
 
// Driver code
var mat = [ [ 1, 2, 3 ],
                [ 4, 5, 6 ],
                [ 7, 8, 9 ] ];
var n = 3;
// find the sum of alternate elements
sumAlternate(mat, n);
 
</script>
Producción: 

Sum of alternate elements : 25, 20

 

Complejidad temporal: O(N 2 )
 

Publicación traducida automáticamente

Artículo escrito por andrew1234 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *