How to resolve the algorithm Koch curve step by step in the zkl programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Koch curve step by step in the zkl programming language

Table of Contents

Problem Statement

Draw a Koch curve. See details: Koch curve

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Koch curve step by step in the zkl programming language

Source code in the zkl programming language

var width=512, height=512, img=PPM(width,height,0xFfffFF);   // white canvas
var angle=(60.0).toRad();
const green=0x00FF00;

fcn koch(x1,y1, x2,y2, it){
   x3,y3 := (x1*2 + x2)  /3, (y1*2 + y2)  /3;
   x4,y4 := (x1   + x2*2)/3, (y1   + y2*2)/3;
   x:=x3 + (x4-x3)*angle.cos() + (y4-y3)*angle.sin();
   y:=y3 - (x4-x3)*angle.sin() + (y4-y3)*angle.cos();
 
   if(it>0){
      it-=1;
      koch(x1,y1, x3,y3, it);
      koch(x3,y3, x, y,  it);
      koch(x, y,  x4,y4, it);
      koch(x4,y4, x2,y2, it);
   }else{
      x,y, x1,y1, x2,y2, x3,y3, x4,y4 = 
         T(x,y, x1,y1, x2,y2, x3,y3, x4,y4).apply("toInt");
      img.line(x1,y1, x3,y3, green);
      img.line(x3,y3, x, y,  green);
      img.line(x, y,  x4,y4, green);
      img.line(x4,y4, x2,y2, green);
   }
}

koch(100.0,100.0, 400.0,400.0, 4);
img.writeJPGFile("koch.zkl.jpg");

lsystem("F--F--F", Dictionary("F","F+F--F+F"), "+-", 4)  // snowflake
//lsystem("F", Dictionary("F","F+F--F+F"), "+-", 3)	 // curve
: turtle(_);

fcn lsystem(axiom,rules,consts,n){	// Lindenmayer system --> string
   foreach k in (consts){ rules.add(k,k) }
   buf1,buf2 := Data(Void,axiom).howza(3), Data().howza(3);  // characters
   do(n){
      buf1.pump(buf2.clear(), rules.get);
      t:=buf1; buf1=buf2; buf2=t;	// swap buffers
   }
   buf1.text		// n=4 snow flake --> 1,792 characters
}

fcn turtle(koch){
   const D=10.0;
   dir,deg60, x,y := 0.0, (60.0).toRad(), 20.0, 710.0; // turtle; x,y are float
   img,color := PPM(850,950), 0x00ff00;
   foreach c in (koch){
      switch(c){
	 case("F"){   // draw forward
	    dx,dy := D.toRectangular(dir);
	    tx,ty := x,y; x,y = (x+dx),(y+dy);
	    img.line(tx.toInt(),ty.toInt(), x.toInt(),y.toInt(), color);
	 }
	 case("-"){ dir-=deg60 } // turn right 60*
	 case("+"){ dir+=deg60 } // turn left  60*
      }
   }
   img.writeJPGFile("kochSnowFlake.zkl.jpg");
}

  

You may also check:How to resolve the algorithm Arithmetic/Complex step by step in the CoffeeScript programming language
You may also check:How to resolve the algorithm Calkin-Wilf sequence step by step in the Maxima programming language
You may also check:How to resolve the algorithm Almost prime step by step in the EasyLang programming language
You may also check:How to resolve the algorithm Text processing/Max licenses in use step by step in the Raku programming language
You may also check:How to resolve the algorithm 99 bottles of beer step by step in the Ra programming language