Count possible moves in the given direction in a grid | Function to return the count of possible steps in a single direction ; It can cover infinite steps ; We are approaching towards X = N ; We are approaching towards X = 1 ; Function to return the count of steps ; Take the minimum of both moves independently ; Update count and current positions ; driver program
function steps ( cur , x , n ) { if ( x == 0 ) return Number . MAX_VALUE ; if ( x > 0 ) return Math . abs ( ( n - cur ) / x ) ; else return Math . abs ( ( cur - 1 ) / x ) ; } function countSteps ( curx , cury , n , m , moves ) { let count = 0 ; let k = moves . length ; for ( let i = 0 ; i < k ; i ++ ) { let x = moves [ i ] [ 0 ] ; let y = moves [ i ] [ 1 ] ; let stepct = Math . min ( steps ( curx , x , n ) , steps ( cury , y , m ) ) ; count += stepct ; curx += stepct * x ; cury += stepct * y ; } return Math . floor ( count ) ; } let n = 4 , m = 5 , x = 1 , y = 1 ; let moves = [ [ 1 , 1 ] , [ 1 , 1 ] , [ 0 , - 2 ] ] ; document . write ( countSteps ( x , y , n , m , moves ) ) ;