0

I have the following array

$values = ['P1', 'P2', 'P3', ['P1', 'P2'], ['P1', 'P3'], ['P2', 'P3'], ['P1', 'P2', 'P3']];

From this array I want to pick all combinations without a value repeating itself and you can only pick distinct number of items which in this case will be 3.

For example it should be like this

$result1 = ['P1', 'P2', 'P3'];
$result2 = ['P1', ['P2', 'P3']];
$result3 = ['P2', ['P1', 'P3']];
$result4 = ['P3', ['P1', 'P2']];
$result5 = [['P1', 'P2', 'P3']];
.
.
.
.and so on

What I have done until now

  1. Looked at many combinations questions like these Question, Question.
  2. Looked at Chase's Twiddle algorithm here.

The above approaches seems like they will not work for me. So I started doing my own code like below, but I am a little lost.

$values = [['P1'], ['P2'], ['P3'], ['P1', 'P2'], ['P1', 'P3'], ['P2', 'P3'], ['P1', 'P2', 'P3']];
        $result = [];
        $i = 0;
        foreach ($values as $key => $value) {
            $result[$i][] = $value;
            $restArray = array_diff_key($values, array_flip([$key]));
            foreach ($restArray as $v) {
                foreach ($v as $val) {
                    if (!in_array($val, $result[$i])) {
                        $result[$i][] = $v;
                    }
                }
            }
            
            $i++;
        }
        
Subash
  • 165
  • 2
  • 3
  • 13
  • I presume `checkAllExists` is your own function as well. So I'd suggest you include it in the question as well. – El_Vanja Dec 10 '20 at 09:17
  • @El_Vanja Updated what I have done. – Subash Dec 10 '20 at 11:19
  • One thing - at the beginning you show your input array like this: `$values = ['P1', 'P2', 'P3'...` and later you show it like this: `$values = [['P1'], ['P2'], ['P3']...`. What is the actual structure of the input array? Are these single elements arrays or strings? – El_Vanja Dec 10 '20 at 11:43

0 Answers0