Page 1 of 1

[Challenge] Seeing Stars (and a Diamond)

Posted: Sun Sep 20, 2009 6:33 pm
by McInfo
Write a script to generate stars in a diamond pattern as shown below. The width of the diamond should be determined by user input. Both Web scripts and command-line scripts are acceptable.

Example 1: seven stars wide

Code: Select all

     *  
    ***  
   *****
  *******
   *****
    ***  
     *   
All lines should contain stars. If the width is even, the first and last lines will contain two stars each.

Example 2: six stars wide

Code: Select all

    **  
   ****
  ******
   ****
    **  
If you want more of a challenge, write a variation with one or more of these constraints:
  • Use only two variables (not including user-submitted variables).
  • Use only one loop with no conditions in the loop body and only one condition in the loop header.
This challenge is based on an exercise found in a Java book by Tony Gaddis. (ISBN 1576761711)

Edit: This post was recovered from search engine cache.

Re: [Challenge] Seeing Stars (and a Diamond)

Posted: Sun Sep 20, 2009 8:04 pm
by requinix
I accept your constraints :)

Code: Select all

function diamond($width) {
    for ($i = $width - 1 + ($width % 2); $i >= 1; $i--) {
        echo str_pad(str_repeat("*", 2 * min($i, $width + ($width % 2) - $i) - ($width % 2)), $width, " ", STR_PAD_BOTH), "\n";
    }
}
 
diamond(7);