Koch curve: Difference between revisions

19,104 bytes added ,  1 month ago
m
(→‎{{header|Python}}: added code from sierpinski curve)
 
(39 intermediate revisions by 12 users not shown)
Line 7:
{{libheader|Action! Tool Kit}}
{{libheader|Action! Real Math}}
<langsyntaxhighlight Actionlang="action!">INCLUDE "H6:REALMATH.ACT"
 
DEFINE MAXSIZE="20"
Line 125:
DO UNTIL CH#$FF OD
CH=$FF
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Koch_curve.png Screenshot from Atari 8-bit computer]
Line 131:
=={{header|Ada}}==
{{libheader|APDF}}
<langsyntaxhighlight Adalang="ada">with Ada.Command_Line;
with Ada.Numerics.Generic_Elementary_Functions;
with Ada.Text_IO;
Line 191:
Rule => Even_Odd);
Doc.Close;
end Koch_Curve;</langsyntaxhighlight>
 
=={{header|BASIC256ALGOL 68}}==
{{libheader|ALGOL 68-l-system}}
<lang BASIC256>global RtoD, DtoR
Generates an SVG file containing the curve using the L-System. Very similar to the Algol 68 [[Sierpinski square curve]] sample.
RtoD = 180 / Pi
<br/>
DtoR = Pi / 180
Note the Algol 68 L-System library source code is on a separate page on Rosetta Code - follow the above link and then to the Talk page.
<syntaxhighlight lang="algol68">
BEGIN # Koch Curve in SVG #
# uses the RC Algol 68 L-System library for the L-System evaluation & #
# interpretation #
 
PR read "lsystem.incl.a68" PR # include L-System utilities #
global posX, posY, angulo
posX = 170 : posY = 100 : angulo = 0
 
PROC koch curve = ( STRING fname, INT size, length, order, init x, init y )VOID:
global ancho, alto
IF FILE svg file;
ancho = 650 : alto = 650
BOOL open error := IF open( svg file, fname, stand out channel ) = 0
graphsize ancho, alto
THEN
# opened OK - file already exists and #
# will be overwritten #
FALSE
ELSE
# failed to open the file #
# - try creating a new file #
establish( svg file, fname, stand out channel ) /= 0
FI;
open error
THEN # failed to open the file #
print( ( "Unable to open ", fname, newline ) );
stop
ELSE # file opened OK #
 
REAL x := init x;
subroutine kochLado(longitud, fondo)
REAL y := init y;
if fondo = 0 then
INT angle := 0;
dx = cos(angulo*DtoR) * longitud
put( svg file, ( "<svg xmlns='http://www.w3.org/2000/svg' width='"
dy = sin(angulo*DtoR) * longitud
, whole( size, 0 ), "' height='", whole( size, 0 ), "'>"
color rgb(5,100,24)
, newline, "<rect width='100%' height='100%' fill='white'/>"
line (posX, posY, posX+dx, posY+dy)
, newline, "<path stroke-width='1' stroke='black' fill='none' d='"
posX += dx
, newline, "M", whole( x, 0 ), ",", whole( y, 0 ), newline
posY += dy
)
else
);
call kochLado(longitud/3.0, fondo-1)
angulo += 60
call kochLado(longitud/3.0, fondo-1)
angulo -= 120
call kochLado(longitud/3.0, fondo-1)
angulo += 60
call kochLado(longitud/3.0, fondo-1)
end if
end subroutine
 
LSYSTEM ssc = ( "F++F++F"
subroutine CopoNieveKoch(longitud, recursionfondo)
, ( "F" -> "F-F++F-F"
for i = 1 to 6
)
call kochLado(longitud,recursionfondo)
);
angulo -= 300
STRING curve = ssc EVAL order;
next i
curve INTERPRET ( ( CHAR c )VOID:
end subroutine
IF c = "F" THEN
x +:= length * cos( angle * pi / 180 );
y +:= length * sin( angle * pi / 180 );
put( svg file, ( " L", whole( x, 0 ), ",", whole( y, 0 ), newline ) )
ELIF c = "+" THEN
angle +:= 60 MODAB 360
ELIF c = "-" THEN
angle -:= 60 MODAB 360
FI
);
put( svg file, ( "'/>", newline, "</svg>", newline ) );
close( svg file )
FI # sierpinski square # ;
 
koch curve( "koch.svg", 600, 5, 4, 150, 150 )
for n = 0 To 7
clg
fastgraphics
text 3,4, "Copo de nieve de Koch"
text 4,16, "Iteración número: " & n
call CopoNieveKoch(280, n)
pause 0.8
refresh
next n
 
END
imgsave "Koch_curve.jpg", "jpg"
</syntaxhighlight>
end</lang>
 
=={{header|Amazing Hopper}}==
Line 250 ⟶ 266:
or
./src/kock_curve.com > kockcurve.svg
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
#!/usr/bin/hopper
 
