1到n个数字组合的概率
Probability of 1 to n number combination
我要1到n号的组合。
示例集:
号码范围: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...
我试过下面的组合函数,但我想要 2 位数字
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));
试试下面的实现:
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 )
逆向执行。 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到n号的组合。
示例集:
号码范围: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...
我试过下面的组合函数,但我想要 2 位数字
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));
试试下面的实现:
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 )
逆向执行。 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;
}
}