Fizz Buzz In PHP

Fizz Buzz / Bizz Buzz?? 😀 kalo engga tau apa itu fizz buzz bisa baca dulu di wiki

Dan ini merupakan implementasinya di PHP.


<?php
/**
* @author  : Muhamad Rifki
* @Desc    : Fizz Buzz
*  Jika kelipatan 3 Fizz
*  Jika kelipatan 5 Buzz
*  Jika kelipatan 15 FizzBuzz
*/

/** Teknik 1: Fizz Buzz Function 1 **/
function FizzBuzz1(){
   for($counter=1; $counter<=100; $counter++){
     if($counter%3 == 0 && $counter%5 == 0){
        echo "FizzBuzz" . "<br>";
     }
     else if($counter%3 == 0){
        echo "Fizz" . "<br>";
     }
     else if($counter%5 == 0){
        echo "Buzz" . "<br>";
     }
     else{
        echo $counter . "<br>";
     }
   }
}

/** Teknik 2: Fizz Buzz Function 2 **/
function FizzBuzz2(){
   for($i=1;$i<=100;$i++){
     $result=$i/3;
     $result2=$i/5;
     if(!preg_match("[\.]" , $result)&&!preg_match("[\.]" , $result2)){
        echo "FizzBuzz<br />";
     }
     elseif(!preg_match("[\.]" , $result)){
        echo "Fizz<br />";
     }
     elseif(!preg_match("[\.]" , $result2)){
        echo "Buzz<br />";
     }
     else{
        echo $i."<br />";
     }
   }
}

/** teknik 3: Fizz Buzz Function 3 **/
function FizzFuzz3(){
   foreach (range(1,100) as $num) {
    $printout = "";
    if ($num%3 == 0){
      $printout .= "Fizz";
    }
    if ($num%5 == 0){
      $printout .= "Buzz";
    }
    if (empty($num)) {
      $printout = $num;
    }
      print "$printout\n";
  }
}

/** Teknik 4: Fizz Buzz Function 4 **/
function FizzBuzz4(){
   for($i=1;$i<101;$i++){
     echo $i%15 ? $i%5 ? $i%3 ? $i : 'Fizz' : 'Buzz' : 'FizzBuzz' , "\n";
   }
}

/** Teknik 5: Fizz Buzz Function 5 **/
function FizzBuzz5(){
   foreach (range(1, 100) as $i) {
     $mod=array($i,"Bizz","Buzz","BizzBuzz");
     echo $mod[(!($i%5))+2 * ($i%7 == 0)].' ';
   }
}
?>

fungsi mana yang lebih elegant dari 5 fungsi tersebut?? atau punya teknik lain? atau mungkin menggunakan class ?? 😀

 

Bacaan lain :

http://www.codinghorror.com/blog/2007/02/why-cant-programmers-program.html

http://www.codinghorror.com/blog/2007/02/fizzbuzz-the-programmers-stairway-to-heaven.html

http://en.wikipedia.org/wiki/Bizz_buzz