Line 338 ⟶ 354:
{output}
back
</syntaxhighlight>
</lang>
 
 
=={{header|AutoHotkey}}==
{{trans|Go}}
Requires [https://www.autohotkey.com/boards/viewtopic.php?t=6517 Gdip Library]
<langsyntaxhighlight AutoHotkeylang="autohotkey">gdip1()
KochX := 0, KochY := 0
Koch(0, 0, A_ScreenWidth, A_ScreenHeight, 4, Arr:=[])
Line 424 ⟶ 439:
Gdip_Shutdown(pToken)
ExitApp
Return</langsyntaxhighlight>
 
=={{header|BASIC256}}==
<syntaxhighlight lang="basic256">global RtoD, DtoR
RtoD = 180 / Pi
DtoR = Pi / 180
 
global posX, posY, angulo
posX = 170 : posY = 100 : angulo = 0
 
global ancho, alto
ancho = 650 : alto = 650
graphsize ancho, alto
 
subroutine kochLado(longitud, fondo)
if fondo = 0 then
dx = cos(angulo*DtoR) * longitud
dy = sin(angulo*DtoR) * longitud
color rgb(5,100,24)
line (posX, posY, posX+dx, posY+dy)
posX += dx
posY += dy
else
call kochLado(longitud/3.0, fondo-1)
angulo += 60
call kochLado(longitud/3.0, fondo-1)
angulo -= 120
call kochLado(longitud/3.0, fondo-1)
angulo += 60
call kochLado(longitud/3.0, fondo-1)
end if
end subroutine
 
subroutine CopoNieveKoch(longitud, recursionfondo)
for i = 1 to 6
call kochLado(longitud,recursionfondo)
angulo -= 300
next i
end subroutine
 
for n = 0 To 7
clg
fastgraphics
text 3,4, "Copo de nieve de Koch"
text 4,16, "Iteración número: " & n
call CopoNieveKoch(280, n)
pause 0.8
refresh
next n
 
imgsave "Koch_curve.jpg", "jpg"
end</syntaxhighlight>
 
=={{header|C}}==
Interactive program which takes the width, height (of the Graphics window) and recursion level of the Koch curve as inputs, prints out usage on incorrect invocation. Requires the [http://www.cs.colorado.edu/~main/bgi/cs1300/ WinBGIm] library.
<syntaxhighlight lang="c">
<lang C>
#include<graphics.h>
#include<stdlib.h>
Line 489 ⟶ 555:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|C++}}==
The output of this program is an SVG file depicting a Koch snowflake.
<langsyntaxhighlight lang="cpp">// See https://en.wikipedia.org/wiki/Koch_snowflake
#include <fstream>
#include <iostream>
Line 560 ⟶ 626:
koch_curve_svg(out, 600, 5);
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
{{out}}
[[Media:Koch_curve_cpp.svg]]
See: [https://slack-files.com/T0CNUL56D-F016A5L6J5D-3c32740a46 koch_curve.svg] (offsite SVG image)
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|Windows,Forms,SysUtils,Types,ExtCtrls,Graphics}}
Fancy version, shows six iterations of both single-line and triangle version drawn to graphics screen. Uses vector libraries to simplify the process
 
[[File:DelphiKochSNowflake2.png|thumb|none]]
 
<syntaxhighlight lang="Delphi">
{===== These routines would normally be in extermal ======}
{===== libraries, but they are presented here for clarity ======}
 
type T2DVector=packed record
X,Y: double;
end;
 
type T2DLine = packed record
P1,P2: T2DVector;
end;
 
procedure ClearImage(Image: TImage; Color: TColor);
var R: TRect;
begin
R:=Rect(0,0,Image.Picture.Bitmap.Width,Image.Picture.Bitmap.Height);
Image.Canvas.Brush.Color:=Color;
Image.Canvas.Brush.Style:=bsSolid;
Image.Canvas.Pen.Mode:=pmCopy;
Image.Canvas.Pen.Style:=psSolid;
Image.Canvas.Pen.Color:=Color;
Image.Canvas.Rectangle(R);
Image.Invalidate;
end;
 
 
 
procedure DrawLine2D(Canvas: TCanvas; L: T2DLine; C: TColor);
{Draw Line on specified canvas}
begin
Canvas.Pen.Color:=C;
Canvas.MoveTo(Trunc(L.P1.X),Trunc(L.P1.Y));
Canvas.LineTo(Trunc(L.P2.X),Trunc(L.P2.Y));
end;
 
 
 
function MakeVector2D(const X,Y: double): T2DVector;
{Create 2D Vector from X and Y}
begin
Result.X:=X;
Result.Y:=Y;
end;
 
 
function VectorAdd2D(const V1,V2: T2DVector): T2DVector;
{Add V1 and V2}
begin
Result.X:= V1.X + V2.X;
Result.Y:= V1.Y + V2.Y;
end;
 
 
function VectorSubtract2D(const V1,V2: T2DVector): T2DVector;
{Subtract V2 from V1}
begin
Result.X:= V1.X - V2.X;
Result.Y:= V1.Y - V2.Y;
end;
 
 
function VectorABS2D(const V: T2DVector): double;
{Find ABS of vector}
begin
Result:=Sqrt(Sqr(V.X) + Sqr(V.Y));
end;
 
 
function LineLength2D(const L: T2DLine) : double; overload;
{ Find length of a line defined by P1 and P2 }
begin
Result:=VectorABS2D(VectorSubtract2D(L.P2,L.P1));
end;
 
 
 
