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 - The Fusion of Science and Community**

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

# Recursion Problem in MMA

Loading...

Similar Threads - Recursion Problem | Date |
---|---|

Mathematica: Recursive expression | Jun 13, 2013 |

How do I avoid the recursion limit in Mathematica? | Apr 4, 2013 |

Mathematica 8.0 - solve two recursive relations | Nov 12, 2012 |

Matlab recursion (error in book?) | Nov 11, 2012 |

Recursive sequence problem: proofs by mathematical induction | Sep 24, 2004 |

**Physics Forums - The Fusion of Science and Community**