I want all subsets of the digits 1 through 9 containing exactly 2 elements. But I also want their respective totals. All from a single line command.

I already know how to generate the subsets:

Subsets[Range@9, {2}]

This gives {{1,2},{1,3},{1,4},... etc.

But I am looking for something like this:

So {{1,2},3},{{1,3,},4},{{1,4},5},... etc..

I can generate the totals separately:

Total/@Subsets[Range@9, {2}]

But I can't generate it all at once, in one line. Any ideas? I have a feeling a pure function might help.

  • 5
    $\begingroup$ {#, Total[#]} & /@ Subsets[Range@9, {2}] $\endgroup$
    – kirma
    Commented Aug 29, 2023 at 20:44
  • $\begingroup$ Thank you. I never thought to map a pure function to the expression. $\endgroup$ Commented Aug 29, 2023 at 20:46
  • 2
    $\begingroup$ A lot can be done with pure functions (here it applies to the evaluated result, not the function) - I must admit that most of what I do in Mathematica is chains of pure functions (if practically plausible). It is not necessarily the most readable form but perfectly capable of accomplishing most tasks. $\endgroup$
    – kirma
    Commented Aug 29, 2023 at 20:49
  • 3
    $\begingroup$ You can also use replace with a suitable rule: Subsets[Range@9, {2}] /. {x_, y_} -> {{x, y}, Total[{x, y}]} $\endgroup$ Commented Aug 29, 2023 at 21:14
  • $\begingroup$ Transpose@Through[{Identity, Map[Total]}[Subsets[Range@9, {2}]]] $\endgroup$
    – Syed
    Commented Aug 30, 2023 at 8:51


Browse other questions tagged or ask your own question.