Home > Backend Development > PHP Tutorial > PHP printing Yang Hui triangle comprehensive example

PHP printing Yang Hui triangle comprehensive example

WBOY
Release: 2016-07-25 09:12:53
Original
846 people have browsed it

例子,php打印杨辉三角。

  1. $params=getParams(1);

  2. $argv0=trim($params[0]);
  3. if(!is_numeric($argv0))
  4. {
  5. error_msg("params 1 must be a numbers");
  6. }

  7. $spaceNumber=6;

  8. $maxn=$argv0;
  9. output("",true);
  10. get_trangle($argv0);
  11. error_msg("execute success");
  12. function get_trangle($n){
  13. if($n <= 0)
  14. { // bbs.it-home.org
  15. return false;
  16. }
  17. if($n==1)
  18. {
  19. $this_level=array(1);
  20. print_line($this_level,$n);
  21. return array(1);
  22. }
  23. if($n==2)
  24. {
  25. $this_level=array(1,1);
  26. print_line(array(1),1);
  27. print_line($this_level,$n);
  28. return $this_level;
  29. }
  30. $last_level=get_trangle($n-1);
  31. if(!is_array($last_level)||count($last_level) < 2)
  32. {
  33. return false;
  34. }
  35. $this_level=array();
  36. $this_level[0]=1;
  37. for($i=0;$i< count($last_level)-1;$i++)
  38. {
  39. $this_level[$i+1]=$last_level[$i]+$last_level[$i+1];
  40. }
  41. $this_level[]=1;
  42. print_line($this_level,$n);
  43. return $this_level;
  44. }
  45. function print_line($aArray,$n)
  46. {
  47. global $maxn,$spaceNumber;
  48. $line=sprintf("%".(($maxn-$n)*$spaceNumber/2)."s","");
  49. foreach($aArray as $i)
  50. {
  51. $line.=sprintf("%".$spaceNumber."s",$i);
  52. }
  53. output($line);
  54. }
  55. function getParams($paramNum)
  56. {
  57. $in=file_get_contents("in.txt");
  58. if($in===FALSE){
  59. error_msg("cannot read in.txt,please check in.txt existsn");
  60. }
  61. $in=preg_replace("/(s+)/i", " ", $in);
  62. $parms=split(" ",trim($in));
  63. if($parms===FALSE)
  64. {
  65. error_msg("cannot get param from in.txtn");
  66. }
  67. if(count($parms) < $paramNum)
  68. {
  69. error_msg("it needs $paramNum paramsn");
  70. }
  71. return $parms;
  72. }
  73. //输出 杨辉三角
  74. function output($msg,$isClean=false)
  75. {
  76. if($isClean)
  77. {
  78. $handle = fopen('out.txt', 'w');
  79. fclose($handle);
  80. }
  81. error_log($msg."n", 3, "out.txt");
  82. }
  83. function error_msg($msg,$is_exit=true)
  84. {
  85. if($is_exit)
  86. die($msg."n");
  87. else
  88. echo $msg."n";
  89. }
  90. ?>

复制代码


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template