function ScalarDivide2D(const V: T2DVector; const S: double): T2DVector;
{Divide vector by scalar}
begin
Result.X:=V.X / S;
Result.Y:=V.Y / S;
end;
 
 
 
function ScalarProduct2D(const V: T2DVector; const S: double): T2DVector;
{Multiply vector by scalar}
begin
Result.X:=V.X * S;
Result.Y:=V.Y * S;
end;
 
 
function UnitVector2D(const V: T2DVector): T2DVector;
{Return unit vector}
var L: double;
begin
L:=VectorABS2D(V);
if L=0.0 then L:=1E-99;
Result.X:=V.X / L;
Result.Y:=V.Y / L;
end;
 
 
function GetUnitNormal2D(const V: T2DVector): T2DVector; overload;
{Returns perpendicular unit vector}
begin
Result:=UnitVector2D(MakeVector2D(-V.Y, V.X));
end;
 
 
function ExtendLine2D(const L1: T2DLine; const Len: double): T2DVector;
{ Return a point that extends line L1 by Len }
var Len1,UX,UY : double;
begin
Len1 := LineLength2D(L1)+1E-9;
UX := (L1.P2.X - L1.P1.X)/Len1;
UY := (L1.P2.Y - L1.P1.Y)/Len1;
Result.X := L1.P2.X +(UX *Len);
Result.Y := L1.P2.Y+(UY *Len);
end;
 
 
 
{---------------------------------------------------------------------------}
 
{Array of lines to contain the snow flake}
 
type TLineArray = array of T2DLine;
 
{Screen and display parameters}
 
var ScreenSize: TPoint;
var SquareBox: TRect;
var BoxSize: integer;
 
procedure ConfigureScreen(Image: TImage);
{Setup screen parameters based Image component}
begin
ScreenSize:=Point(Image.Width, Image.Height);
if ScreenSize.X<ScreenSize.Y then BoxSize:=ScreenSize.X
else BoxSize:=ScreenSize.Y;
SquareBox:=Rect(0,0,BoxSize,BoxSize);
OffsetRect(SquareBox,(ScreenSize.X-BoxSize) div 2,(ScreenSize.Y-BoxSize) div 2);
end;
 
 
procedure DrawLines(Canvas: TCanvas; Lines: TLineArray);
{Draw all the lines in the snow flake}
var I: integer;
begin
for I:=0 to High(Lines) do
DrawLine2D(Canvas,Lines[I],clRed);
end;
 
 
procedure BreakLine(L: T2DLine; var L1,L2,L3,L4: T2DLine);
{Break one line into the four new lines of the next iteration}
var Len,Len3,O: double;
var Delta: TPoint;
var P1,P2,P3,P4,P5,Half: T2DVector;
begin
Len:=LineLength2D(L);
Len3:=Len/3;
O:= Sqrt(sqr(Len3)-sqr(Len3/2));
P1:=L.P1;
P2:=ExtendLine2D(L,-Len3*2);
P4:=ExtendLine2D(L,-Len3);
P5:=L.P2;
Half:=ScalarDivide2D(VectorAdd2D(P4,P2),2);
P3:=GetUnitNormal2D(VectorSubtract2D(P4,P2));
P3:=ScalarProduct2D(P3,O);
P3:=VectorAdd2D(P3,Half);
L1.P1:=P1; L1.P2:=P2;
L2.P1:=P2; L2.P2:=P3;
L3.P1:=P3; L3.P2:=P4;
L4.P1:=P4; L4.P2:=P5;
end;
 
 
 
procedure BreakAndStoreLines(Line: T2DLine; var Lines: TLineArray);
{Break one line and store the resulting four in array}
var Len: integer;
begin
Len:=Length(Lines);
SetLength(Lines,Len+4);
BreakLine(Line, Lines[Len+0],Lines[Len+1],Lines[Len+2],Lines[Len+3]);
end;
 
 
procedure BreakArray(var Lines: TLineArray);
{Break all the lines in an array and replace them with new lines}
var I: integer;
var AT: TLineArray;
begin
AT:=Lines;
SetLength(Lines,0);
for I:=0 to High(AT) do
BreakAndStoreLines(AT[I], Lines);
end;
 
procedure LineSeed(var Lines: TLineArray);
{Put single line seed in array}
var Border: integer;
begin
Border:=MulDiv(BoxSize,10,100);
SetLength(Lines,1);
Lines[0].P1:=MakeVector2D(SquareBox.Left + Border, SquareBox.Top + Border);
Lines[0].P2:=MakeVector2D(SquareBox.Right - Border, SquareBox.Top + Border);
end;
 
 
procedure TriangleSeed(var Lines: TLineArray);
{Put triangle seed in array}
const Border = 15;
var R: TRect;
var PixelBorder: integer;
var H: double;
begin
SetLength(Lines,3);
PixelBorder:=MulDiv(BoxSize,Border,100);
R.Left:=SquareBox.Left + PixelBorder;
R.Right:=SquareBox.Right - PixelBorder;
R.Top:=SquareBox.Top + MulDiv(PixelBorder,1414,1000);
R.Bottom:=SquareBox.Bottom - PixelBorder;
OffsetRect(R,0,-MulDiv(BoxSize,15,100));
 
