Calcule la suma de la diagonal principal y el número de filas y columnas que contienen valores repetidos en una array cuadrada

Dada una array M[][] de dimensiones N * N, que consta únicamente de números enteros del rango 1N , la tarea es calcular la suma de los elementos de la array presentes en la diagonal principal, el número de filas y columnas que contienen números repetidos valores.

Ejemplos:

Entrada: N = 4, M[][] = {{1, 2, 3, 4}, {2, 1, 4, 3}, {3, 4, 1, 2}, {4, 3, 2, 1}}
Salida: 4 0 0
Explicación:
Suma de la diagonal = M[0][0] + M[1][1] + M[2][2] + M[3][3] = 4.
Sin fila o columna consta de elementos repetidos.
Por lo tanto, la suma requerida es 4

Entrada: N = 3, M[][] = {{2, 1, 3}, {1, 3, 2}, {1, 2, 3}}
Salida: 8 0 2
Explicación:
Suma de la diagonal = M[ 0][0]+M[1][1]+M[2][2] = 8.
Ninguna fila consta de elementos repetidos. La 1ª
y la columnas están formadas por elementos repetidos.

Enfoque: El enfoque es simplemente atravesar todos los elementos de la array y encontrar la suma de las diagonales y el número de filas y columnas que tienen valores repetidos. Siga los pasos a continuación para resolver el problema dado:

  • Inicialice las variables trace , rowRepeat y columnRepeat para almacenar la suma de la diagonal principal, el número de filas y columnas que contienen elementos de array repetidos, respectivamente.
  • Recorra cada elemento presente en la array M[i][j] e incremente la traza de la suma si i es igual a j .
  • Para encontrar filas que contengan valores repetidos, repita una fila a la vez, compare valores y verifique si existe un valor repetido o no. Al obtener el primer par de elementos repetidos, incremente rowRepeat en 1 y salga del bucle .
  • Repita los pasos anteriores para cada fila de la array.
  • El mismo procedimiento se repite para todas las columnas, donde columnRepeat se incrementa en 1 si los valores coinciden.
  • Después de completar todas las iteraciones, imprima el valor de trace , rowRepeat y columnRepeat como resultado.

A continuación se muestra la implementación del enfoque anterior:

C++14

// C++14 program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate trace of
// a matrix and number of rows and
// columns with repeated elements
void vestigium(int N, int M[4][4])
{
     
    // Stores the trace, number of
    // rows and columns consisting
    // of repeated matrix elements
    int trace = 0, row_repeat = 0;
    int column_repeat = 0;
 
    // Iterate over the matrix
    for(int i = 0; i < N; i++)
    {
        for(int j = 0; j < N; j++)
        {
             
            // If current element is
            // present in the main diagonal
            if (i == j)
            {
                 
                // Update trace
                trace += M[i][j];
            }
        }
 
        int flag1 = 0;
 
        // Iterate over each row
        // and increment row_repeat
        // if repeated values exists
        for(int j = 0; j < N; j++)
        {
            for(int k = 0; k < N; k++)
            {
                 
                // For each valid range
                if (j != k && M[i][j] == M[i][k])
                {
                    row_repeat++;
                    flag1 = 1;
                    break;
                }
            }
 
            if (flag1 == 1)
            {
                break;
            }
        }
 
        int flag2 = 0;
 
        // Iterate over each column and
        // increment column_repeat if
        // repeated values are encountered
        for(int j = 0; j < N; j++)
        {
            for(int k = 0; k < N; k++)
            {
                 
                // For each valid range
                if (j != k && M[j][i] == M[k][i])
                {
                    column_repeat++;
                    flag2 = 1;
                    break;
                }
            }
 
            if (flag2 == 1)
            {
                break;
            }
        }
    }
 
    // Answer
    cout << trace << " "
         << row_repeat << " "
         << column_repeat ;
}
 
// Driver Code
int main()
{
    int M[4][4] = { { 1, 2, 3, 4 },
                    { 2, 1, 4, 3 },
                    { 3, 4, 1, 2 },
                    { 4, 3, 2, 1 } };
                       
    int N = sizeof(M) / sizeof(M[0]);
 
    vestigium(N, M);
}
 
