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
function countTriplets ( arr , n , a , b ) { var ans = 0 ; for ( var i = 0 ; i < n - 2 ; i ++ ) { for ( var j = i + 1 ; j < n - 1 ; j ++ ) { for ( var k = j + 1 ; k < n ; k ++ ) if ( arr [ i ] + arr [ j ] + arr [ k ] >= a && arr [ i ] + arr [ j ] + arr [ k ] <= b ) ans ++ ; } } return ans ; } var arr = [ 2 , 7 , 5 , 3 , 8 , 4 , 1 , 9 ] ; var n = arr . length ; var a = 8 , b = 16 ; document . write ( countTriplets ( arr , n , a , b ) ) ;