Function to print a diamond shape
Jay Norwood
jayn at prismnet.com
Mon Mar 24 19:25:56 PDT 2014
not through yet with the diamond. This one is a little faster.
Appending the newline to the stars and calculating the slice
backward from the end would save a w.put for the newlines ...
probably faster. I keep looking for a way to create a dynamic
array of a specific size, filled with the init value I provide.
Does it exist?
D:\diamond\diamond\diamond\Release>diamond 1>nul
brad: time: 19370[ms]
printDiamond1: time: 1140[ms]
printDiamond2: time: 1631[ms]
printDiamond3: time: 633[ms]
jay1: time: 459[ms]
sergei: time: 11886[ms]
jay2: time: 415[ms]
diamondShape: time: 4553[ms]
printDiamond: time: 187[ms]
printDiamonde2a: time: 139[ms]
void printDiamonde2a(in uint N)
{
size_t N2 = N/2;
char pSpace[] = uninitializedArray!(char[])(N2);
pSpace[] = ' ';
char pStars[] = uninitializedArray!(char[])(N);
pStars[] = '*';
char pNewLine[]=uninitializedArray!(char[])(2);
pNewLine[] = '\n';
auto w = appender!(char[])();
w.reserve(N*4);
foreach (n ; 0 .. N2 + 1){
w.put(pSpace[0 .. N2 - n]);
w.put(pStars[0 .. 2*n+1]);
w.put(pNewLine[1]);
}
foreach_reverse (n ; 0 .. N2){
w.put(pSpace[0 .. N2 - n]);
w.put(pStars[0 .. 2*n+1]);
w.put(pNewLine[1]);
}
write(w.data);
}
More information about the Digitalmars-d-learn
mailing list