Distribution of a Number in Array within a Range | Function for the distribution of the number ; Distribute the number among k elements ; If there is some remaining sum to distribute ; If there are elements remaining to distribute i . e . ( n - k ) ; Divide the remaining sum into n - k elements ; Print the distribution ; Driver code
function distribution ( n , k , l , r , S , Sk ) { let a = new Array ( n ) ; let len = k , temp , rem , s ; let diff = S - Sk ; for ( let i = 0 ; i < len ; i ++ ) { temp = Sk / k ; rem = Sk % k ; if ( temp + rem >= l && temp + rem <= r ) { a [ i ] = temp ; } else if ( temp + rem > r ) { a [ i ] = r ; } else if ( temp + rem < r ) { document . write ( " " ) ; return ; } Sk = Sk - a [ i ] ; k = k - 1 ; } if ( Sk > 0 ) { document . write ( " " ) ; return ; } if ( len ) { k = n - len ; for ( let i = len ; i < n ; i ++ ) { temp = diff / k ; rem = diff % k ; if ( temp + rem >= l && temp + rem <= r ) { a [ i ] = temp ; } else if ( temp + rem > r ) { a [ i ] = r ; } else if ( temp + rem < r ) { document . write ( " " ) ; return ; } diff = diff - a [ i ] ; k = k - 1 ; } if ( diff ) { document . write ( " " ) ; return ; } } for ( let i = 0 ; i < n ; i ++ ) { document . write ( a [ i ] + " " ) ; } } let n = 5 , k = 3 , l = 1 , r = 5 , S = 13 , Sk = 9 ; distribution ( n , k , l , r , S , Sk ) ;