I wrote the following to generate a multiset with the same number of items over a fixed range:
ConstantArray[#, 3]& /@ Range[9] // Flatten
{1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9}
This approach uses four named functions (Range
, Flatten
, ConstantArray
and Map
(/@
)) and one pure function (ending with &
).
Is there a way to do the same thing with fewer functions?
Also, if I wanted to have variable numbers of items in my multiset how would I do that?
For example, let's say I wanted a multiset like { 1, 1, 1, 1, 2, 2, 3, 4, 4, 4, 6, 6, 7, 8, 8, 8 }
.
By a "variable number of items" I do not mean random, I mean a specified variable number.
Answer
f[n_, k_] := Table[ConstantArray[i, n], {i, k}]
Now you can vary the number of items of each:
f[3, 9] // Flatten
{1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9}
f[4, 10] // Flatten
{1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10}
for random Situation:
fRandom[n_, k_] := Table[ConstantArray[i, RandomInteger[{1, n}]], {i, k}]
For your second situation try this;
Inner[ConstantArray, Range[8], {4, 2, 1, 3, 0, 2, 1, 3}, List] // Flatten
{1, 1, 1, 1, 2, 2, 3, 4, 4, 4, 6, 6, 7, 8, 8, 8}
Comments
Post a Comment