Count number of triplets in an array having sum in the range [ a , b ] | Function to count triplets ; Initialize result ; Fix the first element as A [ i ] ; Fix the second element as A [ j ] ; Now look for the third number ; Driver Code
< ? php function countTriplets ( $ arr , $ n , $ a , $ b ) { $ ans = 0 ; for ( $ i = 0 ; $ i < $ n - 2 ; $ i ++ ) { for ( $ j = $ i + 1 ; $ j < $ n - 1 ; $ j ++ ) { for ( $ k = $ j + 1 ; $ k < $ n ; $ k ++ ) if ( $ arr [ $ i ] + $ arr [ $ j ] + $ arr [ $ k ] >= $ a && $ arr [ $ i ] + $ arr [ $ j ] + $ arr [ $ k ] <= $ b ) $ ans ++ ; } } return $ ans ; } $ arr = array ( 2 , 7 , 5 , 3 , 8 , 4 , 1 , 9 ) ; $ n = sizeof ( $ arr ) ; $ a = 8 ; $ b = 16 ; echo countTriplets ( $ arr , $ n , $ a , $ b ) . " " ; ? >