1到n个数字组合的概率

问题描述 投票:1回答:2

我想要数字1到nth的组合。

示例集:

数字范围:1、2、3

2位数字的输出组合(如果数字范围是1到4,那么我想要2或4位数字。因此它是基于数字范围的动态)

输出:

1,2
1,3
2,3
3,1 
etc...

如果是3位输出的组合

输出:

1,2,3
2,1,3
1,3,2
3,1,2
2,3,1
3,2,1 
etc...

我已经尝试过以下功能进行组合,但我希望输入两位数

function pc_permute($items, $perms = array( )) {
    if (empty($items)) {
        $return = array($perms);
    }  else {
        $return = array();
        for ($i = count($items) - 1; $i >= 0; --$i) {
             $newitems = $items;
             $newperms = $perms;
         list($foo) = array_splice($newitems, $i, 1);
             array_unshift($newperms, $foo);
             $return = array_merge($return, pc_permute($newitems, $newperms));
         }
    }
    return $return;
}
echo "<br> <pre>";
$value = array('1', '2', '3');
print_r(pc_permute($value));
php arrays math probability
2个回答
1
投票

请反复执行。 Demo

function n_combinations($values,$length){
    if($length == 1){
        return $values;
    }else{
        $result = [];
        foreach($values as $value){
            foreach(n_combinations($values,$length-1) as $value_1){
                $result[] = "$value,$value_1";
            }
        }
        return $result;
    }
}

1
投票

尝试以下实现:

function combinations($items, $size, $combo = array()) {    
    if (empty($combo)) {
        $combo = $items;
    }   
    if ($size == 1) {
        return $combo;
    }    
    $new_combo = array();   
    foreach ($combo as $combination) {
        foreach ($items as $i) {
            $new_combo[] = $combination .','. $i;
        }
    }    
    return combinations($items, $size - 1, $new_combo);

}
$items = array(1,2,3);
$output = combinations($items, 2);
print_r($output);

output:Array ( [0] => 1,1 [1] => 1,2 [2] => 1,3 [3] => 2,1 [4] => 2,2 [5] => 2,3 [6] => 3,1 [7] => 3,2 [8] => 3,3 )
© www.soinside.com 2019 - 2024. All rights reserved.