gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:20:32 25 4
gpt4 key购买 nike

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

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

*/

关于php - 通过排除数组成员来找到所有可能性的算法的想法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33668641/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com