Count number of triangles cut by the given horizontal and vertical line segments | Java program for the above approach ; Store the minimum and maximum X and Y coordinates ; Function to convert String to int ; Function to print the number of triangles cut by each line segment ; Initialize Structure ; Find maximum and minimum X and Y coordinates for each triangle ; Minimum X ; Maximum X ; Minimum Y ; Maximum Y ; Traverse each cut from 0 to M - 1 ; Store number of triangles cut ; Extract value from the line segment String ; If cut is made on X - axis ; Check for each triangle if x lies b / w max and min X coordinates ; If cut is made on Y - axis ; Check for each triangle if y lies b / w max and min Y coordinates ; Print answer for ith cut ; Driver Code ; Given coordinates of triangles ; Given cuts of lines ; Function Call
import java . util . * ; class GFG { static class Tri { int MinX , MaxX , MinY , MaxY ; } ; static int StringtoInt ( String s ) { return Integer . valueOf ( s ) ; } static int min ( int a , int b , int c ) { return Math . min ( a , Math . min ( b , c ) ) ; } static int max ( int a , int b , int c ) { return Math . max ( a , Math . max ( b , c ) ) ; } static void TriangleCuts ( int [ ] [ ] Triangle , String Cuts [ ] , int N , int M , int COL ) { Tri [ ] Minimized = new Tri [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { Minimized [ i ] = new Tri ( ) ; Minimized [ i ] . MaxX = 0 ; Minimized [ i ] . MaxY = 0 ; Minimized [ i ] . MinX = 0 ; Minimized [ i ] . MinY = 0 ; } for ( int i = 0 ; i < N ; i ++ ) { int x1 = Triangle [ i ] [ 0 ] ; int y1 = Triangle [ i ] [ 1 ] ; int x2 = Triangle [ i ] [ 2 ] ; int y2 = Triangle [ i ] [ 3 ] ; int x3 = Triangle [ i ] [ 4 ] ; int y3 = Triangle [ i ] [ 5 ] ; Minimized [ i ] . MinX = min ( x1 , x2 , x3 ) ; Minimized [ i ] . MaxX = max ( x1 , x2 , x3 ) ; Minimized [ i ] . MinY = min ( y1 , y2 , y3 ) ; Minimized [ i ] . MaxY = max ( y1 , y2 , y3 ) ; } for ( int i = 0 ; i < M ; i ++ ) { String Cut = Cuts [ i ] ; int CutCount = 0 ; int CutVal = StringtoInt ( Cut . substring ( 2 , Cut . length ( ) ) ) ; if ( Cut . charAt ( 0 ) == ' X ' ) { for ( int j = 0 ; j < N ; j ++ ) { if ( ( Minimized [ j ] . MinX ) < ( CutVal ) && ( Minimized [ j ] . MaxX ) > ( CutVal ) ) { CutCount ++ ; } } } else if ( Cut . charAt ( 0 ) == ' Y ' ) { for ( int j = 0 ; j < N ; j ++ ) { if ( ( Minimized [ j ] . MinY ) < ( CutVal ) && ( Minimized [ j ] . MaxY ) > ( CutVal ) ) { CutCount ++ ; } } } System . out . print ( CutCount + " ▁ " ) ; } } public static void main ( String [ ] args ) { int [ ] [ ] Triangle = { { 0 , 2 , 2 , 9 , 8 , 5 } , { 5 , 0 , 6 , 3 , 7 , 0 } } ; int N = Triangle . length ; int COL = 6 ; String Cuts [ ] = { " X = 2" , " Y = 2" , " Y = 9" } ; int M = Cuts . length ; TriangleCuts ( Triangle , Cuts , N , M , COL ) ; } }