human
Count number of triplets in an array having sum in the range [ a , b ] | Function to find count of triplets having sum less than or equal to val ..
sort the input array ..
Initialize result.
to store sum.
Fix the first element.
Initialize other two elements as corner elements of subarray arr [ j + 1. . k ].
Use Meet in the Middle concept ..
If sum of current triplet is greater , then to reduce it decrease k ..
If sum is less than or equal to given value , then add possible triplets ( k - j ) to result ..
Function to return count of triplets having sum in range [ a , b ] ..
to store count of triplets ..
Find count of triplets having sum less than or equal to b and subtract count of triplets having sum less than or equal to a - 1..
Driver code"
Solution in Python:
assistant
#Here is code to count number of triplets in an array having sum in the range [ a , b ] and the other steps required.
 def countTripletsLessThan ( arr , n , val ) :
	arr . sort ( )
	ans = 0
	j = 0 ; k = 0
	sum = 0
	for i in range ( 0 , n - 2 ) :
		j = i + 1
		k = n - 1
		while j != k :
			sum = arr [ i ] + arr [ j ] + arr [ k ]
			if sum > val :
				k -= 1
			else :
				ans += ( k - j )
				j += 1
	return ans
def countTriplets ( arr , n , a , b ) :
	res = 0
	res = ( countTripletsLessThan ( arr , n , b ) - countTripletsLessThan ( arr , n , a - 1 ) )
	return res
if __name__ == " _ _ main _ _ " :
	arr = [ 2 , 7 , 5 , 3 , 8 , 4 , 1 , 9 ]
	n = len ( arr )
	a = 8 ; b = 16
	print ( countTriplets ( arr , n , a , b ) )