Lines[0].P1:=MakeVector2D(R.Left, R.Bottom);
Lines[0].P2:=MakeVector2D(R.Right, R.Bottom);
 
Lines[1].P1:=Lines[0].P2;
Lines[1].P2:=MakeVector2D((R.Right+R.Left) div 2,R.Top);
 
Lines[2].P1:=Lines[1].P2;
Lines[2].P2:=Lines[0].P1;
end;
 
 
 
procedure DoKochSnowFlake(Image: TImage);
{Construct and display various Koch snow flakes}
var Lines: TLineArray;
 
procedure IterateSnowflakes;
{Iterate through six phases of snow flakes}
var I,J: integer;
begin
for I:=1 to 6 do
begin
ClearImage(Image,clWhite);
Image.Canvas.Pen.Color:=clBlack;
Image.Canvas.Rectangle(SquareBox);
Image.Canvas.TextOut(10, 15, IntToStr(I)+' '+IntToStr(Length(Lines)));
DrawLines(Image.Canvas,Lines);
Image.Repaint;
Sleep(2000);
BreakArray(Lines);
end;
end;
 
 
begin
ConfigureScreen(Image);
{Iterate snow flake line}
LineSeed(Lines);
IterateSnowflakes;
{Iterate snow flake triangle}
TriangleSeed(Lines);
IterateSnowflakes;
end;
 
</syntaxhighlight>
{{out}}
[[File:DelphiKochSNowflake1.png|thumb|none]]
<pre>
</pre>
 
=={{header|EasyLang}}==
 
[https://easylang.dev/show/#cod=ZZLdUoMwEIXv8xTn0tohhp/WK3wXB6llrKQDjCZv754lFWOvIOfbs3uycJ18hw/fnRFKxBKhQqwwLP0EC2sAhBotHoQ+osJeCnZ4Qk0SlcQbiRsJTfKwnnjzNMnD+oyEgxAZthdjg0Jed8I7P+PoKEaKUcV5GEXUdjRJjiIzrfyfae1E03BaL/gCPVLhsWhRpvPfhdTsz4KMqSqRJcAdU1XiyPA7puq2ZLL+Mvep5jKM/To3EzgsEzghE9g2EziBgjXWUPke3pYznK2NtJeLHkzks3bm03/dZp78hNfxXXSHeemvKCuHxaNqdFHStIV+1GeXFirV+hlI4i/h/hO5+7U0pmYIGlBjSFZrfgA= Run it]
 
<syntaxhighlight lang="easylang">
proc koch x1 y1 x2 y2 iter . .
x3 = (x1 * 2 + x2) / 3
y3 = (y1 * 2 + y2) / 3
x4 = (x1 + x2 * 2) / 3
y4 = (y1 + y2 * 2) / 3
x5 = x3 + (x4 - x3) * cos 60 + (y4 - y3) * sin 60
y5 = y3 - (x4 - x3) * sin 60 + (y4 - y3) * cos 60
if iter > 0
iter -= 1
koch x1 y1 x3 y3 iter
koch x3 y3 x5 y5 iter
koch x5 y5 x4 y4 iter
koch x4 y4 x2 y2 iter
else
line x1 y1
line x3 y3
line x5 y5
line x4 y4
line x2 y2
.
.
linewidth 0.3
x1 = 15
y1 = 30
move x1 y1
for ang = 0 step 120 to 240
x2 = x1 + 70 * cos ang
y2 = y1 + 70 * sin ang
koch x1 y1 x2 y2 4
x1 = x2
y1 = y2
.
</syntaxhighlight>
 
=={{header|Factor}}==
The approach taken is to generate a [[Thue-Morse]] sequence. Using turtle graphics, move forward for each 0 encountered and rotate 60 degrees for each 1 encountered. Remarkably, this produces a Koch curve.
<langsyntaxhighlight lang="factor">USING: accessors images images.testing images.viewer kernel
literals math math.constants math.functions sequences ;
IN: rosetta-code.koch-curve
Line 607 ⟶ 997:
] 2with each image-window ;
 
MAIN: koch-curve</langsyntaxhighlight>
{{out}}
[https://i.imgur.com/MVS8QiS.png]
Line 613 ⟶ 1,003:
=={{header|Forth}}==
{{works with|4tH v3.64}}
<syntaxhighlight lang="text">include lib/graphics.4th
include lib/math.4th
include lib/enter.4th
Line 648 ⟶ 1,038:
450 500 115 300 r> koch
 
s" gkoch.ppm" save_image \ save the image</langsyntaxhighlight>
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">
Const Pi = 4 * Atn(1)
Const RtoD = 180 / Pi
Line 696 ⟶ 1,086:
Sleep
End
</syntaxhighlight>
</lang>
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/L-system}}
 
'''Solution'''
 
