Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is an efficient algorithm to create all possible combinations?

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?

like image 391
Hans Avatar asked Aug 22 '09 19:08

Hans


People also ask

How do you get all possible combinations?

The formula for combinations is generally n! / (r! (n -- r)!), where n is the total number of possibilities to start and r is the number of selections made. In our example, we have 52 cards; therefore, n = 52. We want to select 13 cards, so r = 13.

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.

How do you create a combination in Java?

We set a constant value 2 to r, i.e., the number of items being chosen at a time. After that, we use the combination formula, i.e., fact(n) / (fact(r) * fact(n-r)) and store the result into the result variable.

How does Heap's algorithm work?

Heap. This algorithm is based on swapping elements to generate the permutations. It produces every possible permutation of these elements exactly once. This method is a systematic algorithm, which at each step chooses a pair of elements to switch in order to generate new permutations.


2 Answers

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

like image 171
Nick Dandoulakis Avatar answered Nov 15 '22 08:11

Nick Dandoulakis


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
like image 27
I. J. Kennedy Avatar answered Nov 15 '22 07:11

I. J. Kennedy