P
P
PoodingRex2019-01-21 09:31:26
PHP
PoodingRex, 2019-01-21 09:31:26

How to calculate all combination options in php?

Good afternoon. Tell me, please, how can I calculate all the options for combining the elements of an array?
For example, there is an array 1,2,3,4,5,6 It is
necessary to read the options: 1,2; 1.3; ... ; 1.6 then 1,2,3; 1,2,4; 1,2,5, then 1,3,4; 1,3,6 etc.
Those are all possible combinations. Simply, I don’t even quite know how to call this operation.
ps permutation options do not need to be taken into account, i.e. 1,2,3 == 1,3,2 == 3,1,2

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jcmvbkbc, 2019-01-21
@PoodingRex

For example, there is an array 1,2,3,4,5,6 It is
necessary to read the options: 1,2; 1.3; ... ; 1.6 then 1,2,3; 1,2,4; 1,2,5, then 1,3,4; 1,3,6 etc.
ps permutation options do not need to be taken into account, i.e. 1,2,3 == 1,3,2 == 3,1,2
how this operation can be called.

In its entirety, this is called "the set of all subsets " (your list, however, does not include the empty subset and subsets of the same element). What you called options are " combinations of N to K ".

L
Lander, 2019-01-21
@usdglander

Literally on the first link in Google is the solution:

print_r(AllPermutations(array('peter', 'paul', 'mary')));

function AllPermutations($InArray, $InProcessedArray = array())
{
    $ReturnArray = array();
    foreach($InArray as $Key=>$value)
    {
        $CopyArray = $InProcessedArray;
        $CopyArray[$Key] = $value;
        $TempArray = array_diff_key($InArray, $CopyArray);
        if (count($TempArray) == 0)
        {
            $ReturnArray[] = $CopyArray;
        }
        else
        {
            $ReturnArray = array_merge($ReturnArray, AllPermutations($TempArray, $CopyArray));
        }
    }
    return $ReturnArray;
}

upd: For six elements, the number of permutations is 720 (6!)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question