Count triplets with sum smaller than a given value | A Simple Javascript program to count triplets with sum smaller than a given value ; Initialize result ; Fix the first element as A [ i ] ; Fix the second element as A [ j ] ; Now look for the third number ; Driver method to test the above function
let arr = [ 5 , 1 , 3 , 4 , 7 ] ; function countTriplets ( n , sum ) { let ans = 0 ; for ( let i = 0 ; i < n - 2 ; i ++ ) { for ( let j = i + 1 ; j < n - 1 ; j ++ ) { for ( let k = j + 1 ; k < n ; k ++ ) if ( arr [ i ] + arr [ j ] + arr [ k ] < sum ) ans ++ ; } } return ans ; } let sum = 12 ; document . write ( countTriplets ( arr . length , sum ) ) ;