I am new in Mathematica and am stuck on a simple problem. Please advise:
I have the following list:
list = {
{"1", 1000},
{"2", 800},
{"3", 800}
};
I want to select subsets of the first elements Subsets[list[[All,1]]]
when the Total
of coresponding second elements is for example $>= 1000$.
So in this example the expected result is:
{{"1"}, {"1", "2"}, {"1", "3"}, {"2", "3"}, {"1", "2", "3"}}
I solved it using @Kuba's answer below, and added DeleteDuplicates to make it work better (produce less output) on large datasets:
lst = DeleteDuplicates[
If[
Total[#[[;; , 2]]] >= 1000,
#[[;; , 1]]] & /@ (Rest@ Subsets[list]) /. Null -> Sequence[]
]
// TableForm
>=1000
? If I understand correctly your expected result should be{{1}, {1,2}, {1,3}, {2,3}, {1,2,3}}
. $\endgroup$Subsets
has limits, so to speak... (especially on "unbounded" length of subsets). Say, you uselist = Table[{i, RandomInteger[{500, 1100}]}, {i, 20}]
(i.e. 20 elements in the initial list), on my machine, @Kuba's code takes 8sec (and on 25 elements, I didn't wait for it to finish. You could doWith[{subsets = Subsets[list, {1, \[Infinity]}]}, Pick[subsets[[All, All, 1]], UnitStep[Total /@ subsets[[All, All, 2]] - 1000], 1]]
which has the same problem, but better speed. So if the list is considerably longer, you'd need another approach... $\endgroup$