I'm pretty new to Mathematica and am trying to learn to solve problems in a functional way. The problem I was solving was to list the ways in which I could sum elements from a list (with repetitions), so the sum is less-than-or-equal to some value. The code below solves my problem just fine.
i = {7.25, 7.75, 15, 19, 22};
m = 22;
getSum[l_List, n_List] := Total[Thread[{l, n}] /. {x_, y_} -> x y];
t = Prepend[Map[Range[0, Floor[m/#]] &, i], List];
Outer @@ %;
Flatten[%, ArrayDepth[%] - 2];
Map[{#, getSum[i, #]} &, %];
DeleteCases[%, {_, x_} /; x > m || x == 0];
TableForm[Flatten /@ SortBy[%, Last], 0, TableHeadings -> {None, Append[i, "Total"]}]
However, the code checks a lot of unneccesary cases, which could be a problem if m
is bigger or the list is longer. My question is simply: what would be the most Mathematica-esque way to solve this problem with regard to both efficiency and code elegance.
Comments
Post a Comment