+ -
当前位置:首页 → 问答吧 → 在a个数选b个数的进行组合,组合结果及数量的算法及代码的研究

在a个数选b个数的进行组合,组合结果及数量的算法及代码的研究

时间:2007-11-24

来源:互联网

以下是经我三天的研究的成果,如果朋友有更好方法或改进,请留贴
复制内容到剪贴板
代码:

<?php
/***************************
在a个数选b个数的进行组合,组合结果及数量的算法及代码的研究
方法:自调用
2007年11月21日
[email protected]
使用方法:http://localhost/n.php?a=6&b=3&p=0
p=0就只输出组合总数,p=1就列出组合结果,如果结果过大,建议设为p=0
************************************/
class num{
var $a;//范围
var $b;//组合数的个数
var $c = array();//组合的结果
var $d = 0;//组合总数
var $now = array();
var $p = 0;//0不输出,1输出
//初始化
function num($a=6,$b=3,$p=0) {
$this->a = $a;
$this->b = $b;
$this->p = $p;
for($i=1;$i<=$this->b;$i++){
  $this->now[$i] = $i;
}
}
//$p,第$p位的数--------------------
function account($p){
$e = $this->a - $this->b + $p;//当前位置的结束值
while($this->now[$p] < $e){
  if($p < $this->b){
    $this->now[$p+1] = $this->now[$p] + 1;
   $this->account($p+1);
   }
  $this->add();
  $this->now[$p] += 1;   
  }
}
//保存
function add(){
$this->d += 1;
if($this->p == 1){  
  for($i=1;$i <= $this->b;$i++){
   $this->c[$this->d][$i] = $this->now[$i];
  }
}
}
//打印---------------------------------------
function pr(){//$p=1就列表打印,如果结果太大,IE会受不了的,输出要注意呀
  $this->account(1);
$this->add();
  echo "<BR>从 $this->a 个数中选出 $this->b 个数进行组合,能有 $this->d 个不重复的组合。<BR>";
if($this->p == 1){
  for($i=1;$i<=$this->d;$i++){
    for($j=1;$j<=$this->b;$j++){
      echo " ".$this->c[$i][$j]." ";
    }
    echo "<BR>";
  }
}
}
}
//end---------------------------------------------------
if(empty($_GET['a'])){$a = 6;}else{$a = $_GET['a'];}
if(empty($_GET['b'])){$b = 3;}else{$b = $_GET['b'];}
if(empty($_GET['p'])){$p = 0;}else{$p = $_GET['p'];}
$a = new num($a,$b,$p);
$a->pr();

?>
[ 本帖最后由 ljc_168 于 2007-11-24 10:16 编辑 ]

作者: ljc_168   发布时间: 2007-11-24