Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

All possible combinations of elements

Tags:

combinations

I'd like to know a possible algorithm to calculate all possible combinations, without repetitions, starting from length=1 until length=N of N elements.

Example:

Elements: 1, 2, 3.

Output:

1
2
3
12
13
23
123
like image 365
Dario Avatar asked Sep 24 '09 13:09

Dario


People also ask

How do you find all possible combinations?

The formula for combinations is nCr = n! / r! * (n - r)!, where n represents the number of items, and r represents the number of items being chosen at a time.

What is the combinations of elements?

Elements combine to form chemical compounds that are often divided into two categories. Metals often react with nonmetals to form ionic compounds. These compounds are composed of positive and negative ions formed by adding or subtracting electrons from neutral atoms and molecules.

How many combinations are in the periodic table?

Similar to letters in the alphabet, elements can combine and react in many ways. In fact, the permutations of all possible chemical combinations of elements are greater than the estimated number of atoms in the visible universe! If we include the noble gases in the permutations, there would be 6.62×10184 possibilities.

What are possible combinations?

Explanation: The total number of possible combinations of a series of items is the product of the total possibility for each of the items. Thus, for the letters, there are 26 possibilities for each of the 3 slots, and for the numbers, there are 10 possibilities for each of the 3 slots.


1 Answers

Look at the binary presentation of the numbers 0 to 2^n - 1.

n = 3

i  Binary  Combination

   CBA

0  000
1  001     A
2  010       B
3  011     A B
4  100         C
5  101     A   C
6  110       B C
7  111     A B C

So you just have to enumerate the numbers 1 to 2^n - 1 and look at the binary representation to know which elements to include. If you want to have them ordered by the number of elements post sort them or generate the numbers in order (there are several example on SO).

like image 136
Daniel Brückner Avatar answered Sep 19 '22 06:09

Daniel Brückner