A Magic Square is an arrangement of numbers from 1 to n 2 in an n Times n square
ID: 3530765 • Letter: A
Question
A Magic Square is an arrangement of numbers from 1 to n 2 in an n Times n square arrangement such that: (i) the number of elements in each row is equal to the number of rows, (ii) each number appears exactly once, and (iii) the sum of the elements in each row, column or diagonal is the same. Following are some examples of Magic Squares: Write a method which accepts a two-dimensional array of integers as a parameter and returns a boolean indicating whether or not the array represents a Magic Square.Explanation / Answer
function result=isMagicSquare(n)
rows=sum(n);
cols=sum(n,2);
check=rows(1);
result=true;
if(sum(cols==check)~=length(cols)||sum(rows==check)~=length(cols))
result=false;
return;
end
diagL=0;
diagR=0;
len=length(n);
for i=1:len
diagL=diagL+n(i,i);
diagR=diagR+n(i,len-i+1);
end
if(diagL~=diagR || diagL~=check)
result=false;
end