C# Magic Square

Introduction to magic squares:

Magic squares are a cool mathematical trick. Basically, you have a matrix – a square 2 dimensional array, which you have to fill in the numbers in each cell of the matrix starting from 1 so that the sum of all the numbers in each column equals to the sum for each line and both diagonal lines. Also, there are two kinds of magic squares:
Odd(i.e 3X3, 5X5, 7X7…) and Even(i.e 4X4, 6X6…)

Luckily, smart people noticed that there is some kind of a pattern for filling the correct numbers in the correct cells in order to get a magic square, as well as they also observed that odd magic squares follow a different pattern than the even ones.
To learn more about each pattern see: Odd and Even

Based on that knowledge, if we know the pattern then let’s make the computer handle all the paper-work!

In this post, we’ll implement the odd square using C# which is more simple than the even one.

Here is the full code in C# as a pdf file: MagicSquare
Also, check out another implementation using C++

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleMagicSquare
{
  class MagicSquare
{
static void Main(string[] args)
{
  //magic puzzle numbers square
  int num = int.Parse(Console.ReadLine());
  int[,] mat = new int[num,num];
  SolveMagicSquare(mat, num);
  if (test1(mat, num) == false) { Console.WriteLine("FAILED!!!");}
  else Console.WriteLine("SUCCESS!!!");
  //for printing the squre,but since you can 'input' large numbers   , you dont need this
  //for (int i = 0; i < mat.GetLength(0); i++)
 //{
   // for (int j = 0; j < mat.GetLength(1); j++)
   // {
      // Console.Write(mat[i, j]);
      // Console.Write(" ");
      // Console.Write(" ");
   // }
   // Console.WriteLine(" ");
   // Console.WriteLine(" ");
  //}
}
//****************************************************************
public static bool SolveMagicSquare(int[,] mat, int num)
{
  if (num <= 0)
  {
    return false;
  }
  for (int i = 0; i < mat.GetLength(0); i++)
  for (int j = 0; j < mat.GetLength(1); j++) mat[i, j] = 0;
//i = line , j= column
  mat[0, mat.GetLength(1) / 2] = 1;
  for (int i = 0, j = mat.GetLength(1) / 2, process = 2; process <    = num * num; process++)
  {
    if ((i - 1) > 0 && j + 1 < mat.GetLength(1) && mat[i - 1, j +          1] == 0)
    {
       i = i - 1; j = j + 1;
       mat[i, j] = process;
    }
    else if ((i - 1) > 0 && j + 1 < mat.GetLength(1) && mat[i - 1,               j + 1] != 0)
   {
      i = i + 1;
      mat[i, j] = process;
   }
   else if (i == 0 && j == num - 1)
   {
     i = 1; j = num - 1;
     mat[i, j] = process;
   }
   else
   {
     if ((i - 1) < 0 && j + 1 < mat.GetLength(1))
     {
        i = num - 1; j = j + 1;
        mat[i, j] = process;
     }
   else if ((j + 1) == mat.GetLength(1) && (i - 1) > 0 && (i - 1)              < mat.GetLength(0))
   {
      i = i - 1; j = 0;
      mat[i, j] = process;
   }
   else if ((j + 1) == mat.GetLength(1) && (i - 1) == 0)
   {
     i = 0; j = 0;
     mat[i, j] = process;
   }
   else if ((j + 1) == mat.GetLength(1) && (i - 1) < 0)
   {
      i = i - 1; j = 0;
      mat[i, j] = process;
   }
   else if (i - 1 < mat.GetLength(0) && j + 1 < mat.GetLength(1) &             &mat[i - 1, j + 1] != 0)
   {
       i = i + 1; mat[i, j] = process;
   }
   else if ((i - 1) == 0 && j + 1 < mat.GetLength(1) && mat[i - 1,              j +1] == 0)
   {
      i = i - 1; j = j + 1;
      mat[i, j ] = process;
   }
  }
}
 return true;
 }
//**************************************************************** //input: magic squre
 //output: if the fillings are correct(sum of lines= sum of column          s = sum of crossings) output=true => sucess, else=>fail.
 static bool test1(int[,] mat, int num)
 {
   int sum = 0;
   for (int i = 0; i < num; i++)
   {
     sum += mat[0, i];
   }
   int temp = 0;
   for (int i = 0; i < num; i++)
   {
      temp = 0;
      for (int j = 0; j < num;j++)
      {
        temp += mat[i, j];
      }
      if (temp != sum) return false;
   }
   temp = 0;
   for (int i = 0; i < num; i++)
   {
     temp = 0;
     for (int j = 0; j < num; j++)
   {
   temp += mat[j, i];
  }
  if (temp != sum) return false;
  }
 temp = 0;
 for (int i = 0; i < num; i++)
 {
    temp += mat[i, i];
 }
 if (temp != sum) return false;
 return true;
 }
 }
 }

That’s it! hope you found this one useful!

Advertisements

4 thoughts on “C# Magic Square

    1. true, because odd dimensions are simple to implement since they are solved using the same method, and like i’ve said in the post, each even dimension(2,4,6..) requires a different approach, which means you must try all the options to fill the square starting from square one!! which means, you must use backtracking algorithm..some nasty heavy algorithm 🙂 redards.

      Like

    1. hey! sorry for the too late reply! I agree, backtracking is more efficient in this case, but i needed something quick to work lol. However, i am working now on a new implementation in c++ that uses recursion, i uploaded the first update but still not done yet. Thanks again for your tuning in mate!

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: