Random list of M non | Utility function to print the elements of an array ; Function to generate a list of m random non - negative integers whose sum is n ; Create an array of size m where every element is initialized to 0 ; To make the sum of the final list as n ; Increment any random element from the array by 1 ; Print the generated list ; Driver code
function printArr ( arr , n ) { for ( let i = 0 ; i < n ; i ++ ) document . write ( arr [ i ] + " " ) ; } function randomList ( m , n ) { let arr = new Array ( m ) ; for ( let i = 0 ; i < arr . length ; i ++ ) { arr [ i ] = 0 ; } for ( let i = 0 ; i < n ; i ++ ) { arr [ ( Math . floor ( ( Math . random ( ) * n ) ) % m ) ] ++ ; } printArr ( arr , m ) ; } let m = 4 , n = 8 ; randomList ( m , n ) ;