// This code is contributed by sanjoy_62

Java

// Java program for the above approach
public class GFG {
 
    // Function to calculate trace of
    // a matrix and number of rows and
    // columns with repeated elements
    public static String vestigium(
        int N, int M[][])
    {
        // Stores the trace, number of
        // rows and columns consisting
        // of repeated matrix elements
        int trace = 0, row_repeat = 0;
        int column_repeat = 0;
 
        // Iterate over the matrix
        for (int i = 0; i < N; i++) {
 
            for (int j = 0; j < N; j++) {
 
                // If current element is
                // present in the main diagonal
                if (i == j) {
 
                    // Update trace
                    trace += M[i][j];
                }
            }
 
            int flag1 = 0;
 
            // Iterate over each row
            // and increment row_repeat
            // if repeated values exists
            for (int j = 0; j < N; j++) {
                for (int k = 0; k < N; k++) {
 
                    // For each valid range
                    if (j != k
                        && M[i][j] == M[i][k]) {
                        row_repeat++;
                        flag1 = 1;
                        break;
                    }
                }
 
                if (flag1 == 1) {
 
                    break;
                }
            }
 
            int flag2 = 0;
 
            // Iterate over each column and
            // increment column_repeat if
            // repeated values are encountered
            for (int j = 0; j < N; j++) {
                for (int k = 0; k < N; k++) {
 
                    // For each valid range
                    if (j != k
                        && M[j][i] == M[k][i]) {
 
                        column_repeat++;
                        flag2 = 1;
                        break;
                    }
                }
 
                if (flag2 == 1) {
 
                    break;
                }
            }
        }
 
        // Answer
        String output = trace + " "
                        + row_repeat + " "
                        + column_repeat + "\n";
 
        // Return answer
        return output;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int M[][] = { { 1, 2, 3, 4 },
                      { 2, 1, 4, 3 },
                      { 3, 4, 1, 2 },
                      { 4, 3, 2, 1 } };
        int N = M.length;
 
        String output = vestigium(N, M);
 
        // Print the output
        System.out.print(output);
    }
}

Python3

# Python3 program for the above approach
 
# Function to calculate trace of
# a matrix and number of rows and
# columns with repeated elements
def vestigium(N, M) :
     
    # Stores the trace, number of
    # rows and columns consisting
    # of repeated matrix elements
    trace = 0
    row_repeat = 0
    column_repeat = 0
 
    # Iterate over the matrix
    for i in range(N) :
        for j in range(N) :
             
            # If current element is
            # present in the main diagonal
            if (i == j):
                 
                # Update trace
                trace += M[i][j]
        flag1 = 0
 
        # Iterate over each row
        # and increment row_repeat
        # if repeated values exists
        for j in range(N) :
            for k in range(N) :
                 
                # For each valid range
                if (j != k and M[i][j] == M[i][k]) :
                    row_repeat += 1
                    flag1 = 1
                    break
            if (flag1 == 1) :
                break
        flag2 = 0
 
        # Iterate over each column and
        # increment column_repeat if
        # repeated values are encountered
        for j in range(N) :
            for k in range(N) :
                 
                # For each valid range
                if (j != k and M[j][i] == M[k][i]) :
                    column_repeat += 1
                    flag2 = 1
                    break
                 
            if (flag2 == 1) :
                break
 
    # Answer
    print(trace, row_repeat, column_repeat)
 
# Driver Code
M = [[ 1, 2, 3, 4 ],
    [ 2, 1, 4, 3 ],
    [ 3, 4, 1, 2 ],
    [ 4, 3, 2, 1 ]]           
N = len(M)
vestigium(N, M)
 
# This code is contributed by avijitmonald1998.

C#

// C# program for the above approach
using System;
 
