If I have a list of lists $a$ and a list of occurrences of each sublist $n$
a={ {1,1,1}, {2,2,2}, {3,3,3} }
n={1,3,2}
what is the most efficient way to get the following list?
l={{1,1,1},{2,2,2},{2,2,2},{2,2,2},{3,3,3},{3,3,3}}
My current implementation is
l=Flatten[Table[Table[a[[i]],{x,n[[i]]}],{i,Range[Length[n]]}],1]
EDIT
Thank you for the answers!
For the problem as posted, the fastest solution is Catenate[...]
from march
(inspired by J.M.
) at 1.7 10^-5 seconds (AbsoluteTiming), with all other solutions being above 2 10^-5.
If I drastically increase the number of samples I want (for example multiplying n*100), then Catenate[MapThread[Table, {a, List /@ n}]];
takes 1.5 10^-3 seconds and the fastest solution by far is a[[Join @@ MapIndexed[ConstantArray[#2[[1]], #1] &, n]]];
from ubpdqn
, at 7.7 10^-5.
In both cases, solutions from garej
had intermediate timings.
So I guess the ideal solution depends on the exact problem (size of the array, number of samples, ...) and may or may not have a great impact on the overall performance.
Answer
a[[Join @@ MapIndexed[ConstantArray[#2[[1]], #1] &, n]]]
Comments
Post a Comment