6
$\begingroup$

I have created a subset of arrays:

b = Subsets[Range[10], {5}]
(* Out= {{1, 2, 3, 4, 5}, {1, 2, 3, 4, 6}, {1, 2, 3, 4, 7}, {1, 2, 3, 4, 8},
         {1, 2, 3, 4, 9}, ..., {6, 7, 8, 9, 10}} *)

This command shows the combinations I wish to evaluate with. How can I add the elements of each subset in the list above to get an output like:

{{15}, {16}, {17}, {18}, {19},..., {40}} 
$\endgroup$
9
$\begingroup$

Use Applyon the first level of the list b (@@@ is a shorthand), i.e.

Plus @@@ b

Or exactly what you want, then map List over Plus @@@ b, i.e.

List /@ Plus @@@ b
$\endgroup$
  • 3
    $\begingroup$ Aiming for brevity, you could also use: Tr /@ b $\endgroup$ – Mr.Wizard May 17 '12 at 19:40
  • $\begingroup$ Precisely {#} & /@ Tr /@ b. $\endgroup$ – Artes May 17 '12 at 22:22
  • 1
    $\begingroup$ List is as short as {#}& :-) $\endgroup$ – Mr.Wizard May 18 '12 at 3:07
9
$\begingroup$

Not sure I follow, but maybe Total[b, {2}]?

If the list of lists form is important: Transpose@{Total[b, {2}]}, or more simply as Artes just posted: List /@ Total[b, {2}]


Subsets returns an unpacked array, and in that case Plus @@@ b is faster. However, by packing the array this method will be an order of magnitude faster than Plus:

Transpose@{Total[Developer`ToPackedArray@b, {2}]}
$\endgroup$
  • $\begingroup$ I didn't realize that Plus can ever be faster than Total $\endgroup$ – Szabolcs May 18 '12 at 7:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.