Count ways to select K array elements lying in a given range | Function to calculate factorial of all the numbers up to N ; Factorial of 0 is 1 ; Calculate factorial of all the numbers upto N ; Calculate factorial of i ; Function to find the count of ways to select at least K elements whose values in range [ L , R ] ; Stores count of ways to select at least K elements whose values in range [ L , R ] ; Stores count of numbers having value lies in the range [ L , R ] ; Traverse the array ; Checks if the array elements lie in the given range ; Update cntNum ; Stores factorial of numbers upto N ; Calculate total ways to select at least K elements whose values lies in [ L , R ] ; Update cntWays ; Driver Code
function calculateFactorial ( N ) { var fact = Array ( N + 1 ) ; fact [ 0 ] = 1 ; for ( var i = 1 ; i <= N ; i ++ ) { fact [ i ] = fact [ i - 1 ] * i ; } return fact ; } function cntWaysSelection ( arr , N , K , L , R ) { var cntWays = 0 ; var cntNum = 0 ; for ( var i = 0 ; i < N ; i ++ ) { if ( arr [ i ] >= L && arr [ i ] <= R ) { cntNum ++ ; } } var fact = calculateFactorial ( cntNum ) ; for ( var i = K ; i <= cntNum ; i ++ ) { cntWays += fact [ cntNum ] / ( fact [ i ] * fact [ cntNum - i ] ) ; } return cntWays ; } var arr = [ 12 , 4 , 6 , 13 , 5 , 10 ] ; var N = arr . length ; var K = 3 ; var L = 4 ; var R = 10 ; document . write ( cntWaysSelection ( arr , N , K , L , R ) ) ;