Skip to content

Instantly share code, notes, and snippets.

@ivanbuhov
Created May 4, 2014 18:46
Show Gist options
  • Save ivanbuhov/756a7986bd0c8de8f6ad to your computer and use it in GitHub Desktop.
Save ivanbuhov/756a7986bd0c8de8f6ad to your computer and use it in GitHub Desktop.
Magic Square
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagicSquare
{
class MagicSquare
{
static void Main()
{
int[,] matrix = {
{ 7, 12, 1, 14 },
{ 2, 13, 8, 11 },
{ 16, 3, 10, 5 },
{ 9, 6, 15, 4 },
};
bool isMagic = isMagicSquare(matrix);
Console.WriteLine(isMagic);
}
private static bool isMagicSquare(int[,] matrix)
{
if (matrix.GetLength(0) != matrix.GetLength(1))
{
throw new ArgumentException("The matrix must be square.");
}
int sum = 0;
// Init the sum with the value of the sum of the first column
for (int i = 0; i < matrix.GetLength(0); i++)
{
sum += matrix[i, 0];
}
// Calculate columns' sums
for (int col = 1; col < matrix.GetLength(1); col++)
{
int currentColSum = 0;
for (int row = 0; row < matrix.GetLength(0); row++)
{
currentColSum += matrix[row, col];
}
if (currentColSum != sum)
{
return false;
}
}
// Calculate rows' sums
for (int row = 0; row < matrix.GetLength(0); row++)
{
int currentRowSum = 0;
for (int col = 0; col < matrix.GetLength(1); col++)
{
currentRowSum += matrix[row, col];
}
if (currentRowSum != sum)
{
return false;
}
}
// Calculate diagonals' sums
int firstDiagonal = 0;
int secondDiagonal = 0;
for (int index = 0; index < matrix.GetLength(0); index++)
{
firstDiagonal += matrix[index, index];
secondDiagonal += matrix[index, matrix.GetLength(0) - index - 1];
}
if (firstDiagonal != sum || secondDiagonal != sum)
{
return false;
}
return true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment