Peano curve: Difference between revisions

→‎{{header|jq}}: Add turtle graphics solution
(→‎{{header|jq}}: '''Adapted from #Go''')
(→‎{{header|jq}}: Add turtle graphics solution)
Line 567:
 
=={{header|jq}}==
'''Adapted from [[#Go]]'''
 
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
 
This entry includes two distinct solutions. In both cases, the jq program generates
The following jq program generates an SVG file that can be viewed
a SVG document, which can be viewed directly in the browser,
using a web browser, at least if the file suffix is ".svg";.
a .png version of the image can be viewed at https://imgur.com/a/RGQr17J
 
===Using a Lindenmayer System===
In this section, a Lindenmayer system of rules is used with turtle
graphics.
 
The output converted to a .png file can be viewed at https://imgur.com/gallery/4QbUN7I
====Simple Turtle Graphics====
<lang jq>
# => = 0 degrees
# ^ = 90 degrees
# <= = 180 degrees
# v = 270 degrees
 
# $start : [$x, $y]
def turtle($start):
$start
| if type == "array" then "M \($start|join(","))" else "M 0,0" end
| {svg: ., up:true, angle:0};
 
def turtleUp: .up=true;
def turtleDown: .up=false;
 
def turtleRotate($angle): .angle = (360 + (.angle + $angle)) % 360;
 
def turtleForward($d):
if .up
then if .angle== 0 then .svg += " m \($d),0"
elif .angle== 90 then .svg += " m 0,-\($d)"
elif .angle==180 then .svg += " m -\($d),0"
elif .angle==270 then .svg += " m 0,\($d)"
else "unsupported angle \(.angle)" | error
end
else if .angle== 0 then .svg += " h \($d)"
elif .angle== 90 then .svg += " v -\($d)"
elif .angle==180 then .svg += " h -\($d)"
elif .angle==270 then .svg += " v \($d)"
else "unsupported angle \(.angle)" | error
end
end;
 
def svg($size):
"<svg viewBox=\"0 0 \($size) \($size)\" xmlns=\"http://www.w3.org/2000/svg\">",
.,
"</svg>";
def path($fill; $stroke):
"<path fill=\"\($fill)\" stroke=\"\($stroke)\" stroke-width=\"0.1\" d=\"\(.svg)\" />";
 
def draw:
path("none"; "red") | svg(100) ;</lang>
====Peano Curve====
<lang jq># Compute the curve using a Lindenmayer system of rules
def rules:
{ L: "LFRFL-F-RFLFR+F+LFRFL",
R: "RFLFR+F+LFRFL-F-RFLFR" } ;
 
def peano($count):
rules as $rules
| def p($count):
if $count <= 0 then .
else gsub("L"; "l") | gsub("R"; $rules["R"]) | gsub("l"; $rules["L"]) | p($count-1)
end;
"L" | p($count) ;
 
def interpret($x):
if $x == "+" then turtleRotate(90)
elif $x == "-" then turtleRotate(-90)
elif $x == "F" then turtleForward(1)
else .
end;
 
def peano_curve($n):
peano($n)
| split("")
| reduce .[] as $action (turtle([1,1]) | turtleDown;
interpret($action) ) ;
 
peano_curve(4)
| draw</lang>
{{out}}
See https://imgur.com/gallery/4QbUN7I
 
===Peano-Meander curve===
'''Adapted from [[#Go]]'''
 
A .png version of the SVG image generated using an invocation
Example invocation:
asuch .png version ofas the imagefollowing can be viewed at https://imgur.com/a/RGQr17J
<pre>
jq -nr -f peano-curve.jq > peano-curve.svg
2,469

edits