Hilbert curve: Difference between revisions

→‎{{header|Fōrmulæ}}: Added L-system solution
(add bqn)
(→‎{{header|Fōrmulæ}}: Added L-system solution)
(29 intermediate revisions by 14 users not shown)
Line 8:
{{trans|D}}
 
<langsyntaxhighlight lang="11l">T Point
x = 0
y = 0
Line 83:
L(line) lines
print(line)
print()</langsyntaxhighlight>
 
{{out}}
Line 139:
=={{header|Action!}}==
Action! language does not support recursion. Therefore an iterative approach with a stack has been proposed.
<langsyntaxhighlight Actionlang="action!">DEFINE MAXSIZE="12"
 
INT ARRAY
Line 221:
DO UNTIL CH#$FF OD
CH=$FF
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Hilbert_curve.png Screenshot from Atari 8-bit computer]
Line 227:
=={{header|Ada}}==
{{libheader|APDF}}
<langsyntaxhighlight Adalang="ada">with PDF_Out; use PDF_Out;
 
procedure Hilbert_Curve_PDF is
Line 301:
 
PDF.Close;
end Hilbert_Curve_PDF;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 312:
|}
 
<langsyntaxhighlight lang="algol68">BEGIN
INT level = 4; # <-- change this #
 
Line 368:
OD
END
</syntaxhighlight>
</lang>
{{out}}
<pre> ╭───╮ ╭───╮ ╭───╮ ╭───╮ ╭───╮ ╭───╮ ╭───╮ ╭───╮
Line 406:
{{trans|Go}}
Requires [https://www.autohotkey.com/boards/viewtopic.php?t=6517 Gdip Library]
<langsyntaxhighlight AutoHotkeylang="autohotkey">gdip1()
HilbertX := A_ScreenWidth/2 - 100, HilbertY := A_ScreenHeight/2 - 100
Hilbert(HilbertX, HilbertY, 2**5, 5, 5, Arr:=[])
Line 471:
Gdip_Shutdown(pToken)
ExitApp
Return</langsyntaxhighlight>
 
=={{header|Binary Lambda Calculus}}==
 
As shown in https://www.ioccc.org/2012/tromp/hint.html, the 142+3 byte BLC program
 
<pre>0000000 18 18 18 18 11 11 54 68 06 04 15 5f f0 41 9d f9
0000020 de 16 ff fe 5f 3f ef f6 15 ff 94 68 40 58 11 7e
0000040 05 cb fe bc bf ee 86 cb 94 68 16 00 5c 0b fa cb
0000060 fb f7 1a 85 e0 5c f4 14 d5 fe 08 18 0b 04 8d 08
0000100 00 e0 78 01 64 45 ff e5 ff 7f ff fe 5f ff 2f c0
0000120 ee d9 7f 5b ff ff fb ff fc aa ff f7 81 7f fa df
0000140 76 69 54 68 06 01 57 f7 e1 60 5c 13 fe 80 b2 2c
0000160 18 58 1b fe 5c 10 42 ff 80 5d ee c0 6c 2c 0c 06
0000200 08 19 1a 00 16 7f bc bc fd f6 5f 7c 0a 20 31 32
0000220 33</pre>
 
(consisting of the 142 byte binary prefix https://github.com/tromp/AIT/blob/master/hilbert followed by "123") outputs the 3rd order Hilbert curve
 
<pre> _ _ _ _
| |_| | | |_| |
|_ _| |_ _|
_| |_____| |_
| ___ ___ |
|_| _| |_ |_|
_ |_ _| _
| |___| |___| |</pre>
 
=={{header|BQN}}==
{{trans|J}}
BQN does not have complex numbers as of the creation of this submission, so <code>Conj</langcode> and <code>CMul</langcode> implement complex number operations on two element arrays, for clarity's sake.
 
<langsyntaxhighlight lang="bqn">Conj←1‿¯1⊸×
Cmul←-´∘×⋈+´∘×⟜⌽
Iter←(⊢∾⟨1‿0⟩∾Conj¨∘⌽)∘(0‿¯1⊸CMul¨∘⌽∾⟨0‿¯1⟩∾⊢)
Plot←{•Plot´<˘⍉>+`⟨0‿0⟩∾Iter⍟𝕩 ⟨⟩}</langsyntaxhighlight>
 
This program is made for <code>•Plot</code> in the online implementation, and you can view the result in the [online REPL.](https://mlochbaum.github.io/BQN/try.html#code=Q29uauKGkDHigL/CrzHiirjDlwpDbXVs4oaQLcK04oiYw5fii4grwrTiiJjDl+KfnOKMvQpJdGVy4oaQKOKKouKIvuKfqDHigL8w4p+p4oi+Q29uasKo4oiY4oy9KeKImCgw4oC/wq8x4oq4Q011bMKo4oiY4oy94oi+4p+oMOKAv8KvMeKfqeKIvuKKoikKSGlsYmVydOKGkHvigKJQbG90wrQ8y5jijYk+K2Din6gw4oC/MOKfqeKIvkl0ZXLijZ/wnZWpIOKfqOKfqX0KIApIaWxiZXJ0IDU=) Online REPL.]
 
=={{header|C}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="c">#include <stdio.h>
 
#define N 32
Line 556 ⟶ 582:
}
return 0;
}</langsyntaxhighlight>
{{output}}
<pre>Same as Kotlin entry.</pre>
Line 562 ⟶ 588:
=={{header|C sharp|C#}}==
{{trans|Visual Basic .NET}}
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Diagnostics;
Line 678 ⟶ 704:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>Hilbert curve, order=1
Line 754 ⟶ 780:
=={{header|C++}}==
{{trans|D}}
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
#include <vector>
Line 843 ⟶ 869:
}
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>Hilbert curve, order=1
Line 919 ⟶ 945:
=={{header|D}}==
{{trans|Java}}
<langsyntaxhighlight lang="d">import std.stdio;
 
void main() {
Line 1,033 ⟶ 1,059:
 
return lines;
}</langsyntaxhighlight>
{{out}}
<pre>Hilbert curve, order=1
Line 1,106 ⟶ 1,132:
| __ | | __ | | __ | | __ | | __ | | __ | | __ | | __ |
|__| |__| |__| |__| |__| |__| |__| |__| |__| |__| |__| |__| |__| |__| |__| |__|</pre>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
This is a very fancy version of the Hilbert curve. It allows you to draw multiple levels and you have the option of superimposing each level on top of the others. You can choose four different pen colors that alternate according to the level. The pen thickness can vary according to the level and can be increments or decremented according to the settings.
 
<syntaxhighlight lang="Delphi">
 
procedure ClearBackground(Image: TImage; Color: TColor);
{Clear image with specified color}
begin
Image.Canvas.Brush.Color:=Color;
Image.Canvas.Pen.Color:=Color;
Image.Canvas.Rectangle(Image.ClientRect);
end;
 
{Array of colors used in display}
 
type TColorArray = array of TColor;
 
{Option controls the size of lines for each level}
 
type TPenMode = (pmNormal,pmIncrement,pmDecrement);
 
{Combined structure controls the Hilbert display}
 
type TCurveOptions = record
Order: integer;
SuperImposed: boolean;
PenMode: TPenMode;
ColorArray: TColorArray;
end;
 
 
procedure DrawHillbertCurve(Canvas: TCanvas; Width,Height: integer; Options: TCurveOptions);
{ Hilbert Curve}
var X,Y,X0,Y0,H,H0,StartX,StartY: double;
var I,Inx: integer;
 
procedure LeftUpRight(I: integer); forward;
procedure DownRightUp(I: integer); forward;
procedure RightDownLeft(I: integer); forward;
procedure UpLeftDown(I: integer); forward;
 
 
procedure DrawRealLine(var X,Y: double);
begin
Canvas.LineTo(Trunc(X),Trunc(Y));
end;
 
procedure LeftUpRight(I: integer);
begin
if I>0 then
begin
UpLeftDown(I-1);
X:=X-H;
DrawRealLine(X,Y);
LeftUpRight(I-1);
Y:=Y-H;
DrawRealLine(X,Y);
LeftUpRight(I-1);
X:=X+H;
DrawRealLine(X,Y);
DownRightUp(I-1);
end;
end;
 
procedure DownRightUp(I: integer);
begin
if I>0 then
begin
RightDownLeft(I-1);
Y:=Y+H;
DrawRealLine(X,Y);
DownRightUp(I-1);
X:=X+H;
DrawRealLine(X,Y);
DownRightUp(I-1);
Y:=Y-H;
DrawRealLine(X,Y);
LeftUpRight(I-1);
end;
end;
 
procedure RightDownLeft(I: integer);
begin
if I>0 then
begin
DownRightUp(I-1);
X:=X+H;
DrawRealLine(X,Y);
RightDownLeft(I-1);
Y:=Y+H;
DrawRealLine(X,Y);
RightDownLeft(I-1);
X:=X-H;
DrawRealLine(X,Y);
UpLeftDown(I-1);
end;
end;
 
procedure UpLeftDown(I: integer);
begin
if I>0 then
begin
LeftUpRight(I-1);
Y:=Y-H;
DrawRealLine(X,Y);
UpLeftDown(I-1);
X:=X-H;
DrawRealLine(X,Y);
UpLeftDown(I-1);
Y:=Y+H;
DrawRealLine(X,Y);
RightDownLeft(I-1);
end;
end;
 
begin
if Height<Width then H0:=Height else H0:=Width;
STARTX:=Width div 2;
STARTY:=Height div 2;
H:=H0;
X0:=STARTX;
Y0:=STARTY;
 
for I:=1 to Options.Order do
begin
case Options.PenMode of
pmDecrement: Canvas.Pen.Width:=(Options.Order - I) + 1;
pmIncrement: Canvas.Pen.Width:=I;
end;
Inx:=(I-1) mod Length(Options.ColorArray);
Canvas.Pen.Color:=Options.ColorArray[Inx];
H:=H / 2;
X0:=X0+(H / 2);
Y0:=Y0+(H / 2);
X:=X0;
Y:=Y0;
if not Options.SuperImposed and (Options.Order<>I) then continue;
Canvas.MoveTo(Trunc(X),Trunc(Y));
 
{ Draw Curve Of Order I }
LeftUpRight(I);
end;
end;
 
procedure ShowHilbertCurve(Image: TImage);
{Setup parameter and draw Hilbert curve on canvas}
var CA: TColorArray;
var Options: TCurveOptions;
begin
ClearBackground(Image,clWhite);
Image.Canvas.Pen.Width:=1;
SetLength(CA,4);
CA[0]:=clBlack;
CA[1]:=clGray;
CA[2]:=clSilver;
CA[3]:=clGray;
Options.Order:=5;
Options.SuperImposed:=True;
Options.PenMode:=pmNormal;
Options.ColorArray:=CA;
 
DrawHillbertCurve(Image.Canvas,Image.Width,Image.Height,Options);
end;
 
 
</syntaxhighlight>
{{out}}
[[File:DelphiHilbertCurve.png|thumb|none]]
<pre>
 
</pre>
 
=={{header|EasyLang}}==
 
{{trans|FutureBasic}}
 
[https://easylang.dev/show/#cod=jVBLDoIwEN33FG9JMSCtxp2HUajSpAFTUeH2zlAKRDa2TTPz5n2atr4yHmecjsLZxnxs1dU4aOzR8kQ8y4szNFdFETFkU5eENg2wFA/flqituxrfoccAd4dVsBo5cgHA3hgiM25ocWJ0ydBLsgp5MzbM2CTxpnv5hpvRcbSjq7JvaAaW+B1npzwcVnV4kiJru+XrhZ8EilyrtorAUvJXp/7S6ZUuZtMJDqzKRRQVtMOfUCW+ Run it]
 
<syntaxhighlight lang="easylang">
order = 64
linewidth 32 / order
scale = 100 / order - 100 / (order * order)
proc hilbert x y lg i1 i2 . .
if lg = 1
line (order - x) * scale (order - y) * scale
return
.
lg = lg div 2
hilbert x + i1 * lg y + i1 * lg lg i1 1 - i2
hilbert x + i2 * lg y + (1 - i2) * lg lg i1 i2
hilbert x + (1 - i1) * lg y + (1 - i1) * lg lg i1 i2
hilbert x + (1 - i2) * lg y + i2 * lg lg 1 - i1 i2
.
hilbert 0 0 order 0 0
</syntaxhighlight>
 
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">
// Hilbert curve. Nigel Galloway: September 18th., 2023
type C= |At|Cl|Ab|Cr
type D= |Z|U|D|L|R
let fD=function Z->0,0 |U->0,1 |D->0,-1 |L-> -1,0 |R->1,0
let fC=function At->[fD D;fD R;fD U] |Cl->[fD R;fD D;fD L] |Ab->[fD U;fD L;fD D] |Cr->[fD L;fD U;fD R]
let order(n,g)=match g with At->[n,Cl;D,At;R,At;U,Cr]
|Cl->[n,At;R,Cl;D,Cl;L,Ab]
|Ab->[n,Cr;U,Ab;L,Ab;D,Cl]
|Cr->[n,Ab;L,Cr;U,Cr;R,At]
let hilbert=Seq.unfold(fun n->Some(n,n|>List.collect order))[Z,At]
hilbert|>Seq.take 7|>Seq.iteri(fun n g->Chart.Line(g|>Seq.collect(fun(n,g)->(fD n)::(fC g))|>Seq.scan(fun(x,y)(n,g)->(x+n,y+g))(0,0))|>Chart.withTitle(sprintf "Hilbert order %d" n)|>Chart.show)
</syntaxhighlight>
{{out}}
[[File:Hilbert0.png]]
[[File:Hilbert1.png]]
[[File:Hilbert2.png]]
[[File:Hilbert3.png]]
[[File:Hilbert4.png]]
[[File:Hilbert5.png]]
[[File:Hilbert6.png]]
 
=={{header|Factor}}==
{{works with|Factor|0.99 2020-08-14}}
<langsyntaxhighlight lang="factor">USING: accessors L-system ui ;
 
: hilbert ( L-system -- L-system )
Line 1,120 ⟶ 1,367:
} >>rules ;
 
[ <L-system> hilbert "Hilbert curve" open-window ] with-ui</langsyntaxhighlight>
 
 
Line 1,155 ⟶ 1,402:
=={{header|Forth}}==
{{trans|Yabasic}}
{{works with|4tH |v3.62}}
<langsyntaxhighlight lang="forth">include lib/graphics.4th
 
64 constant /width \ hilbertHilbert curve order^2
9 constant /length \ length of a line
 
Line 1,187 ⟶ 1,434:
color_image 255 whiteout blue \ paint blue on white
0 dup origin! \ set point of origin
0 dup /width over dup hilbert \ hilbertHilbert curve, order=8
s" ghilbert.ppm" save_image \ save the image
</syntaxhighlight>
</lang>
Output:
''Since Rosetta Code doesn't seem to support uploads anymore, the resulting file cannot be shown.''
Line 1,195 ⟶ 1,442:
=={{header|FreeBASIC}}==
{{trans|Yabasic}}
<langsyntaxhighlight lang="freebasic">
Dim Shared As Integer ancho = 64
 
Line 1,214 ⟶ 1,461:
Hilbert(0, 0, ancho, 0, 0)
End
</syntaxhighlight>
</lang>
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Hilbert_curve}}
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for storage and transfer purposes more than visualization and edition.
 
'''Solution'''
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.
 
=== Recursive ===
In '''[https://formulae.org/?example=Hilbert_curve this]''' page you can see the program(s) related to this task and their results.
 
The following defines a function that creates a graphics of the Hilbert curve of a given order and size:
 
[[File:Fōrmulæ - Hilbert curve 01.png]]
 
'''Test cases'''
 
The following creates a table with Hilbert curves for orders 1 to 5:
 
[[File:Fōrmulæ - Hilbert curve 02.png]]
 
[[File:Fōrmulæ - Hilbert curve 03.png|279px]]
 
=== 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 Hilbert curve is:
 
[[File:Fōrmulæ - L-system - Hilbert curve 01.png]]
 
[[File:Fōrmulæ - L-system - Hilbert curve 02.png]]
 
=={{header|Frink}}==
This program generates arbitrary L-systems with slight modifications (see the commmented-out list of various angles and rules.)
<langsyntaxhighlight lang="frink">// General description:
// This code creates Lindenmayer rules via string manipulation
// It can generate many of the examples from the Wikipedia page
Line 1,340 ⟶ 1,609:
g.show[]
g.write["hilbert.png",512,undef]
</syntaxhighlight>
</lang>
 
=={{header|FutureBasic}}==
Hilbert Curve Order 64
<syntaxhighlight lang="futurebasic">
#define ORDER 64
 
_window = 1
 
void local fn BuildWindow
CGRect r = fn CGRectMake( 0, 0, 651, 661 )
window _window, @"Order 64 Hilbert Curve In FutureBasic", r, NSWindowStyleMaskTitled
WindowSetBackgroundColor( _window, fn ColorBlack )
end fn
 
void local fn HilbertCurve( x as long, y as long, lg as long, i1 as long, i2 as long )
if ( lg == 1 )
line to ( ORDER-x ) * 10, ( ORDER-y ) * 10
exit fn
end if
lg = lg / 2
fn HilbertCurve( x+i1*lg, y+i1*lg, lg, i1, 1-i2 )
pen 2.0
fn HilbertCurve( x+i2*lg, y+(1-i2)*lg, lg, i1, i2 )
fn HilbertCurve( x+(1-i1)*lg, y+(1-i1)*lg, lg, i1, i2 )
fn HilbertCurve( x+(1-i2)*lg, y+i2*lg, lg, 1-i1, i2 )
end fn
 
fn BuildWindow
pen -2.0, fn ColorGreen
fn HilbertCurve( 0, 0, ORDER, 0, 0 )
 
HandleEvents
</syntaxhighlight>
{{output}}
[[File:Hilbert_Curve_FutureBasic.png]]
 
=={{header|Go}}==
Line 1,347 ⟶ 1,650:
<br>
The following is based on the recursive algorithm and C code in [https://www.researchgate.net/profile/Christoph_Schierz2/publication/228982573_A_recursive_algorithm_for_the_generation_of_space-filling_curves/links/0912f505c2f419782c000000/A-recursive-algorithm-for-the-generation-of-space-filling-curves.pdf this paper]. The image produced is similar to the one linked to in the zkl example.
<langsyntaxhighlight lang="go">package main
 
import "github.com/fogleman/gg"
Line 1,381 ⟶ 1,684:
dc.Stroke()
dc.SavePNG("hilbert.png")
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
Line 1,391 ⟶ 1,694:
and folded to a list of points in a square of given size.
 
<langsyntaxhighlight lang="haskell">import Data.BoolTree (boolTree (..))
 
import Data.Tree
---------------------- HILBERT CURVE ---------------------
 
hilbertTree :: Int -> Tree Char
hilbertTree n
| 0 < n = iterate go seed !! pred n
| otherwise = seed
where
seed = Node 'a' []
go tree
| null xs = Node c (flip Node [] <$> rule c)
| otherwise = Node c (go <$> xs)
where
c = rootLabel tree
xs = subForest tree
 
 
hilbertPoints :: Int -> Tree Char -> [(Int, Int)]
hilbertPoints w = go r (r, r)
where
r = quot w 2
go r xy tree
| null xs = centres
| otherwise = concat $ zipWith (go d) centres xs
where
d = quot r 2
f g x = g xy + (d * g x)
centres =
((,) . f fst)
<*> f snd <$> vectors (rootLabel tree)
xs = subForest tree
 
 
--------------------- PRODUCTION RULE --------------------
 
rule :: Char -> String
Line 1,411 ⟶ 1,747:
'd' -> [(-1, 1), (1, 1), (1, -1), (-1, -1)]
_ -> []
 
 
--------------------------- TEST -------------------------
 
main :: IO ()
Line 1,416 ⟶ 1,755:
let w = 1024
putStrLn $ svgFromPoints w $ hilbertPoints w (hilbertTree 6)
 
hilbertTree :: Int -> Tree Char
hilbertTree n =
let go tree =
let c = rootLabel tree
xs = subForest tree
in Node c (bool (go <$> xs) (flip Node [] <$> rule c) (null xs))
seed = Node 'a' []
in bool seed (iterate go seed !! pred n) (0 < n)
 
hilbertPoints :: Int -> Tree Char -> [(Int, Int)]
hilbertPoints w tree =
let go r xy tree =
let d = quot r 2
f g x = g xy + (d * g x)
centres = ((,) . f fst) <*> f snd <$> vectors (rootLabel tree)
xs = subForest tree
in bool (concat $ zipWith (go d) centres xs) centres (null xs)
r = quot w 2
in go r (r, r) tree
 
svgFromPoints :: Int -> [(Int, Int)] -> String
Line 1,441 ⟶ 1,760:
let sw = show w
points =
(unwords . fmap (((++<>) . show . fst) <*> ((' ' :) . show . snd))) xys
in unlines
[ "<svg xmlns=\"http://www.w3.org/2000/svg\"",
unwords
, unwords ["width=\"512\" height=\"512\" viewBox=\"5 5", sw, sw, "\"> "]
, ["width=\"512\"<path dheight=\"M512\" ++viewBox=\"5 points5", ++sw, sw, "\"> "],
, "stroke-width<path d=\"2\M" stroke=\++ points ++ "red\" fill=\"transparent\"/>",
"stroke-width=\"2\" stroke=\"red\" fill=\"transparent\"/>",
, "</svg>"
] "</langsvg>"
]</syntaxhighlight>
 
=={{header|IS-BASIC}}==
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "Hilbert.bas"
110 OPTION ANGLE DEGREES
120 GRAPHICS HIRES 2
Line 1,468 ⟶ 1,788:
250 CALL HILBERT(S,N-1,-P)
260 PLOT LEFT 90*P;
270 END DEF</langsyntaxhighlight>
 
=={{header|J}}==
Line 1,474 ⟶ 1,794:
Note: J's {{ }} syntax requires a recent version of J (9.02 or more recent).
 
<langsyntaxhighlight Jlang="j">iter=: (, 1 , +@|.) @: (,~ 0j_1 ,~ 0j_1*|.)
hilbert=: {{0j1+(%{:) +/\0,iter ^: y ''}}
</syntaxhighlight>
</lang>
 
For a graphical presentation, you could use (for example):
 
<langsyntaxhighlight Jlang="j">require'plot'
plot hilbert 5</langsyntaxhighlight>
 
For asciiart, you could instead use:
 
<syntaxhighlight lang="j">
<lang J>
asciiart=:{{
coords=. 1 3*"1 +. y % <./(,+.y)-.0
Line 1,513 ⟶ 1,833:
|__ |__| | |__| | |__| __| |__ |__|
__| __ |__ __| __ |__ __| __
|__ __| |__ __| |__ __| |__ __| |__ __| | </langsyntaxhighlight>
 
The idea is to represent the nth order hilbert curve as list of complex numbers that can be summed to trace the curve. The 0th order hilbert curve is an empty list. The first half of the n+1 the curve is formed by rotating the nth right by 90 degrees and reversing, appending -i and appending the nth curve. The whole n+1th curve is the first half appended to 1 appended to the conjugate of the reverse of the first half.
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">// Translation from https://en.wikipedia.org/wiki/Hilbert_curve
 
import java.util.ArrayList;
Line 1,650 ⟶ 1,970:
return;
}
}</langsyntaxhighlight>
{{out}}
<pre>Hilbert curve, order=1
Line 1,729 ⟶ 2,049:
 
An implementation of GO. Prints an SVG string that can be read in a browser.
<langsyntaxhighlight lang="javascript">const hilbert = (width, spacing, points) => (x, y, lg, i1, i2, f) => {
if (lg === 1) {
const px = (width - x) * spacing;
Line 1,782 ⟶ 2,102:
};
 
drawHilbert(6);</langsyntaxhighlight>
 
===Functional===
Line 1,793 ⟶ 2,113:
Like the version above, generates an SVG string for display in a browser.
 
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
"use strict";
 
Line 1,799 ⟶ 2,119:
 
// hilbertCurve :: Dict Char [(Int, Int)] ->
// Dict Char [Char] -> Int -> Int -> SVG string
const hilbertCurve = dictVector =>
dictRule => nwidth => {compose(
const w = 1024;svgFromPoints(width),
hilbertPoints(dictVector)(width),
 
return svgFromPointshilbertTree(wdictRule)(
);
hilbertPoints(dictVector)(w)(
hilbertTree(dictRule)(n)
)
);
};
 
 
// hilbertTree :: Dict Char [Char] -> Int -> Tree Char
const hilbertTree = rule => n => {
const go = treen => {
const xsgo = tree.nest; => {
const xs = tree.nest;
 
return Node(tree.root)(
Boolean( 0 < xs.length) ? (
? xs.map(go)
) : rule[tree.root].map(
flip(Node)([])
)
);
};
const seed = Node("a")([]);
 
return 0 < n
? take(n)(
iterate(go)(seed)
)
.slice(-1);[0]
: seed;
};
const seed = Node("a")([]);
 
return Boolean(n) ? (
take(n)(iterate(go)(seed))
.slice(-1)[0]
) : seed;
};
 
 
Line 1,847 ⟶ 2,166:
]);
 
return Boolean(0 < t.nest.length) ? (
? zipWith(go(r))(centres)(t.nest)
.flat go(r)
) : )(centres;)(t.nest).flat()
: centres;
};
const d = Math.floor(w / 2);
Line 1,901 ⟶ 2,221:
c: ["b", "c", "c", "d"],
d: ["a", "d", "d", "c"]
})(1024)(6);
 
 
Line 1,916 ⟶ 2,236:
nest: xs || []
});
 
 
// compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
const compose = (...fs) =>
// A function defined by the right-to-left
// composition of all the functions in fs.
fs.reduce(
(f, g) => x => f(g(x)),
x => x
);
 
 
// flip :: (a -> b -> c) -> b -> a -> c
const flip = op =>
// The binary function op with
// its arguments reversed.
1 !== op.length ? (
? (a, b) => op(b, a)
) : (a => b => op(b)(a));
 
 
Line 1,949 ⟶ 2,279:
"GeneratorFunction" !== xs.constructor
.constructor.name ? (
xs.length
) : Infinity;
 
 
Line 1,960 ⟶ 2,290:
xs => "GeneratorFunction" !== xs
.constructor.constructor.name ? (
xs.slice(0, n)
) : Array.from({
length: n
}, () => {
const x = xs.next();
 
return x.done ? [] : [x.value];
}).flat();
 
 
Line 1,982 ⟶ 2,312:
}, (_, i) => f(as[i], bs[i]));
};
 
 
// MAIN ---
return main();
})();</langsyntaxhighlight>
 
=={{header|jq}}==
Line 1,997 ⟶ 2,328:
for the simple-turtle.jq module used in this entry. The `include`
statement assumes the file is in the pwd.
<langsyntaxhighlight lang="jq">include "simple-turtle" {search: "."};
 
def rules:
Line 2,027 ⟶ 2,358:
hilbert_curve(5)
| path("none"; "red"; 1) | svg(170)
</syntaxhighlight>
</lang>
{{out}}
https://imgur.com/a/mJAaY6I
Line 2,033 ⟶ 2,364:
=={{header|Julia}}==
Color graphics version using the Gtk package.
<langsyntaxhighlight lang="julia">using Gtk, Graphics, Colors
 
Base.isless(p1::Vec2, p2::Vec2) = (p1.x == p2.x ? p1.y < p2.y : p1.x < p2.x)
Line 2,116 ⟶ 2,447:
signal_connect(endit, win, :destroy)
wait(cond)
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
Line 2,122 ⟶ 2,453:
 
The coordinates of the points are generated using a translation of the C code in the Wikipedia article and then scaled by a factor of 3 (n = 32).
<langsyntaxhighlight lang="scala">// Version 1.2.40
 
data class Point(var x: Int, var y: Int)
Line 2,187 ⟶ 2,518:
println()
}
}</langsyntaxhighlight>
 
{{output}}
Line 2,289 ⟶ 2,620:
The output is visible in [http://lambdaway.free.fr/lambdawalks/?view=hilbert Hibert curve]
 
<syntaxhighlight lang="scheme">
<lang Scheme>
1) two twinned recursive functions
 
Line 2,330 ⟶ 2,661:
{path {@ d="M {turtle 10 10 0 {H5}}" {stroke 1 #fff}}}
}
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
Line 2,349 ⟶ 2,680:
* <num> repeat the following draw command <num> times
* <any> move on canvas without drawing
<langsyntaxhighlight lang="lua">-- any version from LuaJIT 2.0/5.1, Lua 5.2, Lua 5.3 to LuaJIT 2.1.0-beta3-readline
local bit=bit32 or bit -- Lua 5.2/5.3 compatibilty
-- Hilbert curve implemented by Lindenmayer system
Line 2,436 ⟶ 2,767:
local str=arg[2] or "A"
draw(str:hilbert(n))
</syntaxhighlight>
</lang>
{{output}} luajit hilbert.lua 4 1M9FAF-4F2+2F-2F-2F++4F-F-4F+2F+2F+2F++3F+2F+3F--4FA10F-16F-58F-16F-
<pre>
Line 2,461 ⟶ 2,792:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
'''Works with:''' Mathematica 11
<syntaxhighlight lang Mathematica="mathematica">Graphics@HilbertCurve[4]</langsyntaxhighlight>
 
=={{header|Nim}}==
{{trans|Algol68}}
<langsyntaxhighlight Nimlang="nim">const
Level = 4
Side = (1 shl Level) * 2 - 2
Line 2,572 ⟶ 2,903:
stdout.write(s)
stdout.writeLine("")
</syntaxhighlight>
</lang>
{{out}}
See Algol68 version.
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use SVG;
use List::Util qw(max min);
 
Line 2,616 ⟶ 2,947:
open $fh, '>', 'hilbert_curve.svg';
print $fh $svg->xmlify(-namespace=>'svg');
close $fh;</langsyntaxhighlight>
[https://github.com/SqrtNegInf/Rosettacode-Perl5-Smoke/blob/master/ref/hilbert_curve.svg Hilbert curve] (offsite image)
 
Line 2,624 ⟶ 2,955:
{{libheader|Phix/online}}
You can run this online [http://phix.x10.mx/p2js/hilbert_curve.htm here].
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\hilbert_curve.exw
Line 2,693 ⟶ 3,024:
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</langsyntaxhighlight>-->
 
=={{header|Processing}}==
 
<langsyntaxhighlight lang="java">int iterations = 7;
float strokeLen = 600;
int angleDeg = 90;
Line 2,779 ⟶ 3,110:
yo += 25;
}
}</langsyntaxhighlight>
 
==={{header|Processing Python mode}}===
 
<langsyntaxhighlight lang="python">iterations = 7
stroke_len = 600
angle_deg = 90
Line 2,845 ⟶ 3,176:
yo -= 50
if keyCode == DOWN:
yo += 50</langsyntaxhighlight>
 
=={{header|Python}}==
Line 2,857 ⟶ 3,188:
 
{{Works with|Python|3.7}}
<langsyntaxhighlight Pythonlang="python">'''Hilbert curve'''
 
from itertools import (chain, islice)
Line 2,999 ⟶ 3,330:
# TEST ---------------------------------------------------
if __name__ == '__main__':
main()</langsyntaxhighlight>
 
===Recursive===
<syntaxhighlight lang="python">
<lang Python>
import matplotlib.pyplot as plt
import numpy as np
Line 3,060 ⟶ 3,391:
tt.goto(tt.pos()[0] + item[0], tt.pos()[1] + item[1])
tt.done()
</syntaxhighlight>
</lang>
 
=={{header|QB64}}==
{{trans|YaBASIC}}
<langsyntaxhighlight lang="qb64">_Title "Hilbert Curve"
Dim Shared As Integer sw, sh, wide, cell
 
Line 3,092 ⟶ 3,423:
Call Hilbert(iX + (1 - p) * iL, iY + (1 - p) * iL, iL, p, q)
Call Hilbert(iX + (1 - q) * iL, iY + q * iL, iL, 1 - p, q)
End Sub</langsyntaxhighlight>
 
=={{header|Quackery}}==
Line 3,098 ⟶ 3,429:
Using an L-system.
 
<langsyntaxhighlight Quackerylang="quackery"> [ $ "turtleduck.qky" loadfile ] now!
[ stack ] is switch.arg ( --> [ )
Line 3,128 ⟶ 3,459:
turtle
10 frames
witheach
[ switch
Line 3,133 ⟶ 3,465:
char L case [ -1 4 turn ]
char R case [ 1 4 turn ]
otherwise ( ignore ) ] ] </lang>
1 frames</syntaxhighlight>
 
{{output}}
 
[[File:Quackery Hilbert curve.png]]
https://imgur.com/pkEAauf
 
=={{header|Racket}}==
Line 3,143 ⟶ 3,476:
{{trans|Perl}}
 
<langsyntaxhighlight lang="racket">#lang racket
(require racket/draw)
Line 3,174 ⟶ 3,507:
target)
(make-curve 500 6 7 30 (make-color 255 255 0) (make-color 0 0 0))</langsyntaxhighlight>
 
=={{header|Raku}}==
Line 3,180 ⟶ 3,513:
{{works with|Rakudo|2018.03}}
 
<syntaxhighlight lang="raku" perl6line>use SVG;
 
role Lindenmayer {
Line 3,208 ⟶ 3,541:
:polyline[ :points(@points.join: ','), :fill<white> ],
],
);</langsyntaxhighlight>
See: [https://github.com/thundergnat/rc/blob/master/img/hilbert-perl6.svg Hilbert curve]
 
There is a variation of a Hilbert curve known as a [[wp:Moore curve|Moore curve]] which is essentially 4 Hilbert curves joined together in a loop.
<syntaxhighlight lang="raku" perl6line>use SVG;
 
role Lindenmayer {
Line 3,240 ⟶ 3,573:
:polyline[ :points(@points.join: ','), :fill<white> ],
],
);</langsyntaxhighlight>
See: [https://github.com/thundergnat/rc/blob/master/img/moore-perl6.svg Moore curve]
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Hilbert curve
 
Line 3,311 ⟶ 3,644:
x1 = x2
y1 = y2
</syntaxhighlight>
</lang>
Output image:
[https://www.dropbox.com/s/anwtxtrnqhubh4a/HilbertCurve.jpg?dl=0 Hilbert curve]
Line 3,320 ⟶ 3,653:
<br/>
Implemented as a Lindenmayer System, depends on JRuby or JRubyComplete
<syntaxhighlight lang="ruby">
<lang Ruby>
# frozen_string_literal: true
 
Line 3,396 ⟶ 3,729:
end
end
</syntaxhighlight>
</lang>
 
The grammar library:-
 
<langsyntaxhighlight lang="ruby">
# common library class for lsystems in JRubyArt
class Grammar
Line 3,423 ⟶ 3,756:
end
end
</syntaxhighlight>
</lang>
 
=={{header|Rust}}==
Output is a file in SVG format. Implemented using a Lindenmayer system as per the Wikipedia page.
<langsyntaxhighlight lang="rust">// [dependencies]
// svg = "0.8.0"
 
Line 3,509 ⟶ 3,842:
fn main() {
HilbertCurve::save("hilbert_curve.svg", 650, 6).unwrap();
}</langsyntaxhighlight>
 
{{out}}
[[Media:Hilbert_curve_rust.svg]]
See: [https://slack-files.com/T0CNUL56D-F016PFXV0SZ-e88b2585b5 hilbert_curve.svg] (offsite SVG image)
 
=={{header|Scala}}==
===[https://www.scala-js.org/ Scala.js]===
<langsyntaxhighlight Scalalang="scala">@js.annotation.JSExportTopLevel("ScalaFiddle")
object ScalaFiddle {
// $FiddleStart
Line 3,563 ⟶ 3,896:
}
// $FiddleEnd
}</langsyntaxhighlight>
{{Out}}Best seen running in your browser by [https://scalafiddle.io/sf/x7t2zdK/0 ScalaFiddle (ES aka JavaScript, non JVM)].
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "draw.s7i";
include "keybd.s7i";
Line 3,649 ⟶ 3,982:
drawRight(x, y, 6);
readln(KEYBOARD);
end func;</langsyntaxhighlight>
 
=={{header|Sidef}}==
Generic implementation of the Lindenmayer system:
<langsyntaxhighlight lang="ruby">require('Image::Magick')
 
class Turtle(
Line 3,760 ⟶ 4,093:
turtle.save_as(filename)
}
}</langsyntaxhighlight>
 
Generating the Hilbert curve:
<langsyntaxhighlight lang="ruby">var rules = Hash(
a => '-bF+aFa+Fb-',
b => '+aF-bFb-Fa+',
Line 3,780 ⟶ 4,113:
)
 
lsys.execute('a', 6, "hilbert_curve.png", rules)</langsyntaxhighlight>
Output image: [https://github.com/trizen/rc/blob/master/img/hilbert-curve-sidef.png Hilbert curve]
 
Line 3,786 ⟶ 4,119:
{{libheader|Gtk+-3.0}}
 
<langsyntaxhighlight lang="vala">struct Point{
int x;
int y;
Line 3,916 ⟶ 4,249:
Gtk.main();
return 0;
}</langsyntaxhighlight>
 
=={{header|VBScript}}==
Again no graphics in VBScript, so I write SVG in a HTML file and I open it in the default browser.
A turtle graphics library makes the sub that draws the curve very simple
<syntaxhighlight lang="vb">
<lang vb>
 
option explicit
Line 4,024 ⟶ 4,357:
hilb 7,1
set x=nothing
</syntaxhighlight>
</lang>
 
=={{header|Visual Basic .NET}}==
{{trans|D}}
<langsyntaxhighlight lang="vbnet">Imports System.Text
 
Module Module1
Line 4,138 ⟶ 4,471:
End Sub
 
End Module</langsyntaxhighlight>
{{out}}
<pre>Hilbert curve, order=1
Line 4,219 ⟶ 4,552:
{{trans|Go}}
{{libheader|DOME}}
<langsyntaxhighlight ecmascriptlang="wren">import "graphics" for Canvas, Color, Point
import "dome" for Window
 
Line 4,256 ⟶ 4,589:
 
static draw(dt) {}
}</langsyntaxhighlight>
 
{{out}}
[[File:Wren-Hilbert_curve.png|400px]]
 
=={{header|XPL0}}==
Hilbert curve from turtle graphic program on Wikipedia.
<langsyntaxhighlight XPL0lang="xpl0">def Order=5, Size=15; \length of line segment
int Dir, X, Y;
 
Line 4,294 ⟶ 4,630:
Move(X, Y);
Hilbert(Order, 1);
]</langsyntaxhighlight>
 
=={{header|Yabasic}}==
{{trans|Go}}
<langsyntaxhighlight Yabasiclang="yabasic">width = 64
sub hilbert(x, y, lg, i1, i2)
Line 4,314 ⟶ 4,650:
open window 655, 655
hilbert(0, 0, width, 0, 0)</langsyntaxhighlight>
 
=={{header|zkl}}==
Uses Image Magick and
the PPM class from http://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm#zkl
<langsyntaxhighlight lang="zkl">hilbert(6) : turtle(_);
 
fcn hilbert(n){ // Lindenmayer system --> Data of As & Bs
Line 4,345 ⟶ 4,681:
}
img.writeJPGFile("hilbert.zkl.jpg");
}</langsyntaxhighlight>
Image at [http://www.zenkinetic.com/Images/RosettaCode/hilbert.zkl.jpg hilbert curve]
2,120

edits