Number of Triangles that can be formed given a set of lines in Euclidean Plane | Java program to find the number of triangles that can be formed using a set of lines in Euclidean Plane ; Double variables can ' t ▁ be ▁ checked ▁ precisely ▁ using ▁ ' == ' this function returns true if the double variables are equal ; This function returns the number of triangles for a given set of lines ; Slope array stores the slope of lines ; Slope array is sorted so that all lines with same slope come together ; After sorting slopes , count different slopes . k is index in count [ ] . ; Count of current slope ; Calculating sum1 ( Sum of all slopes ) sum1 = m1 + m2 + ... ; Calculating sum2 . sum2 = m1 * m2 + m2 * m3 + ... ; Needed for sum3 ; Calculating sum3 which gives the final answer m1 * m2 * m3 + m2 * m3 * m4 + ... ; Driver code ; Lines are stored as arrays of a , b and c for ' ax + by = c ' ; n is the number of lines
import java . util . * ; class GFG { static double EPSILON = 1.0842e-19 ; static boolean compareDoubles ( double A , double B ) { double diff = A - B ; return ( diff < EPSILON ) && ( - diff < EPSILON ) ; } static int numberOfTringles ( int [ ] a , int [ ] b , int [ ] c , int n ) { Vector < Double > slope = new Vector < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) slope . add ( ( double ) ( a [ i ] * 1.0 ) / b [ i ] ) ; Collections . sort ( slope ) ; int [ ] count = new int [ n ] ; int k = 0 ; int this_count = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( compareDoubles ( ( double ) slope . get ( i ) , ( double ) slope . get ( i - 1 ) ) ) this_count ++ ; else { count [ k ++ ] = this_count ; this_count = 1 ; } } count [ k ++ ] = this_count ; int sum1 = 0 ; for ( int i = 0 ; i < k ; i ++ ) sum1 += count [ i ] ; int sum2 = 0 ; int temp [ ] = new int [ n ] ; for ( int i = 0 ; i < k ; i ++ ) { temp [ i ] = count [ i ] * ( sum1 - count [ i ] ) ; sum2 += temp [ i ] ; } sum2 /= 2 ; int sum3 = 0 ; for ( int i = 0 ; i < k ; i ++ ) sum3 += count [ i ] * ( sum2 - temp [ i ] ) ; sum3 /= 3 ; return sum3 ; } public static void main ( String [ ] args ) { int a [ ] = { 1 , 2 , 3 , 4 } ; int b [ ] = { 2 , 4 , 5 , 5 } ; int c [ ] = { 5 , 7 , 8 , 6 } ; int n = a . length ; System . out . println ( " The ▁ number ▁ of ▁ triangles ▁ " + " that ▁ can ▁ be ▁ formed ▁ are : ▁ " + numberOfTringles ( a , b , c , n ) ) ; } }