Function to print a diamond shape

Ali Çehreli acehreli at yahoo.com
Thu Mar 20 22:13:27 PDT 2014


On 03/20/2014 02:25 PM, Ali Çehreli wrote:

> Write a function that takes
> the size of a diamond and produces a diamond of that size.

I have learned a lot, especially the following two:

1) chain'ing iotas is an effective way of producing non-monotonic number 
intervals (and more).

2) There is std.string.center. :)

Also considering readability, here is my favorite so far:

auto diamondShape(size_t N, dchar fillChar = '*')
{
     import std.range : chain, iota, repeat;
     import std.algorithm : map;
     import std.conv : text;
     import std.string : center, format;
     import std.exception : enforce;

     enforce(N % 2, format("Size must be an odd number. (%s)", N));

     return
         chain(iota(1, N, 2),
               iota(N, 0, -2))
         .map!(i => fillChar.repeat(i))
         .map!(s => s.text)
         .map!(s => s.center(N));
}

unittest
{
     import std.exception : assertThrown;
     import std.algorithm : equal;

     assertThrown(diamondShape(4));
     assert(diamondShape(3, 'o').equal([ " o ", "ooo", " o " ]));
}

void main()
{
     import std.stdio : writefln;

     writefln("%-(%s\n%)", diamondShape(11));
}

Ali



More information about the Digitalmars-d-learn mailing list