1

So I have a group of people, typically between 15 and 30 people. I have a class Person to represent every person. I also have a class Match with represents a duo with its properties $person1 and $person2, which incidentally can also both point to the same person to represent someone who's partitioned singularly.

So I have an array of all possible matches, which means all possible duos and all possible singles. With my current setup that adds up to about 120 matches. Now I want to find all possible configurations to put these duos and singles together so they add up to the whole group again. Of course this means that every person appears exactly one time in every configuration.

I conveniently formatted the array like this: $this->matches['John']['Mary'] contains the Match of John and Mary; and $this->matches['John']['John'] contains the match of John with himself, so that represents a single.

Now I tried what I wanted to do with the following recursive function:

protected function makeConfigs(&$matches)
{
    // If we're at maximum recursion depth then just return what we have...
    if (count($matches) == 1)
        return array_values(current($matches));

    $configs = [];

    array_walk_recursive(
        $matches,
        function($match) use ($matches, &$configs) {
            // Of course when we use a certain match
            // then all other matches with the same people
            // cannot be used anymore for the rest of the config
            unset($matches[$match->person1->name]);
            unset($matches[$match->person2->name]);

            $configs = array_merge(
                $configs,
                array_merge(
                    [$match],
                    $this->makeConfigs($matches)
                )
            );
        }
    );

    return $configs;
}

But sadly it creates this error: Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 72 bytes).

So I wonder, is there a more efficient way to do this?

Evert
  • 2,022
  • 1
  • 20
  • 29
  • given it's a recursive call, you've probably recursed down far enough that you've got a few zillion intermediate arrays all sucking up ram. – Marc B Sep 15 '15 at 21:35

0 Answers0