Alex Rivera | Logout

Loop through different sets of unique permutations

Asked 2010-12-31T05:50:43.523
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?

Edit
Report

1 Answer

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
    }
}
answered 2011-01-01T16:29:57.833

Your Answer