-3

If I have the following array:

array(1,2,3,4,5)

How can I find all the unique, non-repeating, 3 selection combinations?

For instance, these would be valid values:

[1,2,3]
[1,2,4]
[1,2,5]

But this wouldn't be valid:

[1,3,2]

because it's the same as [1,2,3]

Jason M
  • 1,013
  • 13
  • 25

1 Answers1

0

If you want to find all unique 3-tuples (without distinguishing the order (e.g. [1,2,3] is the same as [2,1,3])) you can do it with 3 nested for loops. The first one begins from the first element, the second for loop begins one element further each time, and so on.

$arr = array(1, 2, 3, 4, 5);

for ($i = 0; $i < count($arr) - 2; $i++) {
    $value = $arr[$i];
       for($j = $i+1; $j < count($arr) - 1; $j++) {
           $value2 = $arr[$j];
           for($k = $j+1; $k < count($arr); $k++) {
               $value3 = $arr[$k];
               echo "[".$value.",".$value2.",".$value3."]\n";
           }
       }
}

Output :

[1,2,3]
[1,2,4]
[1,2,5]
[1,3,4]
[1,3,5]
[1,4,5]
[2,3,4]
[2,3,5]
[2,4,5]
[3,4,5]

PS : The solution pointed out in @JuanLopes duplicate's question should be preferred as it is more general.

Kevin
  • 2,813
  • 3
  • 20
  • 30