class GFG{
 
// Function to calculate trace of
// a matrix and number of rows and
// columns with repeated elements
public static String vestigium(int N, int[,] M)
{
     
    // Stores the trace, number of
    // rows and columns consisting
    // of repeated matrix elements
    int trace = 0, row_repeat = 0;
    int column_repeat = 0;
 
    // Iterate over the matrix
    for(int i = 0; i < N; i++)
    {
        for(int j = 0; j < N; j++)
        {
             
            // If current element is
            // present in the main diagonal
            if (i == j)
            {
                 
                // Update trace
                trace += M[i, j];
            }
        }
 
        int flag1 = 0;
 
        // Iterate over each row
        // and increment row_repeat
        // if repeated values exists
        for(int j = 0; j < N; j++)
        {
            for(int k = 0; k < N; k++)
            {
                 
                // For each valid range
                if (j != k && M[i, j] == M[i, k])
                {
                    row_repeat++;
                    flag1 = 1;
                    break;
                }
            }
 
            if (flag1 == 1)
            {
                break;
            }
        }
 
        int flag2 = 0;
 
        // Iterate over each column and
        // increment column_repeat if
        // repeated values are encountered
        for(int j = 0; j < N; j++)
        {
            for(int k = 0; k < N; k++)
            {
                 
                // For each valid range
                if (j != k && M[j, i] == M[k, i])
                {
                    column_repeat++;
                    flag2 = 1;
                    break;
                }
            }
 
            if (flag2 == 1)
            {
                break;
            }
        }
    }
 
    // Answer
    string output = trace + " " + row_repeat + " " +
                    column_repeat + "\n";
 
    // Return answer
    return output;
}
 
// Driver Code
public static void Main(string[] args)
{
    int[, ] M = { { 1, 2, 3, 4 },
                  { 2, 1, 4, 3 },
                  { 3, 4, 1, 2 },
                  { 4, 3, 2, 1 } };
    int N = M.GetLength(0);
 
    string output = vestigium(N, M);
 
    // Print the output
    Console.Write(output);
}
}
 
// This code is contributed by ukasp

Javascript

<script>
// javascript program for the above approach
 
// Function to calculate trace of
// a matrix and number of rows and
// columns with repeated elements
function vestigium( N , M)
{
    // Stores the trace, number of
    // rows and columns consisting
    // of repeated matrix elements
    var trace = 0, row_repeat = 0;
    var column_repeat = 0;
 
    // Iterate over the matrix
    for (i = 0; i < N; i++) {
 
        for (j = 0; j < N; j++) {
 
            // If current element is
            // present in the main diagonal
            if (i == j) {
 
                // Update trace
                trace += M[i][j];
            }
        }
 
        var flag1 = 0;
 
        // Iterate over each row
        // and increment row_repeat
        // if repeated values exists
        for (j = 0; j < N; j++) {
            for (k = 0; k < N; k++) {
 
                // For each valid range
                if (j != k
                    && M[i][j] == M[i][k]) {
                    row_repeat++;
                    flag1 = 1;
                    break;
                }
            }
 
            if (flag1 == 1) {
 
                break;
            }
        }
 
        var flag2 = 0;
 
        // Iterate over each column and
        // increment column_repeat if
        // repeated values are encountered
        for (j = 0; j < N; j++) {
            for (k = 0; k < N; k++) {
 
                // For each valid range
                if (j != k
                    && M[j][i] == M[k][i]) {
 
                    column_repeat++;
                    flag2 = 1;
                    break;
                }
            }
 
            if (flag2 == 1) {
 
                break;
            }
        }
    }
 
    // Answer
    var output = trace + " "
                    + row_repeat + " "
                    + column_repeat + "\n";
 
    // Return answer
    return output;
}
 
// Driver Code
    var M = [ [ 1, 2, 3, 4 ],
                  [ 2, 1, 4, 3 ],
                  [ 3, 4, 1, 2 ],
                  [ 4, 3, 2, 1 ] ];
    var N = M.length;
 
    var output = vestigium(N, M);
 
    // Print the output
    document.write(output);
 
 
// This code contributed by shikhasingrajput
 
</script>
Producción: 

4 0 0

 

Complejidad de Tiempo: O(N 3 )
Espacio Auxiliar: O(N 2 ) 

Publicación traducida automáticamente

Artículo escrito por sherwinfernandes 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 *