15

Every time I have to do this I "invent" a different way. Time to standardize. I suspect there is some default command I overlooked ready to do this, so I am sorry in advance if the question is too trivial.

What is the better (memory, performance) way to get:

 combinations[{1,2,3},2] = {{1,2},{1,3},{2,3}} 

with arbitrary elements in the input list, of course.

5
  • Only trivial if you think to search "subsets". If you, quite reasonably, only think to search "combinations" then, well, you've just done a great service to all such future people by asking this! Commented Apr 27, 2011 at 20:42
  • @dreeves Thank you sooo much! Now, if you really want to blame me, look at the third line of code I wrote here stackoverflow.com/questions/3815496/… Commented Apr 27, 2011 at 20:55
  • It took me two steps in the help center: combinations => Tuples => Subsets (of course I knew this already, so that may have helped) Commented Apr 27, 2011 at 21:09
  • 2
    C'mon @Sjoerd, we were talking about how difficult it is. I almost had my self-esteem restored, and you come with that comment :) Commented Apr 27, 2011 at 21:30
  • 1
    I had to do something to increase my own self-esteem. Mr.Wizard has consistently beaten me in the race to answering questions today. Self-esteem pretty low now. I have to find a tag of my own or so. Commented Apr 27, 2011 at 21:43

2 Answers 2

21
Subsets[{1, 2, 3}, {2}] 

is the built-in way.

Sign up to request clarification or add additional context in comments.

2 Comments

Damn,I knew it was too trivial :). Thanks!
cah, congratulations on the Enlightened badge!
7

Before Subsets was added as a core function, the Combinatorica function KSubsets was available.

Needs["Combinatorica`"] KSubsets[{1, 2, 3}, 2] (* {{1, 2}, {1, 3}, {2, 3}} *) 

Combinatorica still provides additional functionality, such as NextKSubset:

NextKSubset[{1, 2, 3}, {1, 3}] (* {2, 3} *) 

This last function can be very helpful for memory management.

1 Comment

You got to 4000! Congrats ... Now 4010

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.