Answer to Question #330773 in C# for Macky

Question #330773

The first line will contain a message prompt to input the size of the matrix.


The succeeding lines will prompt for the elements of the matrix.


The last line will contain the word "MAGIC!" if it is a magic square and "Just a square" if it isn't.

1
Expert's answer
2022-04-19T08:07:08-0400

public static void Main()

{

int[,] array = InitMatrix(2);

var isMagicCube = IsMagicCube(array);


if (isMagicCube) {

Console.WriteLine("MAGIC!");

}

else {

Console.WriteLine("Just a square");

}

}


public static bool IsMagicCube(int[,] arr)

{

int k = 0;

   int l = arr.GetLength(0);

    int p = arr[0, l - 1];

    int o = arr.GetLength(1) + arr.GetLength(0)-2;

    for (int i = 0; i < arr.GetLength(0)-1; i++)

    {

      k += (arr[i, l - 1] == p) ? 1 : 0;

      k += (arr[l - 1,i] == p) ? 1 : 0;

    }

 

    for (int i = 0; i < arr.GetLength(0); i++)

    {

      for (int j = 0; j < arr.GetLength(1); j++)

      {

        Console.Write("{0}\t", arr[i, j]);

      }


Console.WriteLine();       

    }

     

return k == o;

}


private static int[,] InitMatrix(int matrixSize) {

var matrix = new int[matrixSize, matrixSize];

for (int i = 0; i < matrixSize; i++)

    {

     for (int j = 0; j < matrixSize; j++)

{

       matrix[i, j] = Convert.ToInt32(Console.ReadLine());

      }

    }


return matrix;

}


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS