【转载】PHP的普青、文青和2B青

注:本篇博文转载自 开源小站 

之前看过一篇东西,大致上说:之所以PHP这么流行,主要是因为PHP太“下贱”。门槛太低,什么样的写法都有。这些年接触下来,也颇有共鸣。正巧赶上最近网上很流行“普青、文青、2B青”的恶搞,抱着“回字到底有几种写法”的态度,对同样的问题进行各种风格的编码,为了更多的体现算法,我剔除了注释。只为搏大家一笑,希望大家也不要拓展开来了。

题目:1只羊第二年后开始繁殖,每年一胎,每胎一只,直到第5年死亡,列出前十年的羊的数量。

 

首先照例是普青:

 1 <?php  
2 function foo($n, $echo = true)
3 {
4 $i = 1;
5 $a = 1;
6
7 while($i < = $n)
8 {
9 $c = $b;
10 $b += $a;
11 $a = $c;
12
13 if ($i > 5)
14 {
15 $b -= (foo($i -5, false) -1)
16 }
17 if ($echo)
18 echo "The " . $ i ."th year: " . $b ."n";
19 i ++;
20 }
21 }
22 foo(10);
23 ?>

资质一般,仅仅是做出了题目而已,没有考虑之后代码的维护,以及层层递归造成的性能浪费

接下来是文青: 

 1 <?php
2
3 function getSheepNumber($finalYear)
4 {
5 if ($finalYear < 1 ) return 0;
6 $thisYear = 1;
7 $histoyRecord = array ('1' = 1);
8
9 while($thisYear < = $finalYear)
10 {
11 $lastYear = $thisYear - 1;
12 $theYearBeforLastYear = $lastYear - 1;
13 if ($theYearBeforLastYear < 0 )
14 $historyRecord[$thisYear] = $historyRecord[$lastYear];
15 else
16 $historyRecord[$thisYear] =
17 $historyRecord[$lastYear] + $historyRecord[$theYearBeforLastYea];
18
19 if ($thisYear > 5)
20 {
21 $theYearBefor5Years = $lastYear - 5;
22 $historyRecord[$thisYear] -= $historyRecord[$theYearBefor5Years];
23 }
24 $thisYear ++;
25 }
26 return $historyRecord[$thisYear]
27 }
28
29 for ($year = 1; $year<=10; $year++)
30 {
31 switch ($year)
32 {
33 case 1:
34 echo "The 1st year: ";
35 break;
36 case 2:
37 echo "The 2nd year: ";
38 break;
39 case 3:
40 echo "The 3rd year: ";
41 break;
42 default:
43 echo "The " . $year ."th year: ";
44 break;
45 }
46
47 $sheepCount = getSheepNumber($year);
48 echo $sheepCount . "n";
49 }
50 ?>

足够优雅,也有了不错的优化。可惜为了这优雅,循环调用,导致尽管优化了性能但依旧有潜力可挖,而且代码也罗嗦的可以了。谁让文青都不食人间烟火呢?

接下来2B青闪亮登场:

 1 <?php
2 function foo($n)
3 {
4 $year_2 = $year_1 = 1;
5 $loop = 2;
6
7 while( $n > 0 )
8 {
9 $last_year = "year_" . $loop;
10 $last_2_year = "year_" . ($loop - 1);
11 $loop ++;
12
13 $this_year = "year_" . $loop;
14
15 $$this_year = $$last_2_year + $$last_year;
16
17 if ($loop > 5)
18 $$this_year -= ${substr($this_year, 0 , -2) . ($loop - 5)};
19 ?>
20 The <?php =$loop ?>th year <?php =$$this_year ?>
21 <?php
22 }
23 }
24 foo(10);
25 ?>

好吧,我不得不承认PHP的特性真的很方便。为了特性而特性这就是2B。

NB青的,颇有爱尔兰(Erlang)风格:

 1 <?php
2
3 function sheepBorn($n, &$list)
4 {
5 if ($list[$n]) return $list[$n];
6
7 if $n < 1 return 0;
8 if $n <= 2 return 1;
9
10 $list[$n] = sheepBorn( $n - 1, $list ) + sheepBorn( $n - 2, $list ) - sheepBorn( $n - 5, $list );
11 return $list[$n];
12 }
13
14 $list = array();
15 for ($year = 1; $year<=10; $year++)
16 echo "The " . $year ."th year: " . sheepBorn($year, $list) . "n" ;
17 ?>

够强!可这样的代码,除了表达一下自己的超强算法之外,给别人带来的困惑也会增加,要在注释上多下功夫了。

最终,真相帝降临:

View Code
<?php
for($i = 0; $i <= 10; $i ++)
{
if ($i < 5)
echo "The " . $i . "year is: 1 ";
else
echo "The " . $i . "year is: 0 ";
}
posted @ 2012-03-13 10:35  暮夕  阅读(194)  评论(0编辑  收藏  举报