Problem of 8 Neighbours of an element in a 2 | Dimension of Array ; Count of 1 s ; Counting all neighbouring 1 s ; Comparing the number of neighbouring 1 s with given ranges ; Copying changes to the main matrix ; Driver code ; Function call to calculate the resultant matrix after ' K ' iterations . ; Printing Result
let N = 4 ; function predictMatrix ( arr , range1a , range1b , range0a , range0b , K , b ) { let c = 0 ; while ( K != 0 ) { K -- ; for ( let i = 0 ; i < N ; i ++ ) { for ( let j = 0 ; j < N ; j ++ ) { c = 0 ; if ( i > 0 && arr [ i - 1 ] [ j ] == 1 ) c ++ ; if ( j > 0 && arr [ i ] [ j - 1 ] == 1 ) c ++ ; if ( i > 0 && j > 0 && arr [ i - 1 ] [ j - 1 ] == 1 ) c ++ ; if ( i < N - 1 && arr [ i + 1 ] [ j ] == 1 ) c ++ ; if ( j < N - 1 && arr [ i ] [ j + 1 ] == 1 ) c ++ ; if ( i < N - 1 && j < N - 1 && arr [ i + 1 ] [ j + 1 ] == 1 ) c ++ ; if ( i < N - 1 && j > 0 && arr [ i + 1 ] [ j - 1 ] == 1 ) c ++ ; if ( i > 0 && j < N - 1 && arr [ i - 1 ] [ j + 1 ] == 1 ) c ++ ; if ( arr [ i ] [ j ] == 1 ) { if ( c >= range1a && c <= range1b ) b [ i ] [ j ] = 1 ; else b [ i ] [ j ] = 0 ; } if ( arr [ i ] [ j ] == 0 ) { if ( c >= range0a && c <= range0b ) b [ i ] [ j ] = 1 ; else b [ i ] [ j ] = 0 ; } } } for ( let k = 0 ; k < N ; k ++ ) for ( let m = 0 ; m < N ; m ++ ) arr [ k ] [ m ] = b [ k ] [ m ] ; } } let arr = [ [ 0 , 0 , 0 , 0 ] , [ 0 , 1 , 1 , 0 ] , [ 0 , 0 , 1 , 0 ] , [ 0 , 1 , 0 , 1 ] ] ; let range1a = 2 , range1b = 2 ; let range0a = 2 , range0b = 3 ; let K = 3 ; let b = new Array ( N ) ; for ( let i = 0 ; i < N ; i ++ ) { b [ i ] = new Array ( N ) ; for ( let j = 0 ; j < N ; j ++ ) { b [ i ] [ j ] = 0 ; } } predictMatrix ( arr , range1a , range1b , range0a , range0b , K , b ) ; for ( let i = 0 ; i < N ; i ++ ) { document . write ( " " ) ; for ( let j = 0 ; j < N ; j ++ ) document . write ( b [ i ] [ j ] + " " ) ; }