一种通过排除数组成员来寻找所有可能性的算法思想


An idea of algorithm to find all possibilities by excluding members of an array ?

我将在这个循环中使用这个函数:

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]]。。。

知道我该怎么做吗?

您可以使用以下函数:

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
        )
)
*/