Function to print a diamond shape

Jay Norwood jayn at prismnet.com
Mon Mar 24 22:06:42 PDT 2014


These were times on ubuntu. I may have printed debug build times 
previously, but these are dmd release build.  I gave up trying to 
figure out how to build ldc on ubuntu.  The dmd one click 
installer is much appreciated.

brad: time: 12425[ms]
printDiamond1: time: 380[ms]
printDiamond2: time: 728[ms]
printDiamond3: time: 378[ms]
jay1: time: 62[ms]
sergei: time: 3965[ms]
jay2: time: 27[ms]
diamondShape: time: 2778[ms]
printDiamond: time: 19[ms]
printDiamonde: time: 19[ms]
printDiamonde2b: time: 16[ms]


This was using the appended newlines to get rid of the extra wput 
in the loops.

void printDiamonde2b(in uint N)
{
     uint N2 = N/2;
     char pSpace[] = uninitializedArray!(char[])(N2);
     pSpace[] = ' ';

     char pStars[] = uninitializedArray!(char[])(N+1);
     pStars[] = '*';

     pStars[$-1] = '\n';

     auto w = appender!(char[])();
     w.reserve(N*3);

     foreach (n ; 0 .. N2 + 1){
         w.put(pSpace[0 .. N2 - n]);
	w.put(pStars[$-2*n-2 .. $]);
	}

     foreach_reverse (n ; 0 .. N2){
         w.put(pSpace[0 .. N2 - n]);
	w.put(pStars[$-2*n-2 .. $]);
	}

     write(w.data);
}


More information about the Digitalmars-d-learn mailing list