Function to print a diamond shape

Jay Norwood jayn at prismnet.com
Sun Mar 23 09:48:00 PDT 2014


I converted the solution examples to functions, wrote a test to 
measure each 100 times with a diamond of size 1001.  These are 
release build times.  timon's crashed so I took it out.  Maybe I 
made a mistake copying ... have to go back and look.


D:\diamond\diamond\diamond\Release>diamond 1>nul
brad: time: 78128[ms]
printDiamond1: time: 1166[ms]
printDiamond2: time: 1659[ms]
printDiamond3: time: 631[ms]
jay1: time: 466[ms]
sergei: time: 11944[ms]
jay2: time: 414[ms]


These are the the measurement functions


void measure( void function(in int a) func, int times, int 
diamondsz, string name ){
   StopWatch sw;
   sw.start();
   for (int i=0; i<times; i++){
     func(diamondsz);
   }
   sw.stop;
   stderr.writeln(name, ": time: ", sw.peek().msecs, "[ms]");
}

void measureu( void function(in uint a) func, int times, uint 
diamondsz, string name ){
   StopWatch sw;
   sw.start();
   for (int i=0; i<times; i++){
     func(diamondsz);
   }
   sw.stop;
   stderr.writeln(name, ": time: ", sw.peek().msecs, "[ms]");
}

int main(string[] argv)
{
	int times = 100;
	int dsz = 1001;
	uint dszu = 1001;
	measure (&brad,times,dsz,"brad");
	//measure (&timon,times,dsz,"timon");
	measureu (&printDiamond1,times,dszu,"printDiamond1");
	measure (&printDiamond2,times,dsz,"printDiamond2");
	measure (&printDiamond3,times,dsz,"printDiamond3");
	measure (&jay1,times,dsz,"jay1");
	measure (&sergei,times,dsz,"sergei");
	measure (&jay2,times,dsz,"jay2");

	return 0;

}

All the functions are like this:
void brad(in int length){
   import std.algorithm, std.range, std.stdio, std.conv;

   auto rng =
     chain(iota(length), iota(length, -1, -1))
     .map!((a => " ".repeat(length-a)),
     (a => "#".repeat(a*2+1)))
     .map!(a => chain(a[0].joiner, a[1].joiner, "\n"))
     .joiner;

   writeln(rng);
}

void timon(in int s){
   import std.stdio, std.range, std.algorithm, std.math;

   writef("%(%s\n%)", (i=>i.map!(a=>i.map!(b=>"* "[a+b>s/2])))
     (iota(-s/2,s/2+1).map!abs));
}


More information about the Digitalmars-d-learn mailing list