Count Magic squares in a grid | JavaScript program to count magic squares ;  ; function to check is subgrid is Magic Square ; Elements of grid must contain all numbers from 1 to 9 , sum of all rows , columns and diagonals must be same , i . e . , 15. ; Function to count total Magic square subgrids ; if condition true skip check ; check for magic square subgrid ; return total magic square ; Driver program ; function call to print required answer
var R = 3 ; var C = 4 ; function eqSet ( as , bs ) { if ( as . size !== bs . size ) return false ; for ( var a of as ) if ( ! bs . has ( a ) ) return false ; return true ; } function magic ( a , b , c , d , e , f , g , h , i ) { var s1 = new Set ( [ a , b , c , d , e , f , g , h , i ] ) ; var s2 = new Set ( [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] ) ; if ( eqSet ( s1 , s2 ) && ( a + b + c ) == 15 && ( d + e + f ) == 15 && ( g + h + i ) == 15 && ( a + d + g ) == 15 && ( b + e + h ) == 15 && ( c + f + i ) == 15 && ( a + e + i ) == 15 && ( c + e + g ) == 15 ) return true ; return false ; } function CountMagicSquare ( Grid ) { var ans = 0 ; for ( var i = 0 ; i < R - 2 ; i ++ ) for ( var j = 0 ; j < C - 2 ; j ++ ) { if ( Grid [ i + 1 ] [ j + 1 ] != 5 ) continue ; if ( magic ( Grid [ i ] [ j ] , Grid [ i ] [ j + 1 ] , Grid [ i ] [ j + 2 ] , Grid [ i + 1 ] [ j ] , Grid [ i + 1 ] [ j + 1 ] , Grid [ i + 1 ] [ j + 2 ] , Grid [ i + 2 ] [ j ] , Grid [ i + 2 ] [ j + 1 ] , Grid [ i + 2 ] [ j + 2 ] ) ) ans += 1 ; } return ans ; } var G = [ [ 4 , 3 , 8 , 4 ] , [ 9 , 5 , 1 , 9 ] , [ 2 , 7 , 6 , 2 ] ] ; document . write ( CountMagicSquare ( G ) ) ;