Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating Combinations

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.

like image 203
Dr. belisarius Avatar asked Apr 27 '11 18:04

Dr. belisarius


People also ask

How do you generate all possible combinations of one list?

Enter the formula =List1. Expand out the new List1 column and then Close & Load the query to a table. The table will have all the combinations of items from both lists and we saved on making a custom column in List1 and avoided using a merge query altogether!

What is combination algorithm?

The algorithm assumes that we have a set containing elements: {0, 1, … , }. Then, we generate the subsets containing elements in the form , starting from the smallest lexicographic order: The algorithm visits all -combinations. It recursively represents multiple nested for loops.


2 Answers

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

is the built-in way.

like image 110
cah Avatar answered Sep 24 '22 06:09

cah


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.

like image 28
Mr.Wizard Avatar answered Sep 21 '22 06:09

Mr.Wizard