6

Let's say there's n amount of entries, each of whom can take the value of 0 or 1. That means there's 2^n possible combinations of those entries. The number of entries can vary from 1 to 6.

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

Hans
  • 545
  • 2
  • 10
  • 20
  • 2
    Have you seen the answers to: http://stackoverflow.com/questions/127704/algorithm-to-return-all-combinations-of-k-elements-from-n – Shog9 Aug 22 '09 at 19:14

5 Answers5

17

You can achieve that just by printing the numbers 0..2^n-1 in binary form.

Nick Dandoulakis
  • 42,588
  • 16
  • 104
  • 136
  • Thanks, didn't think of that. Sometimes the answer is right in front of your nose yet you don't see it. – Hans Aug 22 '09 at 20:07
3

Might as well 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 lifted 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
Community
  • 1
  • 1
I. J. Kennedy
  • 24,725
  • 16
  • 62
  • 87
  • Sadly I don't understand a bit of Python, I mainly use Java. But I'll try to give it a shot. Thanks. – Hans Aug 22 '09 at 20:08
1

Generating the mth Lexicographical Element of a Mathematical Combination. LINK

And you must see this by DON KNUTH.(Generating all possible combinations.NOTE:C# code is also provide there.)

Pratik Deoghare
  • 35,497
  • 30
  • 100
  • 146
0

If possible values for each entries can be only 0 or 1, and you want just 0 and 1 combination, why don't you use the natural integers (in binary form) up to 2^(n-1)...as suggested above by Nick..and format those with '0' padding if you want string...

mshsayem
  • 17,557
  • 11
  • 61
  • 69
0

Or use itertools:

import itertools

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

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

Gooey
  • 4,740
  • 10
  • 42
  • 76