欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

PHP 排列组合

程序员文章站 2022-07-11 09:11:28
...
初学PHP,闲暇写的排列组合,以十一运金为例,11,5的排列组合,可通用。(备注:初学,用字符串简单控制)。

<?php
$total = 0;
$result = array();
function test() {
combination(11,5,"",$total);


printf("Total %d", $GLOBALS['total']);

echo '<br />';

foreach ($GLOBALS['result'] as $value) {
echo implode('*',$value) . '<br />';
}
}
function combination($number,$count,$surfix) {
for($i=1;$i<=$number;$i++) {
$num = sprintf("%02d", $i);

if($count==1) {
if(strpos($surfix,$num)==false){
$result = $surfix. "*". $num;

$result = str_replace('A','',$result);
$temp = explode('*',$result);
sort($temp);
$key = implode('',$temp);

if($GLOBALS['result'][$key]==null) {
$GLOBALS['result'][$key]=$temp;
$GLOBALS['total']++;
}
unset($temp);
}
} else {
if($surfix=="") {
combination($number,$count-1,"A".$num);
} else {
if(strpos($surfix,$num)==false){
combination($number,$count-1,$surfix."*" .$num);
}
}
}
}
}
function permutation($number,$count,$surfix) {
for($i=1;$i<=$number;$i++) {
$num = sprintf("%02d", $i);

if($count==1) {
if(strpos($surfix,$num)==false){
$GLOBALS['total']++;
array_push($GLOBALS['result'], $surfix. "*". $num);
}
} else {
if($surfix=="") {
permutation($number,$count-1,"A".$num);
} else {
if(strpos($surfix,$num)==false){
permutation($number,$count-1,$surfix."*" .$num);
}
}
}
}
}
?>