3
$\begingroup$

I want to create a list which contains n sublists, whereby each sublist has a random length and contains integers from 0 to m:

A single results could be for n=6 and m=8:

{{1},{6,4},{7,6,3,8},{5,3},{0},{5,0,7,5,2,7}}
$\endgroup$
5
$\begingroup$
n = 6 ; m = 8; lmax = 10;

RandomInteger[{0, m}, #] & /@ RandomInteger[lmax, n] (* or *)
Table[RandomInteger[{0, m}], n, RandomInteger[lmax]] (* or *)
Table[RandomInteger[{0, m}, RandomInteger[lmax]], n] (* or *)
Array[RandomInteger[{0, m}, RandomInteger[lmax]] &, n]

{{7, 0, 6, 6, 3, 1, 4, 4}, {5, 6, 4}, {0, 7, 5, 1, 3, 7, 5, 0, 0}, {}, {1, 2}, {5, 8, 4, 1, 2}}

If you want to disallow empty lists use {1, lmax} in place of lmax above, e.g,

RandomInteger[{0, m}, #] & /@ RandomInteger[{1, lmax}, n]

{{7, 1, 7, 0, 1, 1, 4, 4}, {6, 5, 5, 0, 8, 1}, {6, 1, 8, 3, 6, 5, 0, 8, 2}, {7, 6}, {7, 5, 1, 8, 7, 5, 5, 8}, {0, 5}}

$\endgroup$
  • $\begingroup$ Thank you for the solutions. $\endgroup$ – lio Jul 5 '18 at 15:05
  • $\begingroup$ @lio, my pleasure. Thank you for the accept. $\endgroup$ – kglr Jul 5 '18 at 15:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.