Rellenar las entradas que faltan de un cuadrado mágico

Dado un tapete de array de 3X3 al que le faltan los elementos de la diagonal izquierda (establecido en 0 ), considerando que la suma de cada fila, columna y diagonal de la array original era igual, la tarea es encontrar los elementos de la diagonal que faltan e imprimir la array original.
Ejemplos: 
 

Entrada: mat[][] = {{0, 7, 6}, {9, 0, 1}, {4, 3, 0}} 
Salida: 
2 7 6 
9 5 1 
4 3 8 
Fila suma = Columna suma = Suma diagonal = 15
Entrada: mat[][] = {{0, 1, 1}, {1, 0, 1}, {1, 1, 0}} 
Salida: 
1 1 1 
1 1 1 
1 1 1 
 

Enfoque: Sea Sum la suma total excluyendo los elementos de la diagonal, 
 

Sum = suma total de la array dada – diagonalSum 
Sum = (3 * rowSum) – diagonalSum 
Sum = (2 * rowSum) [Ya que, columnSum = rowSum = diagonalSum] 
rowSum = Sum / 2 
 

Por lo tanto, podemos insertar un elemento en cada fila de modo que la suma de la fila sea rowSum
A continuación se muestra la implementación del enfoque anterior: 
 

C++

// C++ program to fill blanks with numbers
#include <bits/stdc++.h>
using namespace std;
 
// Function to print the original matrix
int printFilledDiagonal(int sq[][3])
{
    // Calculate the sum of all the elements
    // of the matrix
    int sum = 0;
    for (int i = 0; i < 3; i++)
        for (int j = 0; j < 3; j++)
            sum += sq[i][j];
 
    // Required sum of each row (from the approach)
    sum /= 2;
 
    for (int i = 0; i < 3; i++) {
 
        // Row sum excluding the diagonal element
        int rowSum = 0;
        for (int j = 0; j < 3; j++)
            rowSum += sq[i][j];
 
        // Element that must be inserted at
        // diagonal element of the current row
        sq[i][i] = sum - rowSum;
    }
 
    // Print the updated matrix
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++)
            cout << sq[i][j] << " ";
        cout << endl;
    }
}
 
// Driver Program to test above function
int main()
{
    int sq[3][3] = {
        { 0, 7, 6 },
        { 9, 0, 1 },
        { 4, 3, 0 }
    };
 
    printFilledDiagonal(sq);
    return 0;
}

Java

// Java program to fill blanks with numbers
 
import java.io.*;
 
class GFG {
    
 
 
// Function to print the original matrix
static int printFilledDiagonal(int sq[][])
{
    // Calculate the sum of all the elements
    // of the matrix
    int sum = 0;
    for (int i = 0; i < 3; i++)
        for (int j = 0; j < 3; j++)
            sum += sq[i][j];
 
    // Required sum of each row (from the approach)
    sum /= 2;
 
    for (int i = 0; i < 3; i++) {
 
        // Row sum excluding the diagonal element
        int rowSum = 0;
        for (int j = 0; j < 3; j++)
            rowSum += sq[i][j];
 
        // Element that must be inserted at
        // diagonal element of the current row
        sq[i][i] = sum - rowSum;
    }
 
    // Print the updated matrix
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++)
            System.out.print( sq[i][j] + " ");
        System.out.println();
    }
    return 0;
}
 
// Driver Program to test above function
 
    public static void main (String[] args) {
        int sq[][] = {
        { 0, 7, 6 },
        { 9, 0, 1 },
        { 4, 3, 0 }
    };
 
    printFilledDiagonal(sq);
    }
     
}
// This code is contributed by anuj_67..

Python3

# Python3 program to fill blanks
# with numbers
 
# Function to print the original matrix
def printFilledDiagonal(sq):
 
    # Calculate the sum of all the
    # elements of the matrix
    Sum = 0
    for i in range(0, 3):
        for j in range(0, 3):
            Sum += sq[i][j]
 
    # Required sum of each
    # row (from the approach)
    Sum = Sum//2
 
    for i in range(0, 3):
 
        # Row sum excluding the
        # diagonal element
        rowSum = 0
        for j in range(0, 3):
            rowSum += sq[i][j]
 
        # Element that must be inserted
        # at diagonal element of the
        # current row
        sq[i][i] = Sum - rowSum
     
    # Print the updated matrix
    for i in range(0, 3):
        for j in range(0, 3):
            print(sq[i][j], end = " ")
        print()
 
