Function to print a diamond shape

bearophile bearophileHUGS at lycos.com
Thu Mar 20 17:31:57 PDT 2014


Ali Çehreli:

> This is a somewhat common little exercise: Write a function 
> that takes the size of a diamond and produces a diamond of that 
> size.
>
> When printed, here is the output for size 11:
>
>      *
>     ***
>    *****
>   *******
>  *********
> ***********
>  *********
>   *******
>    *****
>     ***
>      *

Some of my solutions (using each() in the last two is easy):

import std.stdio, std.array, std.string, std.range, 
std.algorithm, std.math;

void printDiamond1(in uint n) {
     immutable k = (n % 2 == 1) ? 1 : 2;

     for (int i = k; i <= n; i += 2)
         writeln("*".replicate(i).center(n));

     for (int i = n - 2; i >= k; i -= 2)
         writeln("*".replicate(i).center(n));
}

void printDiamond2(in int n) {
     iota(!(n % 2), n)
     .map!(i => "*"
                .replicate((n % 2) + ((n / 2) - abs(i - (n / 2))) 
* 2)
                .center(n))
     .join("\n")
     .writeln;
}

void printDiamond3(in int n) {
     writefln("%-(%s\n%)",
              iota(!(n % 2), n)
              .map!(i => "*"
                         .replicate((n % 2) + ((n / 2) - abs(i - 
(n / 2))) * 2)
                         .center(n)));
}

void main() {
     foreach (immutable i; 0 .. 15) {
         printDiamond3(i);
         writeln;
     }
}


Output:


*

**

  *
***
  *

  **
****
  **

   *
  ***
*****
  ***
   *

   **
  ****
******
  ****
   **

    *
   ***
  *****
*******
  *****
   ***
    *

    **
   ****
  ******
********
  ******
   ****
    **

     *
    ***
   *****
  *******
*********
  *******
   *****
    ***
     *

     **
    ****
   ******
  ********
**********
  ********
   ******
    ****
     **

      *
     ***
    *****
   *******
  *********
***********
  *********
   *******
    *****
     ***
      *

      **
     ****
    ******
   ********
  **********
************
  **********
   ********
    ******
     ****
      **

       *
      ***
     *****
    *******
   *********
  ***********
*************
  ***********
   *********
    *******
     *****
      ***
       *

       **
      ****
     ******
    ********
   **********
  ************
**************
  ************
   **********
    ********
     ******
      ****
       **


Bye,
bearophile


More information about the Digitalmars-d-learn mailing list