[Challenge] Seeing Stars (and a Diamond)

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

[Challenge] Seeing Stars (and a Diamond)

Post 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.
Last edited by McInfo on Mon Jun 14, 2010 5:47 pm, edited 1 time in total.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

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

Post 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);
Post Reply