I have an arbitrary list of unique elements:
lst = {a, b, c, d}
Documentation allows finding subsets with same number of elements, say 2
:
Subsets[lst, {2}]
(* {{a, b}, {a, c}, {a, d}, {b, c}, {b, d}, {c, d}} *)
What I need is to add some placeholder, i.e. 0
, to each subset.
{{a, b, 0, 0}, {a, 0, c, 0}, {a, 0, 0, d}, {0, b, c, 0}, {0, b, 0, d}, {0, 0, c, d}}
Replacements work slow (even freeze) for large lists and many subsets.
lst /. # & /@ (Thread[# -> 0] & /@ Complement[list, #] & /@ Subsets[lst, {2}])
I'd like to have a better way.
(Application - intertemporal choice problems with discrete time).
ReplacePart[ConstantArray[0, Length[lst]], Thread[# -> lst[[#]]]] & /@ Subsets[Range[Length[lst]], {2}]
doesn't work for you? $\endgroup$Normal@SparseArray[ MapThread[First@Position[lst, #] -> # &, Transpose@{#}] , Length@lst ] & /@ Subsets[lst, {2}]
, pretty similar to J.M.'s solution, but you can keep it in sparse form to save some memory for large lists. i.e. removeNormal
if you want. $\endgroup$SparseArray[Flatten[MapIndexed[Map[Function[k, Append[#2, k] -> lst[[k]]], #1] &, Subsets[Range[Length[lst]], {2}]]]]
. $\endgroup$