-1

I have an array :

$names = array("Jim", "Jane", "Bob", "Susan", "Ralph"); 

And I want to have calculate combinations for 3 elements.

The output is something like that:

Jim, Jane, Bob
Jim, Jane, Susan
Jim, Jane, Ralph
Jim, Bob, Susan
Jim, Bob, Ralph
Jim, Susan, Ralph
Jane, Bob, Susan
Jane, Bob, Ralph
Jane, Susan, Ralph
Bob, Susan, Ralph

The expected output has 10 different combinations. I have been thinking how to achieve this but have no idea how to do this. Please help, thanks.

hatched
  • 795
  • 2
  • 9
  • 34
  • 2
    Does this answer your question? [How to generate in PHP all combinations of items in multiple arrays](https://stackoverflow.com/questions/8567082/how-to-generate-in-php-all-combinations-of-items-in-multiple-arrays) – Masivuye Cokile Feb 26 '20 at 11:09
  • Can you elaborate a bit more about the restriction of the combinations? I see a total of X names which should be filled in groups of size Y? I guess they need to be unique per group? Is the number of total groups also restricted (Z) or should it be the maximum possible? – Christoph Kluge Feb 26 '20 at 11:13
  • @ChristophKluge the names should be unique per group , using the math formula `r!(n – r)!` , therefore `3!(5 – 3)!` the numbers of group should be exactly 10 – hatched Feb 26 '20 at 11:27

1 Answers1

0

The algorithm is pretty straight forward. You can simply use a while statement to loop over the remained entries after you shift the first element, and then use 2 other loops to append the remained names in order:

$names = ["Jim", "Jane", "Bob", "Susan", "Ralph"];
$result = [];

while (count($names) > 2) {
    $currentName = array_shift($names);

    for ($i = 0; $i < count($names) - 1; $i++) {
        for ($j = $i + 1; $j < count($names); $j++) {
            $result[] = implode(', ', [$currentName, $names[$i], $names[$j]]);
        }
    }
}

var_dump($result);

The result would be:

array(10) {
  [0]=>
  string(14) "Jim, Jane, Bob"
  [1]=>
  string(16) "Jim, Jane, Susan"
  [2]=>
  string(16) "Jim, Jane, Ralph"
  [3]=>
  string(15) "Jim, Bob, Susan"
  [4]=>
  string(15) "Jim, Bob, Ralph"
  [5]=>
  string(17) "Jim, Susan, Ralph"
  [6]=>
  string(16) "Jane, Bob, Susan"
  [7]=>
  string(16) "Jane, Bob, Ralph"
  [8]=>
  string(18) "Jane, Susan, Ralph"
  [9]=>
  string(17) "Bob, Susan, Ralph"
}
Mihai Matei
  • 24,166
  • 5
  • 32
  • 50