Suppose I have a list of positive integers:
data={1, 1, 2, 3, 3, 3, 5, 5, 5, 7, 7, 8, 8, 9, 10, 10, 12, 16, 23}
I want to count the number of subsets up to length t (including an empty set) whose total doesn't exceed the value t.
The naive approach would be:
sumZaehl[t_, data_] :=
Length@Select[Total /@ Subsets[data, t], # <= t &]
But this would not work for larger list, because of the rapidly increasing number of subsets. I have an iterative method which works for larger list too:
sumZaehlIter[t_, data_] :=
Module[{n = Length[data], v, d, i, j},
For[i = 0, i <= t, i++, v[i] = 1];
For[i = 1, i <= n, i++,
d = data[[i]];
For[j = t, j >= d, j--,
v[j] = v[j] + v[j - d];
]];
v[t]]
Is there a functional way to realize this?
sumZaehlIter[3,data]
and Leonid'sv[3,data]
return 10. What are the other four sublists with a total not greater than 3? $\endgroup${3}
and one additional occurence for each of{1}
and{2,1}
. $\endgroup$