比较PHP中两个数组中元素对的所有可能组合
发布时间:2020-12-13 15:58:58 所属栏目:PHP教程 来源:网络整理
导读:我试图在 PHP中进行基本的二进制行分类. (编程语言无关紧要,用PHP更舒服). 所以基本上我有2个坐标数组: $classA = [ new Point(1,1),new Point(1,2),new Point(3,3),5) ];$classB = [ new Point(4,new Point(5,new Point(4,new Point(6,6) ]; 我需要遍历这
我试图在
PHP中进行基本的二进制行分类. (编程语言无关紧要,用PHP更舒服).
所以基本上我有2个坐标数组: $classA = [ new Point(1,1),new Point(1,2),new Point(3,3),5) ]; $classB = [ new Point(4,new Point(5,new Point(4,new Point(6,6) ]; 我需要遍历这些数组并且每次获得2对点(一对由来自classA的点和来自classB的另一个点).获得所有可能的组合非常重要.一旦特定点在一对中,它就不能存在于另一对中. 例如,前两对将是: $pair1 = [$a[0],$b[0]]; $pair2 = [$a[1],$b[1]]; 为了更好地解释自己,这就是我需要的: 当第一对包含[1,1],[4,1]时,另一对的所有可能组合都以黄色突出显示. 到目前为止,这就是我所拥有的: $classA = [ new Point(1,3)]; $classB = [ new Point(4,1)]; $combinations = []; $pair1 = []; $pair2 = []; $n = count($classA); $m = count($classB); for ($i=0; $i<$n; $i++){ for ($j=0; $j<$m; $j++){ $pair1 = [ $classA[$i],$classB[$j] ]; for ($z=0; $z<$n; $z++){ if($z != $i && $z != $j){ for ($y=0; $y<$m; $y++){ if($y != $i && $y != $j){ $pair2 = [ $classA[$z],$classB[$y] ]; $combinations[] = [$pair1,$pair2]; } } } } } } 除了效率低下,这给了我很多重复,有没有办法只获得独特的组合? 解决方法
我建议首先创建所有可能的组合,然后对于每一对,在“所有可能的组合”中用null-s替换行/列,虽然它可能不是最快的,但它应该工作并且给你一般理念
$allCombinations = Array(); foreach($classA as $value) { $column = Array(); foreach($classB as $bPart) { $column[] = Array($bPart,$value); } $allCombinations[] = $column; } $possibleCombinations = Array(); $sizeA = count($classA); $sizeB = count($classB); for($a = 0; $a < $sizeA; $a++) { $column = Array(); for($b = 0; $b < $sizeB; $b++) { $temp = $allCombinations; for($i = 0;$i < $sizeA;$i++) { $temp[$a][$i] = null; } for($i = 0;$i < $sizeB;$i++) { $temp[$i][$b] = null; } // for $classA[$a],$classB[$b] possible combinations are in temp now $column[] = $temp; } $possibleCombinations[] = $column; } 现在,在$possibleCombinations中,您可以看到给定A / B索引的可能组合 在第一个循环中,它只是创建所有可能的组合, 例: $ab = Array($classA[$i],$classB[$j]); $possibleCombinationsForAB = $possibleCombinations[$i,$j]; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |