Random list of M non | Java implementation of the approach ; 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
class GFG { static void printArr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } static void randomList ( int m , int n ) { int arr [ ] = new int [ m ] ; for ( int i = 0 ; i < n ; i ++ ) { arr [ ( int ) ( Math . random ( ) * m ) ] ++ ; } printArr ( arr , m ) ; } public static void main ( String args [ ] ) { int m = 4 , n = 8 ; randomList ( m , n ) ; } }