10

I'm having a hard time getting started to layout code for this problem.

I have a fixed amount of random numbers, in this case 8 numbers. R[] = { 1, 2, 3, 4, 5, 6, 7, 8 };

That are going to be placed in 3 sets of numbers, with the only constraint that each set contain minimum one value, and each value can only be used once. Edit: all 8 numbers should be used

For example:

R1[] = { 1, 4 }

R2[] = { 2, 8, 5, 6 }

R3[] = { 7, 3 }

I need to loop through all possible combinations of a set R1, R2, R3. Order is not important, so if the above example happened, I don't need

R1[] = { 4, 1 }

R2[] = { 2, 8, 5, 6 }

R3[] = { 7, 3 }

NOR

R1[] = { 2, 8, 5, 6 }

R2[] = { 7, 3 }

R3[] = { 1, 4 }

What is a good method?

2
  • In the example that you give, all numbers are used. Is this an accident or do you always want for this to be the case? Dec 31, 2010 at 6:09
  • @Vincent @aaron I've assumed yes for both in my answer.
    – moinudin
    Dec 31, 2010 at 7:59

4 Answers 4

3

I have in front of me Knuth Volume 4, Fascicle 3, Generating all Combinations and Partitions, section 7.2.1.5 Generating all set partitions (page 61 in fascicle).

First he details Algorithm H, Restricted growth strings in lexicographic order due to George Hutchinson. It looks simple, but I'm not going to dive into it just now.

On the next page under an elaboration Gray codes for set partitions he ponders:

Suppose, however, that we aren't interested in all of the partitions; we might want only the ones that have m blocks. Can we run this through the smaller collection of restricted growth strings, still changing one digit at a time?

Then he details a solution due to Frank Ruskey.

The simple solution (and certain to be correct) is to code Algorithm H filtering on partitions where m==3 and none of the partitions are the empty set (according to your stated constraints). I suspect Algorithm H runs blazingly fast, so the filtering cost will not be large.

If you're implementing this on an 8051, you might start with the Ruskey algorithm and then only filter on partitions containing the empty set.

If you're implementing this on something smaller than an 8051 and milliseconds matter, you can seed each of the three partitions with a unique element (a simple nested loop of three levels), and then augment by partitioning on the remaining five elements for m==3 using the Ruskey algorithm. You won't have to filter anything, but you do have to keep track of which five elements remain to partition.

The nice thing about filtering down from the general algorithm is that you don't have to verify any cleverness of your own, and you change your mind later about your constraints without having to revise your cleverness.

I might even work a solution later, but that's all for now.

P.S. for the Java guppies: I discovered searching on "George Hutchison restricted growth strings" a certain package ca.ubc.cs.kisynski.bell with documentation for method growthStrings() which implements the Hutchison algorithm.

Appears to be available at http://www.cs.ubc.ca/~kisynski/code/bell/

1

Probably not the best approach but it should work.

Determine number of combinations of three numbers which sum to 8:

1,1,6
1,2,5
1,3,4
2,2,4
2,3,3

To find the above I started with:

6,1,1 then subtracted 1 from six and added it to the next column...
5,2,1 then subtracted 1 from second column and added to next column...
5,1,2 then started again at first column...
4,2,2 carry again from second to third
4,1,3 again from first...
3,2,3 second -> third
3,1,4 

knowing that less than half is 2 all combinations must have been found... but since the list isn't long we might as well go to the end.

Now sort each list of 3 from greatest to least(or vice versa) Now sort each list of 3 relative to each other. Copy each unique list into a list of unique lists. We now have all the combinations which add to 8 (five lists I think).

Now consider a list in the above set

6,1,1 all the possible combinations are found by:

8 pick 6, (since we picked six there is only 2 left to pick from) 2 pick 1, 1 pick 1 which works out to 28*2*1 = 56, it is worth knowing how many possibilities there are so you can test.

n choose r (pick r elements from n total options)

n C r = n! / [(n-r)! r!]

So now you have the total number of iterations for each component of the list for the first one it is 28...

Well picking 6 items from 8 is the same as creating a list of 8 minus 2 elements, but which two elements?

