What is an efficient algorithm for creating all possible combinations?

Let's say there are n number of records, each of which can take the value 0 or 1 . This means that there are 2 ^ n possible combinations of these entries. The number of entries can vary from 1 to 6 .

How can you create every possible combination as a sequence of numbers (i.e. for n = 2: 00, 01, 10, 11) without resorting to thousands of IFs?

+6
algorithm boolean combinations
source share
5 answers

You can achieve this by simply typing the numbers 0..2^n-1 in binary form.

+15
source share

You can also just use ints:

 n = 5 for x in range(2**n): print ''.join(str((x>>i)&1) for i in xrange(n-1,-1,-1)) 

Crazy decimal to binary conversion is canceled from this answer .

Output:

 00000 00001 00010 00011 00100 00101 00110 00111 01000 01001 01010 01011 01100 01101 01110 01111 10000 10001 10010 10011 10100 10101 10110 10111 11000 11001 11010 11011 11100 11101 11110 11111 
+3
source share

Generation of the m-th lexicographic element of a mathematical combination. LINK

And you should see this DON KNUTH . (Creating all possible combinations. NOTE : C # code also provide there.)

+1
source share

If the possible values ​​for each record can be only 0 or 1 , and you only need combinations of 0 and 1, why don't you use natural integers (in binary form) up to 2 ^ (n-1) ... as suggested above Nick .. and format those that have a "0" if a string is required ...

0
source share

Or use itertools :

 import itertools for item in itertools.product((1, 0), repeat=4): print item 

Note that the element is a tuple of 4 elements in this case.

0
source share

All Articles