Random list of M non | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printArr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << arr [ i ] << " ▁ " ; } void randomList ( int m , int n ) { int arr [ m ] = { 0 } ; srand ( time ( 0 ) ) ; for ( int i = 0 ; i < n ; i ++ ) { arr [ rand ( ) % m ] ++ ; } printArr ( arr , m ) ; } int main ( ) { int m = 4 , n = 8 ; randomList ( m , n ) ; return 0 ; }