Well if we remove 1,2 that leaves us with 3,4,5,6,7,8. Lets consider all groups of 2... Starting with 1,2 the next would be 1,3... so the following is read column by column.

12
13 23 
14 24 34
15 25 35 45
16 26 36 46 56
17 27 37 47 57 67
18 28 38 48 58 68 78

Summing each of the above columns gives us 28. (so this only covered the first digit in the list (6,1,1) repeat the procedure for the second digit (a one) which is "2 Choose 1" So of the left over two digits from the above list we pick one of two and then for the last we pick the remaining one.

I know this is not a detailed algorithm but I hope you'll be able to get started.

1

Turn the problem on it's head and you'll find a straight-forward solution. You've got 8 numbers that each need to be assigned to exactly one group; The "solution" is only a solution if at least one number got assigned to each group.

The trivial implementation would involve 8 for loops and a few IF's (pseudocode):

for num1 in [1,2,3]
  for num2 in [1,2,3]
    for num3 in [1,2,3]
      ...
        if ((num1==1) or (num2==1) or (num3 == 1) ... (num8 == 1)) and ((num1 == 2) or ... or (num8 == 2)) and ((num1 == 3) or ... or (num8 == 3))
          Print Solution!

It may also be implemented recursively, using two arrays and a couple of functions. Much nicer and easier to debug/follow (pseudocode):

numbers = [1, 2, 3, 4, 5, 6, 7, 8]
positions = [0, 0, 0, 0, 0, 0, 0, 0]

function HandleNumber(i) {
  for position in [1,2,3] {
    positions[i] = position;
    if (i == LastPosition) {
        // Check if valid solution (it's valid if we got numbers in all groups)
        // and print solution!
      }
    else HandleNumber(i+1)
  }      
}

The third implementation would use no recursion and a little bit of backtracking. Pseudocode, again:

numbers = [1,2,3,4,5,6,7,8]
groups = [0,0,0,0,0,0,0,0]

c_pos = 0 // Current position in Numbers array; We're done when we reach -1
while (cpos != -1) {
  if (groups[c_pos] == 3) {
      // Back-track
      groups[c_pos]=0;
      c_pos=c_pos-1
    }
  else {
     // Try the next group
     groups[c_pos] = groups[c_pos] + 1
     // Advance to next position OR print solution
     if (c_pos == LastPostion) {
         // Check for valid solution (all groups are used) and print solution!
       }
     else
       c_pos = c_pos + 1
    }
}
0

Generate all combinations of subsets recursively in the classic way. When you reach the point where the number of remaining elements equals the number of empty subsets, then restrict yourself to the empty subsets only.

Here's a Python implementation:

def combinations(source, n):
  def combinations_helper(source, subsets, p=0, nonempty=0):
    if p == len(source):
      yield subsets[:]
    elif len(source) - p == len(subsets) - nonempty:
      empty = [subset for subset in subsets if not subset]
      for subset in empty:
        subset.append(source[p])
        for combination in combinations_helper(source, subsets, p+1, nonempty+1):
          yield combination
        subset.pop()
    else:
      for subset in subsets:
        newfilled = not subset
        subset.append(source[p])
        for combination in combinations_helper(source, subsets, p+1, nonempty+newfilled):
          yield combination
        subset.pop()

  assert len(source) >= n, "Not enough items"
  subsets = [[] for _ in xrange(n)]
  for combination in combinations_helper(source, subsets):
    yield combination

And a test:

>>> for combination in combinations(range(1, 5), 2):
...   print ', '.join(map(str, combination))
... 
[1, 2, 3], [4]
[1, 2, 4], [3]
[1, 2], [3, 4]
[1, 3, 4], [2]
[1, 3], [2, 4]
[1, 4], [2, 3]
[1], [2, 3, 4]
[2, 3, 4], [1]
[2, 3], [1, 4]
[2, 4], [1, 3]
[2], [1, 3, 4]
[3, 4], [1, 2]
[3], [1, 2, 4]
[4], [1, 2, 3]
>>> len(list(combinations(range(1, 9), 3)))
5796

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.