/**
* @see [url]https://ru.wikipedia.org/wiki/Магический_квадрат[/url]
* @param {Array<Array<Number>>} matrix
* @constructor
*/
function Square(matrix) {
this.__matrix = matrix;
}
/**
* @returns {Boolean}
*/
Square.prototype.isMagic = function() {
var lastRow = this.__matrix.length - 1;
var lastColumn = this.__matrix[0].length - 1;
var magicConst = this.getMagicConst();
for(var i = 0; i <= lastRow; i++) {
if (this.__calcSum(i, 0, 0, 1, i, lastColumn) !== magicConst) return false;
}
for(var j = 0; j <= lastColumn; j++) {
if(this.__calcSum(0, j, 1, 0, lastRow, j) !== magicConst) return false;
}
if(this.__calcSum(0, 0, 1, 1, lastRow, lastColumn) !== magicConst) return false;
if(this.__calcSum(lastRow, 0, -1, 1, 0, lastColumn) !== magicConst) return false;
return true;
};
/**
* @returns {Number}
*/
Square.prototype.getMagicConst = function() {
var k = this.__matrix.length;
return (k * (k * k + 1)) / 2;
};
/**
* @param {Number} rowStart
* @param {Number} colStart
* @param {Number} rowStep
* @param {Number} colStep
* @param {Number} rowEnd
* @param {Number} colEnd
* @returns {Number}
* @private
*/
Square.prototype.__calcSum = function(rowStart, colStart, rowStep, colStep, rowEnd, colEnd) {
var min = Math.min;
var max = Math.max;
var limitRow = rowStep > 0 ? min : max;
var limitCol = colEnd > 0 ? min : max;
var i = limitRow(rowStart - rowStep, rowEnd);
var j = limitCol(colStart - colStep, colEnd);
var sum = 0;
while(i !== rowEnd || j !== colEnd) {
i = limitRow(i + rowStep, rowEnd);
j = limitCol(j + colStep, colEnd);
sum += this.__matrix[i][j];
}
return sum;
};
// ------------------------
var matrix = [
[2, 7, 6],
[9, 5, 1],
[4, 3, 8]
];
var square = new Square(matrix);
alert(square.isMagic());