# Driver Code
if __name__ == "__main__":
 
    sq = [[0, 7, 6],
          [9, 0, 1],
          [4, 3, 0]]
 
    printFilledDiagonal(sq)
     
# This code is contributed
# by Rituraj Jain

C#

// C# program to fill blanks with numbers
 
using System;
 
class GFG {
     
 
 
// Function to print the original matrix
static int printFilledDiagonal(int [,]sq)
{
    // Calculate the sum of all the elements
    // of the matrix
    int sum = 0;
    for (int i = 0; i < 3; i++)
        for (int j = 0; j < 3; j++)
            sum += sq[i,j];
 
    // Required sum of each row (from the approach)
    sum /= 2;
 
    for (int i = 0; i < 3; i++) {
 
        // Row sum excluding the diagonal element
        int rowSum = 0;
        for (int j = 0; j < 3; j++)
            rowSum += sq[i,j];
 
        // Element that must be inserted at
        // diagonal element of the current row
        sq[i,i] = sum - rowSum;
    }
 
    // Print the updated matrix
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++)
            Console.Write( sq[i,j] + " ");
            Console.WriteLine();
    }
    return 0;
}
 
// Driver Program to test above function
 
    public static void Main () {
        int [,]sq = {
        { 0, 7, 6 },
        { 9, 0, 1 },
        { 4, 3, 0 }
    };
 
    printFilledDiagonal(sq);
    }
     
}
// This code is contributed by inder_verma

PHP

<?php
// PHP program to fill blanks with numbers
 
// Function to print the original matrix
function printFilledDiagonal($sq)
{
    // Calculate the sum of all the
    // elements of the matrix
    $sum = 0;
    for ($i = 0; $i < 3; $i++)
        for ($j = 0; $j < 3; $j++)
            $sum += $sq[$i][$j];
 
    // Required sum of each row
    // (from the approach)
    $sum = (int)($sum / 2);
 
    for ($i = 0; $i < 3; $i++)
    {
 
        // Row sum excluding the
        // diagonal element
        $rowSum = 0;
        for ($j = 0; $j < 3; $j++)
            $rowSum += $sq[$i][$j];
 
        // Element that must be inserted at
        // diagonal element of the current row
        $sq[$i][$i] = $sum - $rowSum;
    }
 
    // Print the updated matrix
    for ($i = 0; $i < 3; $i++)
    {
        for ($j = 0; $j < 3; $j++)
            echo $sq[$i][$j] . " ";
        echo "\n";
    }
}
 
// Driver Code
$sq = array(array(0, 7, 6),
            array(9, 0, 1),
            array(4, 3, 0));
 
printFilledDiagonal($sq);
 
// This code is contributed
// by Akanksha Rai
?>

Javascript

<script>
    // Javascript program to fill blanks with numbers
     
    // Function to print the original matrix
    function printFilledDiagonal(sq)
    {
        // Calculate the sum of all the elements
        // of the matrix
        let sum = 0;
        for (let i = 0; i < 3; i++)
            for (let j = 0; j < 3; j++)
                sum += sq[i][j];
 
        // Required sum of each row (from the approach)
        sum /= 2;
 
        for (let i = 0; i < 3; i++) {
 
            // Row sum excluding the diagonal element
            let rowSum = 0;
            for (let j = 0; j < 3; j++)
                rowSum += sq[i][j];
 
            // Element that must be inserted at
            // diagonal element of the current row
            sq[i][i] = sum - rowSum;
        }
 
        // Print the updated matrix
        for (let i = 0; i < 3; i++) {
            for (let j = 0; j < 3; j++)
                document.write(sq[i][j] + " ");
            document.write("</br>");
        }
        return 0;
    }
     
    let sq = [
              [ 0, 7, 6 ],
              [ 9, 0, 1 ],
              [ 4, 3, 0 ]
              ];
   
    printFilledDiagonal(sq);
 
</script>
Producción: 

2 7 6 
9 5 1 
4 3 8

 

Publicación traducida automáticamente

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