3

I'm looking to write a method that takes an arbitrary number of NSArray objects, and returns a nested array of all possible complete combinations of the members of that array.

As I've been told in answer to this question, I'm looking to create a bipartite graph or, more precisely, a complete bipartite graph.

So, for instance, if I had two arrays:

NSArray *a1 = [NSArray arrayWithObjects:@"Blue", @"Green", @"Yellow", nil];
NSArray *a2 = [NSArray arrayWithObjects:@"Apple", @"Orange", @"Pear", nil];

I would want a method that took an array of those arrays:

NSArray *nestedArray = [NSArray arrayWithObjects:a1, a2, nil];

and returned an array of all possible combinations, of the same length. So, in this example, I'd want an array that looked roughly like this:

 [
      [@"Blue", @"Apple"],
      [@"Blue", @"Orange"],
      [@"Blue", @"Pear"],
      [@"Green", @"Apple"],
      [@"Green", @"Orange"],
      [@"Green", @"Pear"],
      [@"Yellow", @"Apple"],
      [@"Yellow", @"Orange"],
      [@"Yellow", @"Pear"]
]

As the number of objects in those arrays grew in size, so would the number of results, exponentially I believe. I'd probably then make this method a category on NSArray. Also, I'd want the results to be all of the same length. That is, if there were three source arrays, each of the nested arrays returned by the method should have a length of three.

Any ideas of the most elegant way to do this?

Chris Ladd
  • 2,795
  • 1
  • 29
  • 22
  • 1
    What you want are not combinations, they are not permutations, and their number does not grow exponentially "as the arrays grew in size", but as the *number of arrays* grows. – Fred Foo Mar 21 '11 at 01:19
  • @larsmans, I see your point -- is the new title clearer? – Chris Ladd Mar 21 '11 at 14:11

2 Answers2

1

What do you mean with all combinations? If you want all combinations why do you need two list? If you want a bipartite graph then you want to correct your question.

Micromega
  • 12,486
  • 7
  • 35
  • 72
0

A recursive solution is probably a good solution. The function would only find the permutations of the first two arrays and then once combined into a single array, you would call this function again with the new combined array instead of the original arrays.

Eventually you would only have 1 array left and that would be the final result array.

drewag
  • 93,393
  • 28
  • 139
  • 128