Count Knights that can attack a given pawn in an N * N board | Function to count the knights that are attacking the pawn in an M * M board ; Stores count of knights that are attacking the pawn ; Traverse the knights [ ] [ ] array ; Stores absolute difference of X co - ordinate of i - th knight and pawn ; Stores absolute difference of Y co - ordinate of i - th knight and pawn ; If X is 1 and Y is 2 or X is 2 and Y is 1 ; Update cntKnights ; Driver Code ; Stores total count of knights
function cntKnightsAttackPawn ( knights , pawn , M ) { let cntKnights = 0 ; for ( let i = 0 ; i < M ; i ++ ) { let X = Math . abs ( knights [ i ] [ 0 ] - pawn [ 0 ] ) ; let Y = Math . abs ( knights [ i ] [ 1 ] - pawn [ 1 ] ) ; if ( ( X == 1 && Y == 2 ) || ( X == 2 && Y == 1 ) ) { cntKnights ++ ; } } return cntKnights ; } let knights = [ [ 0 , 4 ] , [ 4 , 5 ] , [ 1 , 4 ] , [ 3 , 1 ] ] ; let pawn = [ 2 , 3 ] ; let M = knights . length ; document . write ( cntKnightsAttackPawn ( knights , pawn , M ) ) ;