为了账号安全,请及时绑定邮箱和手机立即绑定

PHP数组组合

PHP数组组合

PHP
慕侠2389804 2019-07-20 14:34:09
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个插槽中,而不考虑顺序。
查看完整描述

3 回答

?
临摹微笑

TA贡献1982条经验 获得超2个赞

<?php

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

        count($out) >= $minLength && count($out) <= $max and $return[] = $out;
        }
    return $return;}?>

输出量

Array

(

    [0] => test_1

    [1] => test_2

    [2] => test_3

    [3] => test_1,test_2

    [4] => test_1,test_3

    [5] => test_2,test_3

    [6] => test_1,test_2,test_3

)


查看完整回答
反对 回复 2019-07-20
?
BIG阳

TA贡献1859条经验 获得超6个赞

这个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


查看完整回答
反对 回复 2019-07-20
  • 3 回答
  • 0 关注
  • 631 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信