所有子数组元素的组合,而无需重复 [英] Combinations of all sub array elements without repeats

查看:150
本文介绍了所有子数组元素的组合,而无需重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从数据库属性。每个属性都有多个值。现在,我想混这些价值观,创造出独特的组合。

例如输入:

  $ a =阵列(
    35 =>阵列('绿','红','棕'),
    36 =>阵列('狐狸','家','狗')
);

输出 - 第二层面的元素所有可能的组合。下面的示例输出:

  $输出=阵列(
    阵列(35 =>'绿色',36 =>'狐狸'),
    阵列(35 =>'绿色',36 =>房子),
    阵列(35 =>'绿色',36 =>狗),
    阵列(35 =>'红',36 =>'狐狸'),
    阵列(35 =>'红',36 =>房子),
    阵列(35 =>'红',36 =>狗),
    阵列(35 =>'棕',36 =>'狐狸'),
    阵列(35 =>'棕',36 =>房子),
    阵列(35 =>'棕',36 =>狗),
);

我的功能不复发:

 函数MyFunction的($ A){    $键= array_keys($ A);
    $结果=阵列();    如果(计数($键)== 0){
        $结果=阵列();
    }
    ELSEIF(计数($键)== 1){
        $ K ​​= $按键[0];
        的foreach($ A [$ K]为$ V){
            $结果[] =阵列($ K => $ V);
        }
    }
    ELSEIF(计数($键)== 2){
        $ K1 = $按键[0];
        $ K2 = $键[1];
        的foreach($ A [$ K1]为$ V1){
            的foreach($ A [$ K2]为$ V2){
                $结果[] =阵列($ K1 => $ V1,$ K2 => $ V2);
            }
        }
    }
    ELSEIF(计数($键)== 3){
        $ K1 = $按键[0];
        $ K2 = $键[1];
        $ K3 = $键[2];
        的foreach($ A [$ K1]为$ V1){
            的foreach($ A [$ K2]为$ V2){
                的foreach($ A [$ K3]为$ V3){
                    $结果[] =阵列($ K1 => $ V1,$ K2 => $ V2,K3 $ = GT; $ V3);
                }
            }
        }
    }
    其他{
        抛出新的异常(要多键',1);
    }    返回$结果;
}


解决方案

这应该为你工作:

那么,这code呢?

1。多少个组合有哪些?

所以,首先的问题有多少组合是存在的,答案是你与对方乘以每个阵列的数量。

所以,(C =量 1


  

C <子>阵列1 * C 阵列2 * ...... * C 阵列ñ


和特定于您的例子:


  

C <子>阵列1 * C 阵列2 = 3 * 3的 = 9


<子> * 1 如果你想知道为什么我选择了 C 的量,因为函数计数()在PHP

2。让所有的组合

我们如何与所有阵列的金额是多少?

的长度让现在所有的组合

好吧pretty简单,我们刚刚经历的所有组合(在开始时只是一个空的组合( [] ==阵列())),我们已经循环有与下阵列,直到我们得到这是我们想要的所需长度,在这种情况下,最后阵列的最后一次迭代

因此​​,作为一个例子:

 与数组中的元素(空数组为[]):[
    [1,2],
    [3,4]
]

  //为下一次迭代的新组合
                               |
阵列NAN *:    组合:
                   - [] | - &GT; []
                                  |
数组1 [1,2]:-------------
                    | |
    组合:v v
                   - [] + 1 | - &GT; [1]
                   - [] +2 | - &GT; [2]
                                  |
阵列2 [3,4]:-------------
                    | |
    组合:v v
                   - [] + 3 | - &GT; [3]
                   - [] +4 | - &GT; [4]
                   - [1] + 3 | - &GT; [1,3]
                   - [1] + 4 | - &GT; [1,4]
                   - [2] + 3 | - &GT; [2,3]
                   - [2] + 4 | - &GT; [2,4]
                               // ^这里所有组合

<子> *楠:不是一个数字

所以你可以在上面的例子中看到,我们现在所有的组合与我们有所有阵列量的长度。

但是,为了得到仅具有所需长度我们重写结果数组每次迭代组合,以便在端仅与期望的长度的组合的结果阵列中

code:

 &LT; PHP    $数据= [
            35 =&GT; [绿色,红,棕色]
            36 =&GT; [狐狸精,房子,狗]
        ];    $组合= [[]];
    $ comKeys = array_keys($的数据);
    为($计数= 0; $计数&LT;计数($ comKeys); $计数++){
        $ TMP = [];
        的foreach($组合为$ V1){
            的foreach($数据[$ comKeys [$计数]为$ V2)
                $ TMP [] = $ V1 + [$ comKeys [$计数=&GT; $ V2];        }
        $组合= $ TMP;
    }    的print_r($组合);?&GT;

输出:

 阵列

    [0] =&GT;排列
        (
            [35] =&GT;绿色
            [36] =&GT;狐狸
        )    [1] =&GT;排列
        (
            [35] =&GT;绿色
            [36] =&GT;屋
        )    [2] =&GT;排列
        (
            [35] =&GT;绿色
            [36] =&GT;狗
        )    [3] =&GT;排列
        (
            [35] =&GT;红
            [36] =&GT;狐狸
        )    [4] =&GT;排列
        (
            [35] =&GT;红
            [36] =&GT;屋
        )    [5] =&GT;排列
        (
            [35] =&GT;红
            [36] =&GT;狗
        )    [6] =&GT;排列
        (
            [35] =&GT;棕色
            [36] =&GT;狐狸
        )    [7] =&GT;排列
        (
            [35] =&GT;棕色
            [36] =&GT;屋
        )    [8] =&GT;排列
        (
            [35] =&GT;棕色
            [36] =&GT;狗
        ))

I have "attributes" from database. Each attribute has many values. Now I want to mix these values to create unique combinations.

example of input:

$a = array(
    35=>array('green','red','brown'),
    36=>array('fox','house','dog')
);

output - all possible combinations of second dimensions's elements. example output below:

$output = array(
    array(35=>'green',36=>'fox'),
    array(35=>'green',36=>'house'),
    array(35=>'green',36=>'dog'),
    array(35=>'red',36=>'fox'),
    array(35=>'red',36=>'house'),
    array(35=>'red',36=>'dog'),
    array(35=>'brown',36=>'fox'),
    array(35=>'brown',36=>'house'),
    array(35=>'brown',36=>'dog'),
);

my function without recurrence:

function myfunction($a){

    $keys = array_keys($a);
    $result = array();

    if(count($keys)==0){
        $result = array();
    }
    elseif(count($keys)==1){
        $k = $keys[0];
        foreach($a[$k] as $v){
            $result[] = array($k=>$v);
        }
    }
    elseif(count($keys)==2){
        $k1 = $keys[0];
        $k2 = $keys[1];
        foreach($a[$k1] as $v1){
            foreach($a[$k2] as $v2){
                $result[] = array($k1=>$v1,$k2=>$v2);
            }
        }
    }
    elseif(count($keys)==3){
        $k1 = $keys[0];
        $k2 = $keys[1];
        $k3 = $keys[2];
        foreach($a[$k1] as $v1){
            foreach($a[$k2] as $v2){
                foreach($a[$k3] as $v3){
                    $result[] = array($k1=>$v1,$k2=>$v2,$k3=>$v3);
                }
            }
        }
    }
    else{
        throw new Exception('To much keys', 1);
    }

    return $result;
}

解决方案

This should work for you:

So what does this code do?

1. How many combinations are there?

So first the question how many combinations are there and the answer is you have to multiply the amount of every array with each other.

So (c = amount1):

carray 1 * carray 2 * ... * carray n

And specific for your example:

carray 1 * carray 2 = 3 * 3 = 9

*1 And if you wonder why I chose c for amount, because of the function count() in php

2. Getting all combinations

How do we get now all combinations with the length of the amount of all arrays?

Well pretty simple, we just loop through all combinations (at the start just an empty combination ([] == array())) which we already have with the next array until we get the desired length which we want, in this case the last iteration of the last array.

So as an example:

Array with the elements (Empty array is '[]'):

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

                               //new combinations for the next iteration
                               |
array NAN*:

    Combinations:
                  - []         |  -> []
                                  |
array 1 [1,2]:       -------------
                    |             |
    Combinations:   v             v
                  - []    + 1  |  -> [1]  
                  - []    + 2  |  -> [2]   
                                  |
array 2 [3,4]:       -------------
                    |             |
    Combinations:   v             v
                  - []    + 3  |  -> [3]
                  - []    + 4  |  -> [4]
                  - [1]   + 3  |  -> [1,3]
                  - [1]   + 4  |  -> [1,4]
                  - [2]   + 3  |  -> [2,3]
                  - [2]   + 4  |  -> [2,4]     
                               //^ All combinations here

* NAN: not a number

So as you can see in the above example we now have all combinations with the length of the amount of all arrays which we have.

But to get only the combinations with the desired length we are overwriting the result array each iteration, so that at the end only the combinations with the expected length are in the results array.

code:

<?php

    $data = [
            35 => ["green", "red", "brown"],
            36 => ["fox", "house", "dog"]
        ];

    $combinations = [[]];
    $comKeys = array_keys($data);


    for ($count = 0; $count < count($comKeys); $count++) {
        $tmp = [];
        foreach ($combinations as $v1) {
            foreach ($data[$comKeys[$count]] as $v2)
                $tmp[] = $v1 + [$comKeys[$count] => $v2];

        }
        $combinations = $tmp;
    }

    print_r($combinations);

?>

output:

Array
(
    [0] => Array
        (
            [35] => green
            [36] => fox
        )

    [1] => Array
        (
            [35] => green
            [36] => house
        )

    [2] => Array
        (
            [35] => green
            [36] => dog
        )

    [3] => Array
        (
            [35] => red
            [36] => fox
        )

    [4] => Array
        (
            [35] => red
            [36] => house
        )

    [5] => Array
        (
            [35] => red
            [36] => dog
        )

    [6] => Array
        (
            [35] => brown
            [36] => fox
        )

    [7] => Array
        (
            [35] => brown
            [36] => house
        )

    [8] => Array
        (
            [35] => brown
            [36] => dog
        )

)

这篇关于所有子数组元素的组合,而无需重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