DEV Community

Discussion on: Daily Challenge #2 - String Diamond

Collapse
 
andreasjakof profile image
Andreas Jakof

A bit late, but with functional flavoured C#

public static string Diamond(ulong n)
{
    if ((n % 2) == 0)
       return null;

    ulong maxIndent = (n-1) / 2;
    StringBuilder sb = new StringBuilder();
    sb.WriteRows(maxIndent, maxIndent, end => end > 0, i => i-1);
    sb.WriteRows(maxIndent, 0, end => end <= maxIndent ,i => i+1);
    return sb.ToString();
}

public static void WriteRows(this StringBuilder sb, ulong maxIndent, ulong start, Func<ulong,bool> condition, Func<ulong,ulong> step)
{
    for (ulong indent = start; condition(indent); indent = step(indent) )
    {
        sb.WriteChars(indent,' ');
        sb.WriteChars(maxIndent - indent,'*');
        sb.Append("*");
        sb.WriteChars(maxIndent - indent,'*');
        sb.WriteChars(indent,' ');
        sb.WriteLine(); //make a NewLine
    }

}

private static void WriteChars(this StringBuilder sb, ulong count, char c)
{
    for (ulong i = 0; i< count; ++i)
    {
        sb.Append(c);
    }
}