Hello, I'm going through Introduction to programming with MMA by R.Gaylord and there is an exemple in chapter 7 about recursively creating k-elements subsets of a given set.(adsbygoogle = window.adsbygoogle || []).push({});

subsets[Range[5], 2] should give {{1, 2}, {1, 3}, {1, 4}, {1, 5}, {2, 3}, {2, 4}, {2,5}, {3,4}, {3, 5}, {4, 5}}

The problem is, I can't figure out how he created this function. He explains only the tip of the iceberg. I tried the common ways of analyzing using trace but the resulting output is way too big. Any tips on why this function works and how you would go about creating it from just knowing what you have to do would be appreciated.

Code (Text):subsets[lis_, 0] := {{}}

subsets[{}, k_] := {}

subsets[lis_, k_] := Module[{res = subsets[Rest[lis], k - 1]},

Join[

Map[(Join[{First[lis]}, #] &), res],

subsets[Rest[lis], k]

]

]

Code (Text):In[9]:= subsets[Range[5], 2]

Out[9]= {{1, 2}, {1, 3}, {1, 4}, {1, 5}, {2, 3}, {2, 4}, {2, 5}, {3,

4}, {3, 5}, {4, 5}}

**Physics Forums | Science Articles, Homework Help, Discussion**

The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

# Recursion Problem in MMA

**Physics Forums | Science Articles, Homework Help, Discussion**