text: Probability of distributing given balls into two halves having equal count of distinct colors | C # program for the above approach ; 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
code: using System ; public class GFG { static int box1 = 0 ; static int box2 = 0 ; static int [ ] fact = new int [ 11 ] ; public static double getProbability ( int [ ] balls ) { factorial ( 10 ) ; box2 = balls . Length ; int K = 0 ; for ( int i = 0 ; i < balls . Length ; i ++ ) K += balls [ i ] ; if ( K % 2 == 1 ) return 0 ; long all = comb ( K , K / 2 ) ; long validPermutationss = validPermutations ( ( K / 2 ) , balls , 0 , 0 ) ; return ( double ) validPermutationss / all ; } static long validPermutations ( int n , int [ ] balls , int usedBalls , int i ) { if ( usedBalls == n ) { return box1 == box2 ? 1 : 0 ; } if ( i >= balls . Length ) return 0 ; long res = validPermutations ( n , balls , usedBalls , i + 1 ) ; box1 ++ ; for ( int j = 1 ; j <= balls [ i ] ; j ++ ) { if ( j == balls [ i ] ) box2 -- ; long combinations = comb ( balls [ i ] , j ) ; res += combinations * validPermutations ( n , balls , usedBalls + j , i + 1 ) ; } box1 -- ; box2 ++ ; return res ; } static void factorial ( int N ) { fact [ 0 ] = 1 ; for ( int i = 1 ; i <= N ; i ++ ) fact [ i ] = fact [ i - 1 ] * i ; } static long comb ( int n , int r ) { long res = fact [ n ] / fact [ r ] ; res /= fact [ n - r ] ; return res ; } public static void Main ( String [ ] args ) { int [ ] arr = { 2 , 1 , 1 } ; int N = 4 ; Console . WriteLine ( getProbability ( arr ) ) ; } }