It can be done using an [[wp:L-system|L-system]]. There are generic functions written in Fōrmulæ to compute an L-system in the page [[L-system#Fōrmulæ | L-system]].
 
The program that creates a Koch curve is:
 
[[File:Fōrmulæ - L-system - Koch's snowflake 01.png]]
 
[[File:Fōrmulæ - L-system - Koch's snowflake 02.png]]
 
=={{header|Go}}==
{{libheader|Go Graphics}}
{{trans|Ring}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 741 ⟶ 1,145:
dc.Stroke()
dc.SavePNG("koch.png")
}</langsyntaxhighlight>
 
{{out}}
Line 752 ⟶ 1,156:
Generates SVG for a Koch snowflake. To view, save to a text file with an .svg extension, and open in a browser.
 
<langsyntaxhighlight lang="haskell">import Data.Bifunctor (bimap)
import Text.Printf (printf)
 
Line 853 ⟶ 1,257:
)
)
xys</langsyntaxhighlight>
 
=={{header|IS-BASIC}}==
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "Koch.bas"
110 OPTION ANGLE DEGREES
120 SET 22,1:SET 23,0:SET 24,42:SET 25,26
Line 877 ⟶ 1,281:
290 PLOT LEFT A;FORWARD D;
300 END IF
310 END DEF</langsyntaxhighlight>
 
=={{header|J}}==
 
<langsyntaxhighlight Jlang="j">seg=: [ + [: +/\ (0,1r3*1,(^j.(,-)_2 o.1r2),1) * -~
koch=: [: ,/ 2 seg/\ ]
 
require'plot'
tri=: ^ j. 4r3 * (_2 o. 0) * i._4
plot koch ^: 5 tri</langsyntaxhighlight>
 
[[j:File:J-Koch-snowflake.png|example]]
 
The idea is to continually expand the segments between a list of points in the complex plane. Given consecutive x and y in the list, v = (y-x)/3 is a vector representing 1/3 of the trip from x to y. An iteration building the Koch curve starts at x, advances by v, advances by v rotated by 60 degrees, advances by v rotated -60 degrees, and finally advances by another v, reaching y. x seg y produces this expansion. koch takes a list of points and expands segments between consecutive ones, producing another list. koch ^: 5 does this 5 times, and plot shows the snowflake in a window.
 
=={{header|Java}}==
<syntaxhighlight lang="java">
 
import java.awt.Point;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
 
public final class KochCurve {
public static void main(String[] aArgs) throws IOException {
List<Point> points = initialEquilateralTriangle();
for ( int i = 1; i < 5; i++ ) {
points = nextIteration(points);
}
String text = kochCurveText(points, IMAGE_SIZE);
Files.write(Paths.get("C:/Users/psnow/Desktop/koch.svg"), text.getBytes());
}
private static List<Point> initialEquilateralTriangle() {
final int margin = 50;
final int boxSize = IMAGE_SIZE - margin;
final int sideLength = Math.round(boxSize * SIN_60_DEGREES);
final int x = ( boxSize + margin - sideLength ) / 2;
final int y = Math.round(( boxSize + margin ) / 2 - sideLength * SIN_60_DEGREES / 3);
List<Point> points = Arrays.asList(
new Point(x, y),
new Point(x + sideLength / 2, Math.round(y + sideLength * SIN_60_DEGREES)),
new Point(x + sideLength, y),
new Point(x, y)
);
return points;
}
private static List<Point> nextIteration(List<Point> aPoints) {
List<Point> result = new ArrayList<Point>();
for ( int i = 0; i < aPoints.size() - 1; i++ ) {
final int x0 = aPoints.get(i).x;
final int y0 = aPoints.get(i).y;
final int x1 = aPoints.get(i + 1).x;
final int y1 = aPoints.get(i + 1).y;
final int dy = y1 - y0;
final int dx = x1 - x0;
result.add(aPoints.get(i));
result.add( new Point(x0 + dx / 3, y0 + dy / 3) );
result.add( new Point(Math.round(x0 + dx / 2 - dy * SIN_60_DEGREES / 3),
Math.round(y0 + dy / 2 + dx * SIN_60_DEGREES / 3)) );
result.add( new Point(x0 + 2 * dx / 3, y0 + 2 * dy / 3) ) ;
}
result.add(aPoints.get(aPoints.size() - 1));
return result;
}
private static String kochCurveText(List<Point> aPoints, int aSize) {
StringBuilder text = new StringBuilder();
text.append("<svg xmlns='http://www.w3.org/2000/svg'");
text.append(" width='" + aSize + "' height='" + aSize + "'>\n");
text.append("<rect style='width:100%;height:100%;fill:cyan'/>\n");
text.append("<polygon points='");
for ( int i = 0; i < aPoints.size(); i++ ) {
text.append(aPoints.get(i).x + ", " + aPoints.get(i).y + " ");
}
text.append("' style='fill:pink;stroke:black;stroke-width:2'/>\n</svg>\n");
return text.toString();
}
private static final int IMAGE_SIZE = 700;
private static final float SIN_60_DEGREES = (float) Math.sin(Math.PI / 3.0);
}
</syntaxhighlight>
{{ out }}
[[Media:kochCurve.svg]]
 
=={{header|JavaScript}}==
Line 897 ⟶ 1,385:
 
{{Trans|Haskell}}{{Trans|Python}}
<langsyntaxhighlight lang="javascript">(() => {
'use strict';
 
Line 1,024 ⟶ 1,512:
// MAIN ---
return main();
})();</langsyntaxhighlight>
 
=={{header|jq}}==
Line 1,037 ⟶ 1,525:
depending on the location of the included file, and the command-line
options used.
<langsyntaxhighlight lang="jq">include "turtle" {search: "."};
 
def rules:
Line 1,066 ⟶ 1,554:
 
koch_curve(5)
| draw(1200)</langsyntaxhighlight>
 
 
=={{header|Julia}}==
Multiple snowflake plots. Copied from https://www.juliabloggers.com/koch-snowflakes-for-the-holidays/.
<langsyntaxhighlight Julialang="julia">using Plots
 
function pointskoch(points, maxk, α = sqrt(3)/2)
Line 1,241 ⟶ 1,729:
#large_koch()
koch_julia()
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
{{trans|Ring}}
This incorporates code from other relevant tasks in order to provide a runnable example. The image produced is saved to disk where it can be viewed with a utility such as EOG.
<langsyntaxhighlight lang="scala">// Version 1.2.41
 
import java.awt.Color
Line 1,327 ⟶ 1,815:
ImageIO.write(image, "jpg", kFile)
}
}</langsyntaxhighlight>
 
{{output}}
Line 1,335 ⟶ 1,823:
 
=={{header|Lambdatalk}}==
<langsyntaxhighlight lang="scheme">
{def koch
{lambda {:d :n}
Line 1,362 ⟶ 1,850:
The output is a "square of Koch" which can be seen in
http://lambdaway.free.fr/lambdawalks/?view=koch
</syntaxhighlight>
</lang>
 
=={{header|Logo}}==
Line 1,368 ⟶ 1,856:
{{works with|FMSLogo}}
 
<syntaxhighlight lang="fmslogo">
<lang >
to ff :l :i
cs
Line 1,394 ⟶ 1,882:
 
Make "startup [zzz]
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
Using the Bitmap class [[Bitmap#Lua|here]], with an ASCII pixel representation, then extending with <code>line()</code> as [[Bitmap/Bresenham%27s_line_algorithm#Lua|here]], then extending further..
<langsyntaxhighlight lang="lua">local cos, sin, floor, pi = math.cos, math.sin, math.floor, math.pi
 
function Bitmap:render()
Line 1,439 ⟶ 1,927:
bitmap:render()
print()
end</langsyntaxhighlight>
{{out}}
<pre style="font-size:50%">...........
Line 1,596 ⟶ 2,084:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight lang="mathematica">Graphics[{GeometricTransformation[KochCurve[5], RotationTransform[Pi, {0.5, 0}]],
GeometricTransformation[KochCurve[5], RotationTransform[-Pi/3, {1, 0}]],
GeometricTransformation[KochCurve[5], RotationTransform[Pi/3, {0, 0}]]}]</langsyntaxhighlight>
 
=={{header|Maxima}}==
Using [https://riotorto.users.sourceforge.net/Maxima/gnuplot/turtle/turtle.mac turtle.mac] package for turtle graphics in Maxima.
<syntaxhighlight lang="maxima">
set_draw_defaults(
terminal = svg,
dimensions = [350,350],
proportional_axes = xy) $
 
wxdraw2d(
turtle(
to(koch_snowflake, [n, len],
ifelse(n = 0,
[forward(len)],
[koch_snowflake(n - 1, len),
right(60),
koch_snowflake(n - 1, len),
left(120),
koch_snowflake(n - 1, len),
right(60),
koch_snowflake(n - 1, len)]
)
),
repeat(6,
koch_snowflake(5, 300),
right(60)
)
)
);
</syntaxhighlight>
[[File:KochSnowflake.png|thumb|center]]
 
=={{header|Nim}}==
{{works with|nim|1.4.2}}
{{libheader|nim-libgd}}
<langsyntaxhighlight lang="nim">
from math import sin, cos, PI
import libgd
Line 1,645 ⟶ 2,164:
 
main()
</syntaxhighlight>
</lang>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use SVG;
use List::Util qw(max min);
 
Line 1,684 ⟶ 2,203:
open $fh, '>', 'koch_curve.svg';
print $fh $svg->xmlify(-namespace=>'svg');
close $fh;</langsyntaxhighlight>
[https://github.com/SqrtNegInf/Rosettacode-Perl5-Smoke/blob/master/ref/koch_curve.svg Koch curve] (offsite image)
 
Line 1,691 ⟶ 2,210:
{{libheader|Phix/online}}
You can run this online [http://phix.x10.mx/p2js/koch.htm here].
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\Koch_curve.exw
Line 1,769 ⟶ 2,288:
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</langsyntaxhighlight>-->
 
=={{header|Processing}}==
<langsyntaxhighlight lang="java">int l = 300;
 
void setup() {
Line 1,816 ⟶ 2,335:
kcurve(0, s);
popMatrix();
}</langsyntaxhighlight>'''The sketch can be run online''' :<BR> [https://www.openprocessing.org/sketch/848209 here.]
 
==={{header|Processing Python mode}}===
<langsyntaxhighlight lang="python">l = 300
 
def setup():
Line 1,861 ⟶ 2,380:
rotate(radians(-120))
kcurve(0, s)
popMatrix()</langsyntaxhighlight>
 
=={{header|Prolog}}==
{{works with|SWI Prolog}}
Produces an SVG file showing a Koch snowflake.
<langsyntaxhighlight lang="prolog">main:-
write_koch_snowflake('koch_snowflake.svg').
 
Line 1,910 ⟶ 2,429:
koch_curve(Stream, X2, Y2, X3, Y3, N1),
koch_curve(Stream, X3, Y3, X4, Y4, N1),
koch_curve(Stream, X4, Y4, X1, Y1, N1).</langsyntaxhighlight>
 
{{out}}
[[Media:Koch_snowflake_prolog.svg]]
See: [https://slack-files.com/T0CNUL56D-F0173G7T8CR-80ae9200ba koch_snowflake.svg] (offsite SVG image)
 
=={{header|Python}}==
Line 1,920 ⟶ 2,439:
 
{{Trans|Haskell}}
<langsyntaxhighlight lang="python">'''Koch curve'''
 
from math import cos, pi, sin
Line 2,056 ⟶ 2,575:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
 
===String rewriting===
<langsyntaxhighlight lang="python">import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import hsv_to_rgb as hsv
Line 2,090 ⟶ 2,609:
#curve('F', {'F': 'G-F-G', 'G': 'F+G+F'}, 60, 7)
#curve('A', {'A': '+BF-AFA-FB+', 'B': '-AF+BFB+FA-'}, 90, 6)
#curve('FX+FX+', {'X': 'X+YF', 'Y': 'FX-Y'}, 90, 12)</langsyntaxhighlight>
 
=={{header|QBasic}}==
<langsyntaxhighlight lang="qbasic"> ' Chaos: start at any point, this program uses the middle of the screen (or universe. One of six
' degrees of freedom (a direction) is chosen at random (by throwing a six-sided die), and a line
' is drawn from the old point to the new point in the direction indicated by the pip on the die.
Line 2,311 ⟶ 2,830:
Y= Y + YP(N, R)
LINE -(X, Y) ' depending on the "die", draw the next part of the chaos curve.
GOTO 900 ' now, go and do another point.</langsyntaxhighlight><br><br>
 
=={{header|Quackery}}==
Line 2,317 ⟶ 2,836:
Using an L-system.
 
<langsyntaxhighlight Quackerylang="quackery"> [ $ "turtleduck.qky" loadfile ] now!
[ $ "" swap witheach
Line 2,333 ⟶ 2,852:
turtle
20 frames
witheach
[ dup char F = iff
Line 2,338 ⟶ 2,858:
char L = iff
[ -1 6 turn ] done
1 6 turn ]</lang>
1 frames</syntaxhighlight>
 
{{output}}
 
[[File:Quackery Koch curve.png]]
https://imgur.com/pOeCUVH
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">#lang racket
 
(require metapict)
Line 2,371 ⟶ 2,892:
(koch a c n)))
 
(scale 4 (snow 2))</langsyntaxhighlight>
 
=={{header|Raku}}==
Line 2,377 ⟶ 2,898:
{{works with|Rakudo|2018.03}}
Koch curve, actually a full Koch snowflake.
<syntaxhighlight lang="raku" perl6line>use SVG;
 
role Lindenmayer {
Line 2,407 ⟶ 2,928:
:polyline[ points => @points.join(','), :fill<white> ],
],
);</langsyntaxhighlight>
 
See: [https://github.com/thundergnat/rc/blob/master/img/koch1.svg Koch snowflake]
 
Variation using 90° angles:
<syntaxhighlight lang="raku" perl6line>use SVG;
 
role Lindenmayer {
Line 2,441 ⟶ 2,962:
:polyline[ points => @points.join(','), :fill<white> ],
],
);</langsyntaxhighlight>
See: [https://github.com/thundergnat/rc/blob/master/img/koch2.svg Koch curve variant with 90° angles]
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Koch curve
 
Line 2,513 ⟶ 3,034:
paint.drawline(x4, y4, x2, y2)
ok
</syntaxhighlight>
</lang>
Output image:
 
Line 2,522 ⟶ 3,043:
{{libheader|JRubyArt}}
Using a Lindenmayer System to produce a KochSnowflake or simple Koch Fractal
<langsyntaxhighlight lang="ruby">
attr_reader :koch
def settings
Line 2,618 ⟶ 3,139:
end
 
</syntaxhighlight>
</lang>
 
=={{header|Rust}}==
Output is a file in SVG format depicting a Koch snowflake.
<langsyntaxhighlight lang="rust">// [dependencies]
// svg = "0.8.0"
 
Line 2,686 ⟶ 3,207:
fn main() {
write_koch_snowflake("koch_snowflake.svg", 600, 5).unwrap();
}</langsyntaxhighlight>
 
{{out}}
[[Media:Koch_snowflake_rust.svg]]
See: [https://slack-files.com/T0CNUL56D-F016A5RCWPR-5e7c5a723a koch_snowflake.svg] (offsite SVG image)
 
=={{header|Sidef}}==
Using the LSystem class defined at [https://rosettacode.org/wiki/Hilbert_curve#Sidef Hilbert curve].
<langsyntaxhighlight lang="ruby">var rules = Hash(
F => 'F+F--F+F',
)
Line 2,709 ⟶ 3,230:
)
 
lsys.execute('F--F--F', 4, "koch_snowflake.png", rules)</langsyntaxhighlight>
 
Output image: [https://github.com/trizen/rc/blob/master/img/koch-snowflake-sidef.png Koch snowflake]
 
=={{header|VBScript}}==
VBScript does'nt have access to the OS graphics, so the code generates SVG code in an HTML file then opens it in the default browser
A Turtle graphics library makes defining the curve easy.
 
<syntaxhighlight lang="vb">
 
option explicit
'outputs turtle graphics to svg file and opens it
 
const pi180= 0.01745329251994329576923690768489 ' pi/180
const pi=3.1415926535897932384626433832795 'pi
class turtle
dim fso
dim fn
dim svg
dim iang 'radians
dim ori 'radians
dim incr
dim pdown
dim clr
dim x
dim y
 
public property let orient(n):ori = n*pi180 :end property
public property let iangle(n):iang= n*pi180 :end property
public sub pd() : pdown=true: end sub
public sub pu() :pdown=FALSE :end sub
public sub rt(i)
ori=ori - i*iang:
if ori<0 then ori = ori+pi*2
end sub
public sub lt(i):
ori=(ori + i*iang)
if ori>(pi*2) then ori=ori-pi*2
end sub
public sub bw(l)
x= x+ cos(ori+pi)*l*incr
y= y+ sin(ori+pi)*l*incr
end sub
public sub fw(l)
dim x1,y1
x1=x + cos(ori)*l*incr
y1=y + sin(ori)*l*incr
if pdown then line x,y,x1,y1
x=x1:y=y1
end sub
Private Sub Class_Initialize()
setlocale "us"
initsvg
pdown=true
end sub
Private Sub Class_Terminate()
disply
end sub
private sub line (x,y,x1,y1)
svg.WriteLine "<line x1=""" & x & """ y1= """& y & """ x2=""" & x1& """ y2=""" & y1 & """/>"
end sub
 
private sub disply()
dim shell
svg.WriteLine "</svg></body></html>"
svg.close
Set shell = CreateObject("Shell.Application")
shell.ShellExecute fn,1,False
end sub
 
private sub initsvg()
dim scriptpath
Set fso = CreateObject ("Scripting.Filesystemobject")
ScriptPath= Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, "\"))
fn=Scriptpath & "SIERP.HTML"
Set svg = fso.CreateTextFile(fn,True)
if SVG IS nothing then wscript.echo "Can't create svg file" :vscript.quit
svg.WriteLine "<!DOCTYPE html>" &vbcrlf & "<html>" &vbcrlf & "<head>"
svg.writeline "<style>" & vbcrlf & "line {stroke:rgb(255,0,0);stroke-width:.5}" &vbcrlf &"</style>"
svg.writeline "</head>"&vbcrlf & "<body>"
svg.WriteLine "<svg xmlns=""http://www.w3.org/2000/svg"" width=""800"" height=""800"" viewBox=""0 0 800 800"">"
end sub
end class
 
sub koch (n,le)
if n=0 then x.fw le :exit sub
koch n-1, le/3
x.lt 1
koch n-1, le/3
x.rt 2
koch n-1, le/3
x.lt 1
koch n-1, le/3
end sub
 
dim x,i
set x=new turtle
x.iangle=60
x.orient=0
x.incr=3
x.x=100:x.y=300
for i=0 to 3
koch 7,100
x.rt 2
next
set x=nothing 'show image in browser
 
</syntaxhighlight>
 
=={{header|Wren}}==
{{trans|Go}}
{{libheader|DOME}}
<langsyntaxhighlight ecmascriptlang="wren">import "graphics" for Canvas, Color, Point
import "dome" for Window
import "math" for M
Line 2,755 ⟶ 3,389:
 
static draw(dt) {}
}</langsyntaxhighlight>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">real PosX, PosY, Angle;
 
proc DrawSide(Depth, Dist); \Draw side as 4 segments
Line 2,784 ⟶ 3,418:
Angle:= Angle + 120.;
];
]</langsyntaxhighlight>
 
{{out}}
Line 2,795 ⟶ 3,429:
Uses Image Magick and
the PPM class from http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm#zkl
<langsyntaxhighlight lang="zkl">var width=512, height=512, img=PPM(width,height,0xFfffFF); // white canvas
var angle=(60.0).toRad();
const green=0x00FF00;
Line 2,822 ⟶ 3,456:
 
koch(100.0,100.0, 400.0,400.0, 4);
img.writeJPGFile("koch.zkl.jpg");</langsyntaxhighlight>
Image at [http://www.zenkinetic.com/Images/RosettaCode/koch.zkl.jpg koch curve]
 
Line 2,828 ⟶ 3,462:
Using a Lindenmayer system and turtle graphics to draw a Koch snowflake:
 
<langsyntaxhighlight lang="zkl">lsystem("F--F--F", Dictionary("F","F+F--F+F"), "+-", 4) // snowflake
//lsystem("F", Dictionary("F","F+F--F+F"), "+-", 3) // curve
: turtle(_);
Line 2,858 ⟶ 3,492:
}
img.writeJPGFile("kochSnowFlake.zkl.jpg");
}</langsyntaxhighlight>
Image at [http://www.zenkinetic.com/Images/RosettaCode/kochSnowFlake.zkl.jpg Koch snow flake]
3,028

edits