How to duplicate list elements
Another one:
MapThread[ConstantArray, {S, RotateLeft[S]}]
It's a one-liner. Use Partition
to split the list up into pairs, with the offset and cyclic arguments to get what you want, and then apply ConstantArray
to each pair.
ClearAll[duplicate];
duplicate[list : {___Integer}] := ConstantArray @@@ Partition[list, 2, 1, 1];
duplicate[S]
(* {{3, 3, 3, 3}, {4, 4, 4, 4, 4, 4}, {6}, {1, 1}, {2, 2, 2, 2, 2}, {5, 5, 5}}*)
Update: Using Partition
with its undocumented sixth argument:
Partition[#, 2, 1, {1, -1}, {}, ConstantArray] & @ {3, 4, 6, 1, 2, 5}
{{3, 3, 3, 3}, {4, 4, 4, 4, 4, 4}, {6}, {1, 1}, {2, 2, 2, 2, 2}}
Original answer:
ClearAll[f0, f1, f2]
f0 = Table @@@ ({#, {##2, #} & @@ #} &@#) &;
f1 = Developer`PartitionMap[Internal`RepetitionFromMultiplicity@{#} &, #, 2, 1, 1] &;
f2 = Developer`PartitionMap[ConstantArray @@ # &, #, 2, 1, 1] &;
f3 = Normal@SparseArray[{}, {#}, #2] & @@@ ({#, {##2, #} & @@ #} &@#) &;
f0 @ {3, 4, 6, 1, 2, 5}
{{3, 3, 3, 3}, {4, 4, 4, 4, 4, 4}, {6}, {1, 1}, {2, 2, 2, 2, 2}, {5, 5, 5}}
Equal @@ (#@{3, 4, 6, 1, 2, 5} & /@ {f0, f1, f2, f3})
True
For fun:
☺ = {#} //. {♯1___, ♯2_, ♯3___}/;♯2>1 :> {♯1, 1, ♯2 - 1, ♯3} &;
☺☺ = # (☺ /@ {##2, #} & @@ #) &;
☺☺ @ {3, 4, 6, 1, 2, 5}
{{3, 3, 3, 3}, {4, 4, 4, 4, 4, 4}, {6}, {1, 1}, {2, 2, 2, 2, 2}, {5, 5, 5}}