using System;
namespace CuadradoMagico
{
class ProgramaAPP
{
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.Title = "Magic Square Builder :P";
int n = 0;
do
{
Console.Clear();
Console.Write("Orden del cuadrado mágico (impar): ");
try
{
n = Int32.Parse(Console.ReadLine());
if (CuadradoMagico.esPar(n))
{
Console.WriteLine("El orden debe ser impar.");
Console.ReadKey(true);
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadKey(true);
}
}
while (CuadradoMagico.esPar(n));
CuadradoMagico cm = new CuadradoMagico(n);
cm.Crear();
Console.WriteLine("\n\nEL cuadrado mágico de orden " + n + " es:\n\n");
cm.Mostrar();
Console.ReadKey(true);
}
}
class CuadradoMagico
{
private int[,] cm;
private int n;
public CuadradoMagico(int orden)
{
n = orden;
cm = new int[n, n];
}
public static bool esPar(int n)
{
if (n % 2 == 0) return true;
else return false;
}
public void Crear()
{
int fil = 0, col = n / 2, fil_ant = 0, col_ant = n / 2, cont = 1;
cm[fil, col] = cont++;
while (cont <= n * n)
{
fil--;
col++;
if (fil < 0) fil = n - 1;
if (col > n - 1) col = 0;
if (cm[fil, col] != 0)
{
col = col_ant;
fil = fil_ant + 1;
if (fil == n) fil = 0;
}
cm[fil, col] = cont++;
fil_ant = fil;
col_ant = col;
}
}
public void Mostrar()
{
for (int i = 0; i < n; i++)
{
Console.Write("\t");
for (int j = 0; j < n; j++) Console.Write(cm[i, j] + "\t");
Console.WriteLine();
}
}
}
}
Crea cuadrados mágicos de cualquier orden impar. Ejemplo:
Citar8 1 6
3 5 7
4 9 2
Salu2
Hola,
Este codigo dice si una matriz es un cuadrado magico o no:
Descargue la solucion .NET completa: http://code.msdn.microsoft.com/Cuadrados-magicos-50df5132 (http://code.msdn.microsoft.com/Cuadrados-magicos-50df5132)
using System;
using System.Collections.Generic;
using System.Text;
namespace CuadradoMagico
{
class Program
{
public static bool EsCuadradoPerfecto(int[,] matriz)
{
if (matriz.GetLength(0) != matriz.GetLength(1))
return false;
else
{
int suma1 = 0, suma2 = 0, suma3 = 0, suma4 = 0;
for (int i = 0; i < matriz.GetLength(0); i++)
{
for (int j = 0; j < matriz.GetLength(1); j++)
{
suma1 += matriz[i, j];
suma2 += matriz[j, i];
if (i == 0)
{
suma3 += matriz[j, j];
suma4 += matriz[j, matriz.GetLength(1) - 1 - j];
}
}
if (suma1 != suma2 || suma1 != suma3 || suma1 != suma4)
return false;
suma1 = 0;
suma2 = 0;
}
return true;
}
}
static void Main(string[] args)
{
int[,] cuadrado ={ { 1, 8, 10, 15 }, { 12, 13, 3, 6 }, { 7, 2, 16, 9 }, { 14, 11, 5, 4 } };
Console.WriteLine("La matriz cuadrada: ");
for (int i = 0; i < cuadrado.GetLength(0); i++)
{
for (int j = 0; j < cuadrado.GetLength(1); j++)
Console.Write(cuadrado[i, j].ToString() + '\t');
Console.WriteLine();
}
if (EsCuadradoPerfecto(cuadrado))
Console.WriteLine("Es un cuadrado magico.");
else
Console.WriteLine("No es un cuadrado magico.");
Console.ReadLine();
}
}
}