PHP数组组合

PHP数组组合

我有一个由7个数字组成的数组(1,2,3,4,5,6,7),我想对5个数字,如(1,2,3,4,5),(1,2,3,4,6),(1,2,3,4,7)(1,2,3,4,5)等于(4,5,3,1,2)

我想知道PHP中是否有一个函数或任何算法可以做到这一点?我不知道从哪里开始。你能帮我吗?

我想把7个给定数字的组合(它们是从一个数组中取出来的)放到5个插槽中,而不考虑顺序。


慕侠2389804
浏览 632回答 3
3回答

临摹微笑

<?php echo&nbsp;"<pre>";$test&nbsp;=&nbsp;array("test_1","test_2","test_3");//&nbsp;Get&nbsp;Combination$return&nbsp;=&nbsp;uniqueCombination($test);//Sortsort($return);//Pretty&nbsp;Printprint_r(array_map(function($v){&nbsp;return&nbsp;implode(",",&nbsp;$v);&nbsp;},&nbsp;$return));function&nbsp;uniqueCombination($in,&nbsp;$minLength&nbsp;=&nbsp;1,&nbsp;$max&nbsp;=&nbsp;2000)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;$count&nbsp;=&nbsp;count($in); &nbsp;&nbsp;&nbsp;&nbsp;$members&nbsp;=&nbsp;pow(2,&nbsp;$count); &nbsp;&nbsp;&nbsp;&nbsp;$return&nbsp;=&nbsp;array(); &nbsp;&nbsp;&nbsp;&nbsp;for($i&nbsp;=&nbsp;0;&nbsp;$i&nbsp;<&nbsp;$members;&nbsp;$i&nbsp;++)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$b&nbsp;=&nbsp;sprintf("%0"&nbsp;.&nbsp;$count&nbsp;.&nbsp;"b",&nbsp;$i); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$out&nbsp;=&nbsp;array(); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;for($j&nbsp;=&nbsp;0;&nbsp;$j&nbsp;<&nbsp;$count;&nbsp;$j&nbsp;++)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$b{$j}&nbsp;==&nbsp;'1'&nbsp;and&nbsp;$out[]&nbsp;=&nbsp;$in[$j]; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;count($out)&nbsp;>=&nbsp;$minLength&nbsp;&&&nbsp;count($out)&nbsp;<=&nbsp;$max&nbsp;and&nbsp;$return[]&nbsp;=&nbsp;$out; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;$return;}?>输出量Array(&nbsp; &nbsp; [0] => test_1&nbsp; &nbsp; [1] => test_2&nbsp; &nbsp; [2] => test_3&nbsp; &nbsp; [3] => test_1,test_2&nbsp; &nbsp; [4] => test_1,test_3&nbsp; &nbsp; [5] => test_2,test_3&nbsp; &nbsp; [6] => test_1,test_2,test_3)

BIG阳

这个Math_Combinatorics在PEAR存储库中,您想做什么就做什么:返回所有组合和排列的包,不重复、给定集和子集的大小。关联数组被保留。require_once 'Math/Combinatorics.php';$combinatorics = new Math_Combinatorics;$input = array(1, 2, 3, 4, 5, 6, 7);$output = $combinatorics->combinations($input, 5); // 5 is the subset size// 1,2,3,4,5// 1,2,3,4,6// 1,2,3,4,7// 1,2,3,5,6// 1,2,3,5,7// 1,2,3,6,7// 1,2,4,5,6// 1,2,4,5,7// 1,2,4,6,7// 1,2,5,6,7// 1,3,4,5,6// 1,3,4,5,7// 1,3,4,6,7// 1,3,5,6,7// 1,4,5,6,7// 2,3,4,5,6// 2,3,4,5,7// 2,3,4,6,7// 2,3,5,6,7// 2,4,5,6,7// 3,4,5,6,7
打开App,查看更多内容
随时随地看视频慕课网APP