# Generate lists that satisfy a condition in an efficient way

The following code produces lists of sublists with maximum length 5 that shuffle zeros around an ordered list (here {1,2}). It produces all permutations while keeping the ordering of the list {1,2} within the permutations:

mylst[K_]:=Select[Drop[Tuples[{0,1,2},K],1],Total[#]==3&&Count[#,1]==1&&#[[Position[#,x_/;!TrueQ[x==0],{1},1,Heads->False][[1,1]]]]!=2&]
mylst /@ Range[5]


Each of mylst[K] generates $K(K-1)/2$ terms.

Is there a better way to code mylst?

Just for fun, here is the pattern based version

mylst2[K_] := ReplaceList[
ConstantArray[0, K],
{a___, x_, b___, y_, c___} :> {a, 1, b, 2, c}
]

• Thanks for the simplified version! Seems really compact way to do the same task! Commented Jan 9, 2015 at 13:26
• @ChenStatsYu Surprising! Rule based solutions often have poor complexity, I guess in this case it works... Commented Jan 9, 2015 at 13:38
• mylst2[200]; // AbsoluteTiming (yours) VS mylst3[200]; // AbsoluteTiming (Carlo's), it's about {0.078000, Null} VS {0.780001, Null}. Nearly 10 times. Commented Jan 9, 2015 at 13:46
• No, I think your solution is better Pickett. I forfeit! Commented Jan 9, 2015 at 13:55
• @ChenStatsYu It isn't. Commented Jan 9, 2015 at 16:12
mylst2[K_] := Map[
ReplacePart[#, FirstPosition[#, 2] -> 1] &,

• That will do! I dont really use the case $K=0$. Commented Jan 9, 2015 at 13:27