views:

511

answers:

4

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?

+5  A: 

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

Nick D
Thanks, didn't think of that. Sometimes the answer is right in front of your nose yet you don't see it.
Hans
+1  A: 

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.)

TheMachineCharmer
A: 

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
+3  A: 

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
I. J. Kennedy
Sadly I don't understand a bit of Python, I mainly use Java. But I'll try to give it a shot. Thanks.
Hans