通过排除数组成员来找到所有可能性的算法的想法?

时间:2015-11-12 09:55:50

标签: php algorithm

我将在此循环中使用此函数:

while ($nbrDocument < 12 && $nbrTags > 0)
{
    $tmpDocuments = $this
        ->get('fos_elastica.manager')
        ->getRepository('AppBundle:Document')
        ->findFromTag();
    $tagPossibilities = $this->generateTagPossibilities($userTags, $nbrTags);
    foreach ($tmpDocuments as $document)
    {
        $present = true;
        foreach ($tagPossibilities as $tags)
        {
            foreach ($tags as $tag)
            {
                if (!in_array($tag, $document->getTag()))
                {
                    $present = false;
                    break;
                }
            }
            if ($present) {
                break;
            }
        }
        $nbrDocument ++;
        array_push($documents, $$document);
    }
    $nbrTags--;
}

我需要创建方法generateTagPossibilities。

第一个参数包含一个字符串数据数组,第二个参数是大小 我需要的可能性。

例如,如果我的数组中有[1] [2] [3] [4]且$ nbrTag = 4,则此函数应返回[1] [2] [3] [4],如果$ nbrTag = 3,它应该返回[[1] [2] [3]] [[1] [3] [4]] [[2] [3] [4]] ......

知道我该怎么做吗?

1 个答案:

答案 0 :(得分:0)

您可以使用以下功能:

function array_hash($a)
{
    $s = '';
    foreach($a as $v)
    {
        $s.=$v.'-';
    }

    return hash('sha256',$s);
}

function removeOne($setList)
{
    $returnSetList = array();
    $hashList = array();

    foreach($setList as $set)
    {
        foreach($set as $k=>$v)
        {
            $tmpSet = $set;
            unset($tmpSet[$k]);
            $hash = array_hash($tmpSet);

            if(!in_array($hash, $hashList))
            {
                $returnSetList[] = $tmpSet;
                $hashList[] = $hash;
            }
        }
    }

    return $returnSetList;
}

function generateTagPossibilities($userTags, $nbrTags)
{
    $aUserTags = array($userTags);
    $cUserTags = count($userTags);

    if($nbrTags==$cUserTags)
        return $aUserTags;

    for($i=0; $i<($cUserTags-$nbrTags); $i++)
        $aUserTags = removeOne($aUserTags);

    return $aUserTags;
}

// Example !

$a = array(1,2,3,4);
print_r(generateTagPossibilities($a,2));

/*

Array
(
    [0] => Array
        (
            [2] => 3
            [3] => 4
        )

    [1] => Array
        (
            [1] => 2
            [3] => 4
        )

    [2] => Array
        (
            [1] => 2
            [2] => 3
        )

    [3] => Array
        (
            [0] => 1
            [3] => 4
        )

    [4] => Array
        (
            [0] => 1
            [2] => 3
        )

    [5] => Array
        (
            [0] => 1
            [1] => 2
        )
)

*/