Advertisement
cdsatrian

Square Number Diamond Pattern

Dec 13th, 2012
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.74 KB | None | 0 0
  1. <?php
  2. /*********************************
  3. FILENAME     : diamond.php
  4. PURPOSE      : print square number in diamond pattern
  5. CREATED DATE : 2012-12-13
  6. CREATED BY   : cahya dsn
  7. **********************************/
  8. function diamond($n=3)
  9. {
  10.   $space=strlen($n*$n)+1;
  11.   for($i=0;$i<$n*2;$i++){
  12.     $rst='';
  13.     if($i<$n){
  14.       for($j=0;$j<=$i;$j++){
  15.         $r=($n*$i+1)-($n-1)*$j;
  16.         $rst.=str_pad($r, $space, " ", STR_PAD_BOTH);
  17.       }
  18.     }else{
  19.       for($j=2*$n-$i-1;$j>0;$j--){
  20.         $r=($j+$i+1)*$n-($n*$n+$j)+1;
  21.         $rst.=str_pad($r, $space, " ", STR_PAD_BOTH);
  22.       }
  23.     }
  24.     echo str_pad($rst, $n*$space, " ", STR_PAD_BOTH)."\n";
  25.   }
  26. }
  27.  
  28. //example use:
  29. echo "<pre>";
  30. diamond(3);
  31. diamond(6);
  32. diamond(10);
  33. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement