Probability of distributing given balls into two halves having equal count of distinct colors | Stores the count of distinct colors in box1 ; Stores the count of distinct colors in box2 ; Function to calculate the required probability ; Calculate factorial from [ 1 , 10 ] ; Assign all distinct balls to second box ; Total number of balls ; Calculate total number of balls ; If K is an odd number ; Total ways of distributing the balls in two equal halves ; Required number of ways ; Return the required probability ; Function to calculate total number of possible distributions which satisfies the given conditions ; If used balls is equal to K / 2 ; If box1 is equal to box2 ; Base condition ; Stores the number of ways of distributing remaining balls without including the current balls in box1 ; Increment box1 by one ; Iterate over the range [ 1 , balls [ i ] ] ; If all the balls goes to box1 , then decrease box2 by one ; Total number of ways of selecting j balls ; Increment res by total number of valid ways of distributing the remaining balls ; Decrement box1 by one ; Increment box2 by 1 ; Function to calculate factorial of N ; Base Case ; Iterate over the range [ 1 , N ] ; Function to calculate NcR ; Driver Code ; Print the result
var box1 = 0 ; var box2 = 0 ; var fact = Array ( 11 ) ; function getProbability ( balls , M ) { factorial ( 10 ) ; box2 = M ; var K = 0 ; for ( var i = 0 ; i < M ; i ++ ) K += balls [ i ] ; if ( K % 2 == 1 ) return 0 ; var all = comb ( K , K / 2 ) ; var validPermutation = validPermutations ( K / 2 , balls , 0 , 0 , M ) ; return validPermutation / all ; } function validPermutations ( n , balls , usedBalls , i , M ) { if ( usedBalls == n ) { return box1 == box2 ? 1 : 0 ; } if ( i >= M ) return 0 ; var res = validPermutations ( n , balls , usedBalls , i + 1 , M ) ; box1 ++ ; for ( var j = 1 ; j <= balls [ i ] ; j ++ ) { if ( j == balls [ i ] ) box2 -- ; var combinations = comb ( balls [ i ] , j ) ; res += combinations * validPermutations ( n , balls , usedBalls + j , i + 1 , M ) ; } box1 -- ; box2 ++ ; return res ; } function factorial ( N ) { fact [ 0 ] = 1 ; for ( var i = 1 ; i <= N ; i ++ ) fact [ i ] = fact [ i - 1 ] * i ; } function comb ( n , r ) { var res = fact [ n ] / fact [ r ] ; res /= fact [ n - r ] ; return res ; } var arr = [ 2 , 1 , 1 ] ; var N = 4 ; var M = arr . length ; document . write ( getProbability ( arr , M ) ) ;