例子,php打印杨辉三角。
-
-
$params=getParams(1); - $argv0=trim($params[0]);
-
- if(!is_numeric($argv0))
- {
- error_msg("params 1 must be a numbers");
- }
$spaceNumber=6;
- $maxn=$argv0;
-
- output("",true);
- get_trangle($argv0);
- error_msg("execute success");
-
- function get_trangle($n){
- if($n <= 0)
- { // bbs.it-home.org
-
- return false;
- }
- if($n==1)
- {
- $this_level=array(1);
- print_line($this_level,$n);
- return array(1);
- }
- if($n==2)
- {
- $this_level=array(1,1);
- print_line(array(1),1);
- print_line($this_level,$n);
- return $this_level;
- }
- $last_level=get_trangle($n-1);
- if(!is_array($last_level)||count($last_level) < 2)
- {
-
- return false;
- }
- $this_level=array();
- $this_level[0]=1;
-
- for($i=0;$i< count($last_level)-1;$i )
- {
- $this_level[$i 1]=$last_level[$i] $last_level[$i 1];
- }
- $this_level[]=1;
- print_line($this_level,$n);
- return $this_level;
- }
-
- function print_line($aArray,$n)
- {
- global $maxn,$spaceNumber;
- $line=sprintf("%".(($maxn-$n)*$spaceNumber/2)."s","");
- foreach($aArray as $i)
- {
- $line.=sprintf("%".$spaceNumber."s",$i);
- }
- output($line);
- }
-
- function getParams($paramNum)
- {
- $in=file_get_contents("in.txt");
- if($in===FALSE){
- error_msg("cannot read in.txt,please check in.txt existsn");
- }
- $in=preg_replace("/(s )/i", " ", $in);
-
- $parms=split(" ",trim($in));
- if($parms===FALSE)
- {
- error_msg("cannot get param from in.txtn");
- }
- if(count($parms) < $paramNum)
- {
- error_msg("it needs $paramNum paramsn");
- }
- return $parms;
- }
- //输出 杨辉三角
- function output($msg,$isClean=false)
- {
- if($isClean)
- {
- $handle = fopen('out.txt', 'w');
- fclose($handle);
- }
- error_log($msg."n", 3, "out.txt");
- }
-
- function error_msg($msg,$is_exit=true)
- {
- if($is_exit)
- die($msg."n");
- else
- echo $msg."n";
- }
- ?>
-
复制代码
|