Number of horizontal or vertical line segments to connect 3 points | Function to check if the third point forms a rectangle with other two points at corners ; Returns true if point k can be used as a joining point to connect using two line segments ; Check for the valid polyline with two segments ; Check whether the X - coordinates or Y - cocordinates are same . ; Iterate over all pairs to check for two line segments ; Otherwise answer is three . ; Driver code
< ? php function isBetween ( $ a , $ b , $ c ) { return min ( $ a , $ b ) <= $ c and $ c <= max ( $ a , $ b ) ; } function canJoin ( $ x , $ y , $ i , $ j , $ k ) { return ( $ x [ $ k ] == $ x [ $ i ] or $ x [ $ k ] == $ x [ $ j ] ) and isBetween ( $ y [ $ i ] , $ y [ $ j ] , $ y [ $ k ] ) or ( $ y [ $ k ] == $ y [ $ i ] or $ y [ $ k ] == $ y [ $ j ] ) and isBetween ( $ x [ $ i ] , $ x [ $ j ] , $ x [ $ k ] ) ; } function countLineSegments ( $ x , $ y ) { if ( ( $ x [ 0 ] == $ x [ 1 ] and $ x [ 1 ] == $ x [ 2 ] ) or ( $ y [ 0 ] == $ y [ 1 ] and $ y [ 1 ] == $ y [ 2 ] ) ) return 1 ; else if ( canJoin ( $ x , $ y , 0 , 1 , 2 ) or canJoin ( $ x , $ y , 0 , 2 , 1 ) || canJoin ( $ x , $ y , 1 , 2 , 0 ) ) return 2 ; else return 3 ; } $ x = array ( ) ; $ y = array ( ) ; $ x [ 0 ] = -1 ; $ y [ 0 ] = -1 ; $ x [ 1 ] = -1 ; $ y [ 1 ] = 3 ; $ x [ 2 ] = 4 ; $ y [ 2 ] = 3 ; echo countLineSegments ( $ x , $ y ) ; ? >