task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Draw_a_cuboid | Draw a cuboid | Task
Draw a cuboid with relative dimensions of 2 × 3 × 4.
The cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.
To fulfill the criteria of being a cuboid, three faces must be visible.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a sphere
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #Ruby | Ruby | X, Y, Z = 6, 2, 3
DIR = {"-" => [1,0], "|" => [0,1], "/" => [1,1]}
def cuboid(nx, ny, nz)
puts "cuboid %d %d %d:" % [nx, ny, nz]
x, y, z = X*nx, Y*ny, Z*nz
area = Array.new(y+z+1){" " * (x+y+1)}
draw_line = lambda do |n, sx, sy, c|
dx, dy = DIR[c]
(n+1).times do |i|
xi, yi = sx+i*dx, sy+i*dy
area[yi][xi] = (area[yi][xi]==" " ? c : "+")
end
end
nz .times {|i| draw_line[x, 0, Z*i, "-"]}
(ny+1).times {|i| draw_line[x, Y*i, z+Y*i, "-"]}
nx .times {|i| draw_line[z, X*i, 0, "|"]}
(ny+1).times {|i| draw_line[z, x+Y*i, Y*i, "|"]}
nz .times {|i| draw_line[y, x, Z*i, "/"]}
(nx+1).times {|i| draw_line[y, X*i, z, "/"]}
puts area.reverse
end
cuboid(2, 3, 4)
cuboid(1, 1, 1)
cuboid(6, 2, 1)
cuboid(2, 4, 1) |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right.
*---R----* expands to * *
\ /
R L
\ /
*
*
/ \
L R
/ \
*---L---* expands to * *
The co-routines dcl and dcr in various examples do this recursively to a desired expansion level.
The curl direction right or left can be a parameter instead of two separate routines.
Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees.
*------->* becomes * * Recursive copies drawn
\ / from the ends towards
\ / the centre.
v v
*
This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen.
Successive approximation repeatedly re-writes each straight line as two new segments at a right angle,
*
*-----* becomes / \ bend to left
/ \ if N odd
* *
* *
*-----* becomes \ / bend to right
\ / if N even
*
Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing.
The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this.
Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently.
n = 1010110000
^
bit above lowest 1-bit, turn left or right as 0 or 1
LowMask = n BITXOR (n-1) # eg. giving 0000011111
AboveMask = LowMask + 1 # eg. giving 0000100000
BitAboveLowestOne = n BITAND AboveMask
The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there.
If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is.
Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction.
If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1.
Absolute direction to move at point n can be calculated by the number of bit-transitions in n.
n = 11 00 1111 0 1
^ ^ ^ ^ 4 places where change bit value
so direction=4*90degrees=East
This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ.
Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently.
Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this.
A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.)
The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section.
As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code.
Axiom F, angle 90 degrees
F -> F+S
S -> F-S
This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page.
Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around.
The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
| #jq | jq | include "simple-turtle" {search: "."};
def rules:
{ F: "F+S",
S: "F-S" };
def dragon($count):
rules as $rules
| def p($count):
if $count <= 0 then .
else gsub("S"; "s") | gsub("F"; $rules["F"]) | gsub("s"; $rules["S"])
| p($count-1)
end;
"F" | p($count) ;
def interpret($x):
if $x == "+" then turtleRotate(90)
elif $x == "-" then turtleRotate(-90)
elif $x == "F" then turtleForward(4)
elif $x == "S" then turtleForward(4)
else .
end;
def dragon_curve($n):
dragon($n)
| split("")
| reduce .[] as $action (turtle([200,300]) | turtleDown;
interpret($action) ) ;
dragon_curve(15)
| path("none"; "red"; "0.1") | svg(1700) |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #Perl | Perl | use strict;
use warnings;
my $x = my $y = 255;
$x |= 1; # must be odd
my $depth = 255;
my $light = Vector->new(rand, rand, rand)->normalized;
print "P2\n$x $y\n$depth\n";
my ($r, $ambient) = (($x - 1)/2, 0);
my ($r2) = $r ** 2;
{
for my $x (-$r .. $r) {
my $x2 = $x**2;
for my $y (-$r .. $r) {
my $y2 = $y**2;
my $pixel = 0;
if ($x2 + $y2 < $r2) {
my $v = Vector->new($x, $y, sqrt($r2 - $x2 - $y2))->normalized;
my $I = $light . $v + $ambient;
$I = $I < 0 ? 0 : $I > 1 ? 1 : $I;
$pixel = int($I * $depth);
}
print $pixel;
print $y == $r ? "\n" : " ";
}
}
}
package Vector {
sub new {
my $class = shift;
bless ref($_[0]) eq 'Array' ? $_[0] : [ @_ ], $class;
}
sub normalized {
my $this = shift;
my $norm = sqrt($this . $this);
ref($this)->new( map $_/$norm, @$this );
}
use overload q{.} => sub {
my ($a, $b) = @_;
my $sum = 0;
for (0 .. @$a - 1) {
$sum += $a->[$_] * $b->[$_]
}
return $sum;
},
q{""} => sub { sprintf "Vector:[%s]", join ' ', @{shift()} };
} |
http://rosettacode.org/wiki/Draw_a_clock | Draw a clock | Task
Draw a clock.
More specific:
Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be drawn; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK.
The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock.
A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task.
A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language.
Key points
animate simple object
timed event
polling system resources
code clarity
| #PicoLisp | PicoLisp | (de draw Lst
(for L Lst
(for X L
(cond
((num? X) (space X))
((sym? X) (prin X))
(T (do (car X) (prin (cdr X)))) ) )
(prinl) ) )
(de bigBox (N)
(do 2
(prin "|")
(for I 4
(prin (if (> I N) " |" " ======== |")) )
(prinl) ) )
(call 'clear) # Clear screen
(call "tput" "civis") # Set cursor invisible
(push '*Bye '(call "tput" "cnorm")) # Set cursor visible on exit
(loop
(call "tput" "cup" 0 0) # Cursor to top left
(let Time (time (time))
(draw (20 (5 . _)) (19 / 5 \\))
(if (onOff (NIL))
(draw (18 / 7 \\) (18 \\ 7 /))
(draw (18 / 2 (3 . "#") 2 \\) (18 \\ 2 (3 . "#") 2 /)) )
(draw
(19 \\ (5 . _) /)
(+ (10 . -) + (10 . -) + (10 . -) + (10 . -) +) )
(bigBox (/ (car Time) 5))
(draw (+ (10 . -) + (10 . -) + (10 . -) + (10 . -) +))
(bigBox (% (car Time) 5))
(draw (+ (43 . -) +))
(do 2
(prin "|")
(for I `(range 5 55 5)
(prin
(cond
((> I (cadr Time)) " |")
((=0 (% I 3)) " # |")
(T " = |") ) ) )
(prinl) )
(draw (+ (43 . -) +))
(bigBox (% (cadr Time) 5))
(draw (+ (10 . -) + (10 . -) + (10 . -) + (10 . -) +)) )
(wait 1000) ) |
http://rosettacode.org/wiki/Draw_a_cuboid | Draw a cuboid | Task
Draw a cuboid with relative dimensions of 2 × 3 × 4.
The cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.
To fulfill the criteria of being a cuboid, three faces must be visible.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a sphere
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #Scala | Scala | import java.awt._
import java.awt.event.{MouseAdapter, MouseEvent}
import javax.swing._
import scala.math.{Pi, cos, sin}
object Cuboid extends App {
SwingUtilities.invokeLater(() => {
class Cuboid extends JPanel {
private val nodes: Array[Array[Double]] =
Array(Array(-1, -1, -1), Array(-1, -1, 1), Array(-1, 1, -1), Array(-1, 1, 1),
Array(1, -1, -1), Array(1, -1, 1), Array(1, 1, -1), Array(1, 1, 1))
private var mouseX, prevMouseX, mouseY, prevMouseY: Int = _
private def edges =
Seq(Seq(0, 1), Seq(1, 3), Seq(3, 2), Seq(2, 0),
Seq(4, 5), Seq(5, 7), Seq(7, 6), Seq(6, 4),
Seq(0, 4), Seq(1, 5), Seq(2, 6), Seq(3, 7))
override def paintComponent(gg: Graphics): Unit = {
val g = gg.asInstanceOf[Graphics2D]
def drawCube(g: Graphics2D): Unit = {
g.translate(getWidth / 2, getHeight / 2)
for (edge <- edges) {
g.drawLine(nodes(edge.head)(0).round.toInt, nodes(edge.head)(1).round.toInt,
nodes(edge(1))(0).round.toInt, nodes(edge(1))(1).round.toInt)
}
for (node <- nodes) g.fillOval(node(0).round.toInt - 4, node(1).round.toInt - 4, 8, 8)
}
super.paintComponent(gg)
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
drawCube(g)
}
private def scale(sx: Double, sy: Double, sz: Double): Unit = {
for (node <- nodes) {
node(0) *= sx
node(1) *= sy
node(2) *= sz
}
}
private def rotateCube(angleX: Double, angleY: Double): Unit = {
val (sinX, cosX, sinY, cosY) = (sin(angleX), cos(angleX), sin(angleY), cos(angleY))
for (node <- nodes) {
val (x, y, z) = (node.head, node(1), node(2))
node(0) = x * cosX - z * sinX
node(2) = z * cosX + x * sinX
node(1) = y * cosY - node(2) * sinY
node(2) = node(2) * cosY + y * sinY
}
}
addMouseListener(new MouseAdapter() {
override def mousePressed(e: MouseEvent): Unit = {
mouseX = e.getX
mouseY = e.getY
}
})
addMouseMotionListener(new MouseAdapter() {
override def mouseDragged(e: MouseEvent): Unit = {
prevMouseX = mouseX
prevMouseY = mouseY
mouseX = e.getX
mouseY = e.getY
rotateCube((mouseX - prevMouseX) * 0.01, (mouseY - prevMouseY) * 0.01)
repaint()
}
})
scale(80, 120, 160)
rotateCube(Pi / 5, Pi / 9)
setPreferredSize(new Dimension(640, 640))
setBackground(Color.white)
}
new JFrame("Cuboid") {
add(new Cuboid, BorderLayout.CENTER)
pack()
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
setLocationRelativeTo(null)
setResizable(false)
setVisible(true)
}
})
} |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right.
*---R----* expands to * *
\ /
R L
\ /
*
*
/ \
L R
/ \
*---L---* expands to * *
The co-routines dcl and dcr in various examples do this recursively to a desired expansion level.
The curl direction right or left can be a parameter instead of two separate routines.
Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees.
*------->* becomes * * Recursive copies drawn
\ / from the ends towards
\ / the centre.
v v
*
This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen.
Successive approximation repeatedly re-writes each straight line as two new segments at a right angle,
*
*-----* becomes / \ bend to left
/ \ if N odd
* *
* *
*-----* becomes \ / bend to right
\ / if N even
*
Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing.
The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this.
Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently.
n = 1010110000
^
bit above lowest 1-bit, turn left or right as 0 or 1
LowMask = n BITXOR (n-1) # eg. giving 0000011111
AboveMask = LowMask + 1 # eg. giving 0000100000
BitAboveLowestOne = n BITAND AboveMask
The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there.
If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is.
Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction.
If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1.
Absolute direction to move at point n can be calculated by the number of bit-transitions in n.
n = 11 00 1111 0 1
^ ^ ^ ^ 4 places where change bit value
so direction=4*90degrees=East
This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ.
Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently.
Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this.
A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.)
The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section.
As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code.
Axiom F, angle 90 degrees
F -> F+S
S -> F-S
This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page.
Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around.
The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
| #Julia | Julia |
using Luxor
function dragon(turtle::Turtle, level=4, size=200, direction=45)
if level != 0
Turn(turtle, -direction)
dragon(turtle, level-1, size/sqrt(2), 45)
Turn(turtle, direction*2)
dragon(turtle, level-1, size/sqrt(2), -45)
Turn(turtle, -direction)
else
Forward(turtle, size)
end
end
Drawing(900, 500, "./Dragon.png")
t = Turtle(300, 300, true, 0, (0., 0.0, 0.0));
dragon(t, 10,400)
finish()
preview()
|
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #Phix | Phix | --
-- demo\rosetta\Draw_a_sphere.exw
-- ==============================
--
with javascript_semantics
include pGUI.e
constant title = "Draw a sphere"
Ihandle dlg, canvas
cdCanvas cddbuffer, cdcanvas
function dot(sequence x, y)
return sum(sq_mul(x,y))
end function
function normalize(sequence v)
atom len = sqrt(dot(v, v))
return iff(len=0?{0,0,0}:sq_mul(v,1/len))
end function
procedure drawSphere(integer width, height, atom k, amb, sequence direction)
atom t0 = time()+1, t1 = t0,
lmul = 255/(1+amb)
integer r = floor((min(width,height)-20)/2),
cx = floor(width/2),
cy = floor(height/2)
for x=-r to r do
if time()>t1 then
-- Let the user know we aren't completely dead just yet
IupSetStrAttribute(dlg,"TITLE","%s - drawing (%d%%)",{title,100*(x+r)/(2*r)})
t1 = time()+1
-- (as per DeathStar.exw, prevent "(Not Responding)" nonsense)
if platform()!=JS then
if IupLoopStep()=IUP_CLOSE then
IupExitLoop()
exit
end if
end if
end if
for y=-r to r do
integer z = r*r-(x*x+y*y)
if z>=0 then
atom s = dot(direction, normalize({x,y,sqrt(z)})),
l = iff(s<=0?0:power(s,k))
integer lum = and_bits(#FF,lmul*(l+amb))
cdCanvasPixel(cddbuffer, x+cx, y+cy, lum*#10101)
end if
end for
end for
if t1!=t0 then
IupSetStrAttribute(dlg,"TITLE",title)
end if
end procedure
function redraw_cb(Ihandle /*ih*/, integer /*posx*/, /*posy*/)
integer {width, height} = IupGetIntInt(canvas, "DRAWSIZE")
cdCanvasActivate(cddbuffer)
cdCanvasClear(cddbuffer)
drawSphere(width,height,1.5,0.2,normalize({-30,-30,50}))
cdCanvasFlush(cddbuffer)
return IUP_DEFAULT
end function
function map_cb(Ihandle ih)
cdcanvas = cdCreateCanvas(CD_IUP, ih)
cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
cdCanvasSetBackground(cddbuffer, CD_BLACK)
return IUP_DEFAULT
end function
procedure main()
IupOpen()
canvas = IupCanvas("RASTERSIZE=340x340")
IupSetCallbacks(canvas, {"MAP_CB", Icallback("map_cb"),
"ACTION", Icallback("redraw_cb")})
dlg = IupDialog(canvas,`TITLE="%s"`,{title})
IupShow(dlg)
IupSetAttribute(canvas, "RASTERSIZE", NULL) -- release the minimum limitation
if platform()!=JS then
IupMainLoop()
IupClose()
end if
end procedure
main()
|
http://rosettacode.org/wiki/Draw_a_clock | Draw a clock | Task
Draw a clock.
More specific:
Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be drawn; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK.
The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock.
A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task.
A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language.
Key points
animate simple object
timed event
polling system resources
code clarity
| #Processing | Processing | void draw() {
drawClock();
}
void drawClock() {
background(192);
translate(width/2, height/2);
float s = second() * TWO_PI / 60.0;
float m = minute() * TWO_PI / 60.0;
float h = hour() * TWO_PI / 12.0;
rotate(s);
strokeWeight(1);
line(0, 0, 0, -width*0.5);
rotate(-s+m);
strokeWeight(2);
line(0, 0, 0, -width*0.4);
rotate(-m+h);
strokeWeight(4);
line(0, 0, 0, -width*0.2);
} |
http://rosettacode.org/wiki/Draw_a_cuboid | Draw a cuboid | Task
Draw a cuboid with relative dimensions of 2 × 3 × 4.
The cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.
To fulfill the criteria of being a cuboid, three faces must be visible.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a sphere
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #Sidef | Sidef | const dirs = Hash("-" => [1,0], "|" => [0,1], "/" => [1,1])
func cuboid(nx, ny, nz) {
say("cuboid %d %d %d:" % [nx, ny, nz])
var(x, y, z) = (8*nx, 2*ny, 4*nz)
var area = []
var line = func(n, sx, sy, c) {
var(dx, dy) = dirs{c}...
for i (0..n) {
var (xi, yi) = (sx + i*dx, sy + i*dy)
area[yi] \\= [" "]*(x+y+1)
area[yi][xi] = (area[yi][xi] == " " ? c : '+')
}
}
0 .. nz-1 -> each {|i| line(x, 0, 4*i, "-") }
0 .. ny -> each {|i| line(x, 2*i, z + 2*i, "-") }
0 .. nx-1 -> each {|i| line(z, 8*i, 0, "|") }
0 .. ny -> each {|i| line(z, x + 2*i, 2*i, "|") }
0 .. nz-1 -> each {|i| line(y, x, 4*i, "/") }
0 .. nx -> each {|i| line(y, 8*i, z, "/") }
area.reverse.each { |line|
say line.join('')
}
}
cuboid(2, 3, 4)
cuboid(1, 1, 1)
cuboid(6, 2, 1)
cuboid(2, 4, 1) |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right.
*---R----* expands to * *
\ /
R L
\ /
*
*
/ \
L R
/ \
*---L---* expands to * *
The co-routines dcl and dcr in various examples do this recursively to a desired expansion level.
The curl direction right or left can be a parameter instead of two separate routines.
Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees.
*------->* becomes * * Recursive copies drawn
\ / from the ends towards
\ / the centre.
v v
*
This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen.
Successive approximation repeatedly re-writes each straight line as two new segments at a right angle,
*
*-----* becomes / \ bend to left
/ \ if N odd
* *
* *
*-----* becomes \ / bend to right
\ / if N even
*
Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing.
The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this.
Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently.
n = 1010110000
^
bit above lowest 1-bit, turn left or right as 0 or 1
LowMask = n BITXOR (n-1) # eg. giving 0000011111
AboveMask = LowMask + 1 # eg. giving 0000100000
BitAboveLowestOne = n BITAND AboveMask
The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there.
If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is.
Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction.
If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1.
Absolute direction to move at point n can be calculated by the number of bit-transitions in n.
n = 11 00 1111 0 1
^ ^ ^ ^ 4 places where change bit value
so direction=4*90degrees=East
This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ.
Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently.
Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this.
A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.)
The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section.
As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code.
Axiom F, angle 90 degrees
F -> F+S
S -> F-S
This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page.
Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around.
The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
| #Kotlin | Kotlin | // version 1.0.6
import java.awt.Color
import java.awt.Graphics
import javax.swing.JFrame
class DragonCurve(iter: Int) : JFrame("Dragon Curve") {
private val turns: MutableList<Int>
private val startingAngle: Double
private val side: Double
init {
setBounds(100, 100, 800, 600)
defaultCloseOperation = EXIT_ON_CLOSE
turns = getSequence(iter)
startingAngle = -iter * Math.PI / 4
side = 400.0 / Math.pow(2.0, iter / 2.0)
}
fun getSequence(iterations: Int): MutableList<Int> {
val turnSequence = mutableListOf<Int>()
for (i in 0 until iterations) {
val copy = mutableListOf<Int>()
copy.addAll(turnSequence)
copy.reverse()
turnSequence.add(1)
copy.mapTo(turnSequence) { -it }
}
return turnSequence
}
override fun paint(g: Graphics) {
g.color = Color.BLUE
var angle = startingAngle
var x1 = 230
var y1 = 350
var x2 = x1 + (Math.cos(angle) * side).toInt()
var y2 = y1 + (Math.sin(angle) * side).toInt()
g.drawLine(x1, y1, x2, y2)
x1 = x2
y1 = y2
for (turn in turns) {
angle += turn * Math.PI / 2.0
x2 = x1 + (Math.cos(angle) * side).toInt()
y2 = y1 + (Math.sin(angle) * side).toInt()
g.drawLine(x1, y1, x2, y2)
x1 = x2
y1 = y2
}
}
}
fun main(args: Array<String>) {
DragonCurve(14).isVisible = true
} |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #PicoLisp | PicoLisp | (load "@lib/openGl.l")
(glutInit)
(glutInitDisplayMode (| GLUT_RGBA GLUT_DOUBLE GLUT_ALPHA GLUT_DEPTH))
(glutInitWindowSize 400 400)
(glutCreateWindow "Sphere")
(glEnable GL_LIGHTING)
(glEnable GL_LIGHT0)
(glLightiv GL_LIGHT0 GL_POSITION (10 10 -10 0))
(glEnable GL_COLOR_MATERIAL)
(glColorMaterial GL_FRONT_AND_BACK GL_AMBIENT_AND_DIFFUSE)
(glClearColor 0.3 0.3 0.5 0)
(glColor4f 0.0 0.8 0.0 1.0)
(displayPrg
(glClear (| GL_COLOR_BUFFER_BIT GL_DEPTH_BUFFER_BIT))
(glutSolidSphere 0.9 40 32)
(glFlush)
(glutSwapBuffers) )
# Exit upon mouse click
(mouseFunc '((Btn State X Y) (bye)))
(glutMainLoop) |
http://rosettacode.org/wiki/Draw_a_clock | Draw a clock | Task
Draw a clock.
More specific:
Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be drawn; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK.
The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock.
A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task.
A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language.
Key points
animate simple object
timed event
polling system resources
code clarity
| #PureBasic | PureBasic | #MiddleX = 90 + 1 ;x,y must be odd numbers, minimum width is 67
#MiddleY = #MiddleX
#len_sh = (#MiddleX - 8) * 0.97 ;length of second-hand
#len_mh = (#MiddleX - 8) * 0.88 ;length of minute-hand
#len_hh = (#MiddleX - 8) * 0.66 ;length of hour-hand
#clockFace_img = 0
#clock_gad = 0
#clock_win = 0
Define cx = #MiddleX, cy = #MiddleY, i, ri.f
Define c_gray = RGB($CC, $CC, $CC), c_mgray = RGB($99, $99, $99)
Define c_white = RGB(255, 255, 255), c_black =RGB(0, 0, 0)
Define c_red = RGB(255, 0, 0), c_blue = RGB(0, 0, 255)
Define c_dcyan = RGB($27, $BC, $D8), c_lgreen = RGB($60, $E0, $9)
Define c_yellow = RGB($F4, $D5, $0B)
CreateImage(#clockFace_img, cx * 2 - 1, cy * 2 - 1)
StartDrawing(ImageOutput(#clockFace_img))
Box(0, 0, cx * 2 - 1, cy * 2 - 1, c_mgray)
Circle(cx, cy, cx - 2, c_dcyan)
For i = 0 To 359 Step 30
ri = Radian(i)
Circle(cx + Sin(ri) * (cx - 5), cy + Cos(ri) * (cx - 5), 3, c_gray)
Next
StopDrawing()
OpenWindow(#clock_win, 0, 0, cx * 2, cy * 2, "Clock")
ImageGadget(#clock_gad, 0, 0, cx * 2, cy * 2, ImageID(#clockFace_img))
Define x, y, rad_s.f, rad_m.f, rad_h.f, t$
Repeat
event = WaitWindowEvent(25)
If event = 0
rad_s = Radian(360 - (Second(Date()) * 6) + 180)
rad_m = Radian(360 - (Minute(Date()) * 6) + 180)
rad_h = Radian(360 - (((Hour(Date()) - 1) * 30) + 180) - (Minute(Date()) / 2))
StartDrawing(ImageOutput(#clockFace_img))
Circle(cx, cy, cx - 8, c_lgreen)
t$ = FormatDate("%mm-%dd-%yyyy", Date())
x = cx - (TextWidth(t$) + 2) / 2
y = (cy - (TextHeight(t$) + 2) - 4) / 2
Box(x, y, TextWidth(t$) + 2, TextHeight(t$) + 2, c_black)
DrawText(x + 2, y + 2, t$, c_black, c_yellow)
LineXY(cx, cy, cx + Sin(rad_s) * #len_sh, cy + Cos(rad_s) * #len_sh, c_white)
LineXY(cx, cy, cx + Sin(rad_m) * #len_mh, cy + Cos(rad_m) * #len_mh, c_red)
LineXY(cx, cy, cx + Sin(rad_h) * #len_hh, cy + Cos(rad_h) * #len_hh, c_black)
Circle(cx, cy, 4, c_blue)
StopDrawing()
SetGadgetState(#clock_gad, ImageID(#clockFace_img))
EndIf
Until event = #PB_Event_CloseWindow |
http://rosettacode.org/wiki/Draw_a_cuboid | Draw a cuboid | Task
Draw a cuboid with relative dimensions of 2 × 3 × 4.
The cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.
To fulfill the criteria of being a cuboid, three faces must be visible.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a sphere
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #Tcl | Tcl | package require Tcl 8.5
package require Tk
package require math::linearalgebra
package require math::constants
# Helper for constructing a rectangular face in 3D
proc face {px1 py1 pz1 px2 py2 pz2 px3 py3 pz3 px4 py4 pz4 color} {
set centroidX [expr {($px1+$px2+$px3+$px4)/4.0}]
set centroidY [expr {($py1+$py2+$py3+$py4)/4.0}]
set centroidZ [expr {($pz1+$pz2+$pz3+$pz4)/4.0}]
list [list \
[list [expr {double($px1)}] [expr {double($py1)}] [expr {double($pz1)}]] \
[list [expr {double($px2)}] [expr {double($py2)}] [expr {double($pz2)}]] \
[list [expr {double($px3)}] [expr {double($py3)}] [expr {double($pz3)}]] \
[list [expr {double($px4)}] [expr {double($py4)}] [expr {double($pz4)}]]] \
[list $centroidX $centroidY $centroidZ] \
$color
}
# How to make a cuboid of given size at the origin
proc makeCuboid {size} {
lassign $size x y z
list \
[face 0 0 0 0 $y 0 $x $y 0 $x 0 0 "#800000"] \
[face 0 0 0 0 $y 0 0 $y $z 0 0 $z "#ff8080"] \
[face 0 0 0 $x 0 0 $x 0 $z 0 0 $z "#000080"] \
[face $x 0 0 $x $y 0 $x $y $z $x 0 $z "#008000"] \
[face 0 $y 0 $x $y 0 $x $y $z 0 $y $z "#80ff80"] \
[face 0 0 $z $x 0 $z $x $y $z 0 $y $z "#8080ff"]
}
# Project a shape onto a surface (Tk canvas); assumes that the shape's faces
# are simple and non-intersecting (i.e., it sorts by centroid z-order).
proc drawShape {surface shape} {
global projection
lassign $projection pmat poff
lassign $poff px py pz
foreach side $shape {
lassign $side points centroid color
set pc [::math::linearalgebra::matmul $pmat $centroid]
lappend sorting [list [expr {[lindex $pc 2]+$pz}] $points $color]
}
foreach side [lsort -real -decreasing -index 0 $sorting] {
lassign $side sortCriterion points color
set plotpoints {}
foreach p $points {
set p [::math::linearalgebra::matmul $pmat $p]
lappend plotpoints \
[expr {[lindex $p 0]+$px}] [expr {[lindex $p 1]+$py}]
}
$surface create poly $plotpoints -outline {} -fill $color
}
}
# How to construct the projection transform.
# This is instead of using a hokey hard-coded version
namespace eval transform {
namespace import ::math::linearalgebra::*
::math::constants::constants pi
proc make {angle scale offset} {
variable pi
set c [expr {cos($angle*$pi/180)}]
set s [expr {sin($angle*$pi/180)}]
set ms [expr {-$s}]
set rotX [list {1.0 0.0 0.0} [list 0.0 $c $ms] [list 0.0 $s $c]]
set rotY [list [list $c 0.0 $s] {0.0 1.0 0.0} [list $ms 0.0 $c]]
set rotZ [list [list $c $s 0.0] [list $ms $c 0.0] {0.0 0.0 1.0}]
set mat [scale $scale [mkIdentity 3]]
set mat [matmul [matmul [matmul $mat $rotX] $rotY] $rotZ]
return [list $mat $offset]
}
}
### End of definitions
# Put the pieces together
pack [canvas .c -width 400 -height 400]
set cuboid [makeCuboid {2 3 4}]
set projection [transform::make 15 50 {100 100 100}]
drawShape .c $cuboid |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right.
*---R----* expands to * *
\ /
R L
\ /
*
*
/ \
L R
/ \
*---L---* expands to * *
The co-routines dcl and dcr in various examples do this recursively to a desired expansion level.
The curl direction right or left can be a parameter instead of two separate routines.
Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees.
*------->* becomes * * Recursive copies drawn
\ / from the ends towards
\ / the centre.
v v
*
This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen.
Successive approximation repeatedly re-writes each straight line as two new segments at a right angle,
*
*-----* becomes / \ bend to left
/ \ if N odd
* *
* *
*-----* becomes \ / bend to right
\ / if N even
*
Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing.
The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this.
Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently.
n = 1010110000
^
bit above lowest 1-bit, turn left or right as 0 or 1
LowMask = n BITXOR (n-1) # eg. giving 0000011111
AboveMask = LowMask + 1 # eg. giving 0000100000
BitAboveLowestOne = n BITAND AboveMask
The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there.
If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is.
Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction.
If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1.
Absolute direction to move at point n can be calculated by the number of bit-transitions in n.
n = 11 00 1111 0 1
^ ^ ^ ^ 4 places where change bit value
so direction=4*90degrees=East
This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ.
Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently.
Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this.
A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.)
The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section.
As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code.
Axiom F, angle 90 degrees
F -> F+S
S -> F-S
This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page.
Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around.
The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
| #Lambdatalk | Lambdatalk |
{def dcr
{lambda {:step :length}
{let { {:step {- :step 1}}
{:length {/ :length 1.41421}}
} {if {> :step 0}
then T45
{dcr :step :length}
T-90
{dcl :step :length}
T45
else T45
M:length
T-90
M:length
T45}
}}}
-> dcr
{def dcl
{lambda {:step :length}
{let { {:step {- :step 1}}
{:length {/ :length 1.41421}}
} {if {> :step 0}
then T-45
{dcr :step :length}
T90
{dcl :step :length}
T-45
else T-45
M:length
T90
M:length
T-45}
}}}
-> dcl
|
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #PostScript | PostScript | %!PS-Adobe-3.0
%%BoundingBox 0 0 300 300
150 150 translate 0 0 130 0 360 arc
/Pattern setcolorspace
<< /PatternType 2
/Shading <<
/ShadingType 3
/ColorSpace /DeviceRGB
/Coords [-60 60 0 0 0 100]
/Function <<
/FunctionType 2
/Domain [0 1]
/C0 [1 1 1]
/C1 [0 0 0]
/N 2
>>
>>
>> matrix makepattern setcolor fill
showpage
%%EOF
|
http://rosettacode.org/wiki/Draw_a_clock | Draw a clock | Task
Draw a clock.
More specific:
Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be drawn; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK.
The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock.
A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task.
A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language.
Key points
animate simple object
timed event
polling system resources
code clarity
| #Python | Python | import time
def chunks(l, n=5):
return [l[i:i+n] for i in range(0, len(l), n)]
def binary(n, digits=8):
n=int(n)
return '{0:0{1}b}'.format(n, digits)
def secs(n):
n=int(n)
h='x' * n
return "|".join(chunks(h))
def bin_bit(h):
h=h.replace("1","x")
h=h.replace("0"," ")
return "|".join(list(h))
x=str(time.ctime()).split()
y=x[3].split(":")
s=y[-1]
y=map(binary,y[:-1])
print bin_bit(y[0])
print
print bin_bit(y[1])
print
print secs(s) |
http://rosettacode.org/wiki/Draw_a_cuboid | Draw a cuboid | Task
Draw a cuboid with relative dimensions of 2 × 3 × 4.
The cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.
To fulfill the criteria of being a cuboid, three faces must be visible.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a sphere
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #VBScript | VBScript | x = 6 : y = 2 : z = 3
Sub cuboid(nx, ny, nz)
WScript.StdOut.WriteLine "Cuboid " & nx & " " & ny & " " & nz & ":"
lx = X * nx : ly = y * ny : lz = z * nz
'define the array
Dim area(): ReDim area(ly+lz, lx+ly)
For i = 0 to ly+lz
For j = 0 to lx+ly : area(i,j) = " " : Next
Next
'drawing lines
For i = 0 to nz-1 : drawLine area, lx, 0, Z*i, "-" : Next
For i = 0 to ny : drawLine area, lx, y*i, lz+y*i, "-" : Next
For i = 0 to nx-1 : drawLine area, lz, x*i, 0, "|" : Next
For i = 0 to ny : drawLine area, lz, lx+y*i, y*i, "|" : Next
For i = 0 to nz-1 : drawLine area, ly, lx, z*i, "/" : Next
For i = 0 to nx : drawLine area, ly, x*i, lz, "/" : Next
'output the cuboid (in reverse)
For i = UBound(area,1) to 0 Step -1
linOut = ""
For j = 0 to UBound(area,2) : linOut = linOut & area(i,j) : Next
WScript.StdOut.WriteLine linOut
Next
End Sub
Sub drawLine(arr, n, sx, sy, c)
Select Case c
Case "-"
dx = 1 : dy = 0
Case "|"
dx = 0 : dy = 1
Case "/"
dx = 1 : dy = 1
End Select
For i = 0 to n
xi = sx + (i * dx) : yi = sy + (i * dy)
If arr(yi, xi) = " " Then
arr(yi, xi) = c
Else
arr(yi, xi) = "+"
End If
Next
End Sub
cuboid 2,3,4 |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right.
*---R----* expands to * *
\ /
R L
\ /
*
*
/ \
L R
/ \
*---L---* expands to * *
The co-routines dcl and dcr in various examples do this recursively to a desired expansion level.
The curl direction right or left can be a parameter instead of two separate routines.
Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees.
*------->* becomes * * Recursive copies drawn
\ / from the ends towards
\ / the centre.
v v
*
This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen.
Successive approximation repeatedly re-writes each straight line as two new segments at a right angle,
*
*-----* becomes / \ bend to left
/ \ if N odd
* *
* *
*-----* becomes \ / bend to right
\ / if N even
*
Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing.
The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this.
Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently.
n = 1010110000
^
bit above lowest 1-bit, turn left or right as 0 or 1
LowMask = n BITXOR (n-1) # eg. giving 0000011111
AboveMask = LowMask + 1 # eg. giving 0000100000
BitAboveLowestOne = n BITAND AboveMask
The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there.
If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is.
Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction.
If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1.
Absolute direction to move at point n can be calculated by the number of bit-transitions in n.
n = 11 00 1111 0 1
^ ^ ^ ^ 4 places where change bit value
so direction=4*90degrees=East
This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ.
Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently.
Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this.
A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.)
The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section.
As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code.
Axiom F, angle 90 degrees
F -> F+S
S -> F-S
This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page.
Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around.
The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
| #Liberty_BASIC | Liberty BASIC | nomainwin
mainwin 50 20
WindowHeight =620
WindowWidth =690
open "Graphics library" for graphics as #a
#a, "trapclose [quit]"
#a "down"
Turn$ ="R"
Pace =100
s = 16
[again]
print Turn$
#a "cls ; home ; north ; down ; fill black"
for i =1 to len( Turn$)
v =255 *i /len( Turn$)
#a "color "; v; " 120 "; 255 -v
#a "go "; Pace
if mid$( Turn$, i, 1) ="R" then #a "turn 90" else #a "turn -90"
next i
#a "color 255 120 0"
#a "go "; Pace
#a "flush"
FlippedTurn$ =""
for i =len( Turn$) to 1 step -1
if mid$( Turn$, i, 1) ="R" then FlippedTurn$ =FlippedTurn$ +"L" else FlippedTurn$ =FlippedTurn$ +"R"
next i
Turn$ =Turn$ +"R" +FlippedTurn$
Pace =Pace /1.35
scan
timer 1000, [j]
wait
[j]
timer 0
if len( Turn$) <40000 then goto [again]
wait
[quit]
close #a
end |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #POV-Ray | POV-Ray |
camera { location <0.0 , .8 ,-3.0> look_at 0}
light_source{< 3,3,-3> color rgb 1}
sky_sphere { pigment{ gradient <0,1,0> color_map {[0 color rgb <.2,.1,0>][.5 color rgb 1]} scale 2}}
plane {y,-2 pigment { hexagon color rgb .7 color rgb .5 color rgb .6 }}
sphere { 0,1
texture {
pigment{ color rgbft <.8,1,1,.4,.4> }
finish { phong 1 reflection {0.40 metallic 0.5} }
}
interior { ior 1.5}
}
|
http://rosettacode.org/wiki/Draw_a_clock | Draw a clock | Task
Draw a clock.
More specific:
Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be drawn; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK.
The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock.
A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task.
A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language.
Key points
animate simple object
timed event
polling system resources
code clarity
| #Racket | Racket |
#lang racket/gui
(require racket/date slideshow/pict)
(define (clock h m s [r 100])
(define (draw-hand length angle
#:width [width 1]
#:color [color "black"])
(dc (λ (dc dx dy)
(define old-pen (send dc get-pen))
(send dc set-pen (new pen% [width width] [color color]))
(send dc draw-line
(+ dx r) (+ dy r)
(+ dx r (* length (sin angle)))
(+ dy r (* length (cos angle))))
(send dc set-pen old-pen))
(* 2 r) (* 2 r)))
(cc-superimpose
(for/fold ([pict (circle (* 2 r))])
([angle (in-range 0 (* 2 pi) (/ pi 6))]
[hour (cons 12 (range 1 12))])
(define angle* angle)
(define r* (* r 0.8))
(define txt (text (number->string hour) '(bold . "Helvetica")))
(define x (- (* r* (sin angle*)) (/ (pict-width txt) 2)))
(define y (+ (* r* (cos angle*)) (/ (pict-height txt) 2)))
(pin-over pict (+ r x) (- r y) txt))
(draw-hand (* r 0.7) (+ pi (* (modulo h 12) (- (/ pi 6))))
#:width 3)
(draw-hand (* r 0.5) (+ pi (* m (- (/ pi 30))))
#:width 2)
(draw-hand (* r 0.7) (+ pi (* s (- (/ pi 30))))
#:color "red")
(disk (* r 0.1))))
(define f (new frame% [label "Clock"] [width 300] [height 300]))
(define c
(new canvas%
[parent f]
[paint-callback
(λ (c dc)
(define date (current-date))
(draw-pict (clock (date-hour date)
(date-minute date)
(date-second date)
(/ (send c get-width) 2))
dc 0 0))]))
(define t
(new timer%
[notify-callback (λ () (send c refresh-now))]
[interval 1000]))
(send f show #t)
|
http://rosettacode.org/wiki/Draw_a_cuboid | Draw a cuboid | Task
Draw a cuboid with relative dimensions of 2 × 3 × 4.
The cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.
To fulfill the criteria of being a cuboid, three faces must be visible.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a sphere
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #Wren | Wren | import "/fmt" for Fmt
var cubLine = Fn.new { |n, dx, dy, cde|
Fmt.write("$*s", n + 1, cde[0])
for (d in 9*dx - 1...0) System.write(cde[1])
System.write(cde[0])
Fmt.print("$*s", dy + 1, cde[2..-1])
}
var cuboid = Fn.new { |dx, dy, dz|
Fmt.print("cuboid $d $d $d:", dx, dy, dz)
cubLine.call(dy+1, dx, 0, "+-")
for (i in 1..dy) cubLine.call(dy-i+1, dx, i-1, "/ |")
cubLine.call(0, dx, dy, "+-|")
for (i in 4*dz - dy - 2...0) cubLine.call(0, dx, dy, "| |")
cubLine.call(0, dx, dy, "| +")
for (i in 1..dy) cubLine.call(0, dx, dy-i, "| /")
cubLine.call(0, dx, 0, "+-\n")
}
cuboid.call(2, 3, 4)
cuboid.call(1, 1, 1)
cuboid.call(6, 2, 1) |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right.
*---R----* expands to * *
\ /
R L
\ /
*
*
/ \
L R
/ \
*---L---* expands to * *
The co-routines dcl and dcr in various examples do this recursively to a desired expansion level.
The curl direction right or left can be a parameter instead of two separate routines.
Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees.
*------->* becomes * * Recursive copies drawn
\ / from the ends towards
\ / the centre.
v v
*
This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen.
Successive approximation repeatedly re-writes each straight line as two new segments at a right angle,
*
*-----* becomes / \ bend to left
/ \ if N odd
* *
* *
*-----* becomes \ / bend to right
\ / if N even
*
Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing.
The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this.
Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently.
n = 1010110000
^
bit above lowest 1-bit, turn left or right as 0 or 1
LowMask = n BITXOR (n-1) # eg. giving 0000011111
AboveMask = LowMask + 1 # eg. giving 0000100000
BitAboveLowestOne = n BITAND AboveMask
The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there.
If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is.
Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction.
If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1.
Absolute direction to move at point n can be calculated by the number of bit-transitions in n.
n = 11 00 1111 0 1
^ ^ ^ ^ 4 places where change bit value
so direction=4*90degrees=East
This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ.
Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently.
Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this.
A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.)
The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section.
As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code.
Axiom F, angle 90 degrees
F -> F+S
S -> F-S
This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page.
Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around.
The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
| #Logo | Logo | to dcr :step :length
make "step :step - 1
make "length :length / 1.41421
if :step > 0 [rt 45 dcr :step :length lt 90 dcl :step :length rt 45]
if :step = 0 [rt 45 fd :length lt 90 fd :length rt 45]
end
to dcl :step :length
make "step :step - 1
make "length :length / 1.41421
if :step > 0 [lt 45 dcr :step :length rt 90 dcl :step :length lt 45]
if :step = 0 [lt 45 fd :length rt 90 fd :length lt 45]
end |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #Processing | Processing | void setup() {
size(500, 500, P3D);
}
void draw() {
background(192);
translate(width/2, height/2);
// optional color and lighting style
stroke(200);
fill(255);
lights();
// draw sphere
sphere(200);
} |
http://rosettacode.org/wiki/Draw_a_clock | Draw a clock | Task
Draw a clock.
More specific:
Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be drawn; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK.
The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock.
A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task.
A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language.
Key points
animate simple object
timed event
polling system resources
code clarity
| #Raku | Raku | my ($rows,$cols) = qx/stty size/.words;
my $v = floor $rows / 2;
my $h = floor $cols / 2 - 16;
my @t = < ⡎⢉⢵ ⠀⢺⠀ ⠊⠉⡱ ⠊⣉⡱ ⢀⠔⡇ ⣏⣉⡉ ⣎⣉⡁ ⠊⢉⠝ ⢎⣉⡱ ⡎⠉⢱ ⠀⠶⠀>;
my @b = < ⢗⣁⡸ ⢀⣸⣀ ⣔⣉⣀ ⢄⣀⡸ ⠉⠉⡏ ⢄⣀⡸ ⢇⣀⡸ ⢰⠁⠀ ⢇⣀⡸ ⢈⣉⡹ ⠀⠶⠀>;
loop {
my @x = DateTime.now.Str.substr(11,8).ords X- ord('0');
print "\e[H\e[J";
print "\e[$v;{$h}H";
print ~@t[@x];
print "\e[{$v+1};{$h}H";
print ~@b[@x];
print "\e[H";
sleep 1;
} |
http://rosettacode.org/wiki/Draw_a_cuboid | Draw a cuboid | Task
Draw a cuboid with relative dimensions of 2 × 3 × 4.
The cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.
To fulfill the criteria of being a cuboid, three faces must be visible.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a sphere
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #X86_Assembly | X86 Assembly | 1 ;Assemble with: tasm, tlink /t
2 0000 .model tiny
3 0000 .code
4 .386
5 org 100h
6 ;assume: ax=0000h, bx=0000h, cx=00ff, and
7 ; direction bit is clear (so di increments)
8 ; ____
9 =0050 X0 equ 80 ; / /|
10 =0050 Y0 equ 80 ; / / |
11 =0050 wide equ 2*40 ; X0,Y0 +---+ |
12 =0064 tall equ 3*40*200/240 ; | | |
13 =0035 deep equ 4*40/3 ; | | /
14 ; |___|/
15
16 0100 B0 13 start: mov al, 13h ;set 320x200x8 graphic screen
17 0102 CD 10 int 10h
18 0104 68 A000 push 0A000h ;point es to graphic memory segment
19 0107 07 pop es
20
21 ;Draw front of cuboid using horizontal lines
22 0108 B3 64 mov bl, tall
23 010A BF E150 mov di, X0+(Y0+tall)*320 ;set pen at lower-left corner
24 010D B0 04 mov al, 4 ;use red ink
25 010F B1 50 dc10: mov cl, wide ;draw horizontal line
26 0111 F3> AA rep stosb ;es:[di++], al; cx--
27 0113 81 EF 0190 sub di, wide+320 ;move up to start of next line
28 0117 4B dec bx ;at top of face?
29 0118 75 F5 jne dc10 ;loop if not
30
31 011A B3 35 mov bl, deep
32 ;Draw top using horizontal lines
33 011C B0 02 dc20: mov al, 2 ;use green ink
34 011E B1 50 mov cl, wide ;draw horizontal line
35 0120 F3> AA rep stosb ;es:[di++], al; cx--
36
37 ;Draw side using vertical lines
38 0122 B0 01 mov al, 1 ;use blue ink
39 0124 B1 64 mov cl, tall ;draw vertical line
40 0126 AA dc30: stosb ;es:[di++], al
41 0127 81 C7 013F add di, 320-1 ;move down a pixel
42 012B E2 F9 loop dc30
43
44 012D 81 EF 7E8F sub di, wide+(tall+1)*320-1 ;move to start of next top line
45 0131 4B dec bx ;at deep limit?
46 0132 75 E8 jne dc20 ;loop if not
47
48 0134 CD 16 int 16h ;wait for keystroke (ah=0)
49 0136 B8 0003 mov ax, 0003h ;restore normal text-mode screen
50 0139 CD 10 int 10h
51 013B C3 ret ;return to DOS
52
53 end start
|
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right.
*---R----* expands to * *
\ /
R L
\ /
*
*
/ \
L R
/ \
*---L---* expands to * *
The co-routines dcl and dcr in various examples do this recursively to a desired expansion level.
The curl direction right or left can be a parameter instead of two separate routines.
Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees.
*------->* becomes * * Recursive copies drawn
\ / from the ends towards
\ / the centre.
v v
*
This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen.
Successive approximation repeatedly re-writes each straight line as two new segments at a right angle,
*
*-----* becomes / \ bend to left
/ \ if N odd
* *
* *
*-----* becomes \ / bend to right
\ / if N even
*
Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing.
The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this.
Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently.
n = 1010110000
^
bit above lowest 1-bit, turn left or right as 0 or 1
LowMask = n BITXOR (n-1) # eg. giving 0000011111
AboveMask = LowMask + 1 # eg. giving 0000100000
BitAboveLowestOne = n BITAND AboveMask
The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there.
If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is.
Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction.
If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1.
Absolute direction to move at point n can be calculated by the number of bit-transitions in n.
n = 11 00 1111 0 1
^ ^ ^ ^ 4 places where change bit value
so direction=4*90degrees=East
This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ.
Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently.
Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this.
A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.)
The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section.
As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code.
Axiom F, angle 90 degrees
F -> F+S
S -> F-S
This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page.
Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around.
The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
| #Lua | Lua | function dragon()
local l = "l"
local r = "r"
local inverse = {l = r, r = l}
local field = {r}
local num = 1
local loop_limit = 6 --increase this number to render a bigger curve
for discard=1,loop_limit do
field[num+1] = r
for i=1,num do
field[i+num+1] = inverse[field[num-i+1]]
end
num = num*2+1
end
return field
end
function render(field, w, h, l)
local x = 0
local y = 0
local points = {}
local highest_x = 0
local highest_y = 0
local lowest_x = 0
local lowest_y = 0
local l = "l"
local r = "r"
local u = "u"
local d = "d"
local heading = u
local turn = {r = {r = d, d = l, l = u, u = r}, l = {r = u, u = l, l = d, d = r}}
for k, v in ipairs(field) do
heading = turn[v][heading]
for i=1,3 do
points[#points+1] = {x, y}
if heading == l then
x = x-w
elseif heading == r then
x = x+w
elseif heading == u then
y = y-h
elseif heading == d then
y = y+h
end
if x > highest_x then
highest_x = x
elseif x < lowest_x then
lowest_x = x
end
if y > highest_y then
highest_y = y
elseif y < lowest_y then
lowest_y = y
end
end
end
points[#points+1] = {x, y}
highest_x = highest_x - lowest_x + 1
highest_y = highest_y - lowest_y + 1
for k, v in ipairs(points) do
v[1] = v[1] - lowest_x + 1
v[2] = v[2] - lowest_y + 1
end
return highest_x, highest_y, points
end
function render_text_mode()
local width, height, points = render(dragon(), 1, 1, 1)
local rows = {}
for i=1,height do
rows[i] = {}
for j=1,width do
rows[i][j] = ' '
end
end
for k, v in ipairs(points) do
rows[v[2]][v[1]] = "*"
end
for i=1,height do
print(table.concat(rows[i], ""))
end
end
function dump_points()
local width, height, points = render(dragon(), 4, 4, 1)
for k, v in ipairs(points) do
print(unpack(v))
end
end
--replace this line with dump_points() to output a list of coordinates:
render_text_mode() |
http://rosettacode.org/wiki/Display_a_linear_combination | Display a linear combination | Task
Display a finite linear combination in an infinite vector basis
(
e
1
,
e
2
,
…
)
{\displaystyle (e_{1},e_{2},\ldots )}
.
Write a function that, when given a finite list of scalars
(
α
1
,
α
2
,
…
)
{\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )}
,
creates a string representing the linear combination
∑
i
α
i
e
i
{\displaystyle \sum _{i}\alpha ^{i}e_{i}}
in an explicit format often used in mathematics, that is:
α
i
1
e
i
1
±
|
α
i
2
|
e
i
2
±
|
α
i
3
|
e
i
3
±
…
{\displaystyle \alpha ^{i_{1}}e_{i_{1}}\pm |\alpha ^{i_{2}}|e_{i_{2}}\pm |\alpha ^{i_{3}}|e_{i_{3}}\pm \ldots }
where
α
i
k
≠
0
{\displaystyle \alpha ^{i_{k}}\neq 0}
The output must comply to the following rules:
don't show null terms, unless the whole combination is null.
e(1) is fine, e(1) + 0*e(3) or e(1) + 0 is wrong.
don't show scalars when they are equal to one or minus one.
e(3) is fine, 1*e(3) is wrong.
don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction.
e(4) - e(5) is fine, e(4) + -e(5) is wrong.
Show here output for the following lists of scalars:
1) 1, 2, 3
2) 0, 1, 2, 3
3) 1, 0, 3, 4
4) 1, 2, 0
5) 0, 0, 0
6) 0
7) 1, 1, 1
8) -1, -1, -1
9) -1, -2, 0, -3
10) -1
| #11l | 11l | F linear(x)
V a = enumerate(x).filter2((i, v) -> v != 0).map2((i, v) -> ‘#.e(#.)’.format(I v == -1 {‘-’} E I v == 1 {‘’} E String(v)‘*’, i + 1))
R (I !a.empty {a} E [String(‘0’)]).join(‘ + ’).replace(‘ + -’, ‘ - ’)
L(x) [[1, 2, 3], [0, 1, 2, 3], [1, 0, 3, 4], [1, 2, 0], [0, 0, 0], [0], [1, 1, 1], [-1, -1, -1], [-1, -2, 0, 3], [-1]]
print(linear(x)) |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #6502_Assembly | 6502 Assembly | with Ada.Text_Io; use Ada.Text_Io;
generic
SortName : in String;
type DataType is (<>);
type SortArrayType is array (Integer range <>) of DataType;
with procedure Sort (SortArray : in out SortArrayType;
Comp, Write, Ex : in out Natural);
package Instrument is
-- This generic package essentially accomplishes turning the sort
-- procedures into first-class functions for this limited purpose.
-- Obviously it doesn't change the way that Ada works with them;
-- the same thing would have been much more straightforward to
-- program in a language that had true first-class functions
package Dur_Io is new Fixed_Io(Duration);
procedure TimeSort (Arr : in out SortArrayType);
procedure Put;
procedure Put (File : in out File_Type);
end Instrument; |
http://rosettacode.org/wiki/Diversity_prediction_theorem | Diversity prediction theorem | The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other.
Thus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.
Scott E. Page introduced the diversity prediction theorem:
The squared error of the collective prediction equals the average squared error minus the predictive diversity.
Therefore, when the diversity in a group is large, the error of the crowd is small.
Definitions
Average Individual Error: Average of the individual squared errors
Collective Error: Squared error of the collective prediction
Prediction Diversity: Average squared distance from the individual predictions to the collective prediction
Diversity Prediction Theorem: Given a crowd of predictive models, then
Collective Error = Average Individual Error ─ Prediction Diversity
Task
For a given true value and a number of number of estimates (from a crowd), show (here on this page):
the true value and the crowd estimates
the average error
the crowd error
the prediction diversity
Use (at least) these two examples:
a true value of 49 with crowd estimates of: 48 47 51
a true value of 49 with crowd estimates of: 48 47 51 42
Also see
Wikipedia entry: Wisdom of the crowd
University of Michigan: PDF paper (exists on a web archive, the Wayback Machine).
| #11l | 11l | F average_square_diff(a, predictions)
R sum(predictions.map(x -> (x - @a) ^ 2)) / predictions.len
F diversity_theorem(truth, predictions)
V average = sum(predictions) / predictions.len
print(‘average-error: ’average_square_diff(truth, predictions)"\n"‘’
‘crowd-error: ’((truth - average) ^ 2)"\n"‘’
‘diversity: ’average_square_diff(average, predictions))
diversity_theorem(49.0, [Float(48), 47, 51])
diversity_theorem(49.0, [Float(48), 47, 51, 42]) |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #Python | Python | import math
shades = ('.',':','!','*','o','e','&','#','%','@')
def normalize(v):
len = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)
return (v[0]/len, v[1]/len, v[2]/len)
def dot(x,y):
d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
return -d if d < 0 else 0
def draw_sphere(r, k, ambient, light):
for i in range(int(math.floor(-r)),int(math.ceil(r)+1)):
x = i + 0.5
line = ''
for j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)):
y = j/2 + 0.5
if x*x + y*y <= r*r:
vec = normalize((x,y,math.sqrt(r*r - x*x - y*y)))
b = dot(light,vec)**k + ambient
intensity = int((1-b)*(len(shades)-1))
line += shades[intensity] if 0 <= intensity < len(shades) else shades[0]
else:
line += ' '
print(line)
light = normalize((30,30,-50))
draw_sphere(20,4,0.1, light)
draw_sphere(10,2,0.4, light) |
http://rosettacode.org/wiki/Draw_a_clock | Draw a clock | Task
Draw a clock.
More specific:
Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be drawn; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK.
The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock.
A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task.
A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language.
Key points
animate simple object
timed event
polling system resources
code clarity
| #Red | Red | Red [Needs: 'View]
view [t: h4 rate 1 on-time [t/data: now/time]]
|
http://rosettacode.org/wiki/Distributed_programming | Distributed programming | Write two programs (or one program with two modes) which run on networked computers, and send some messages between them.
The protocol used may be language-specific or not, and should be suitable for general distributed programming; that is, the protocol should be generic (not designed just for the particular example application), readily capable of handling the independent communications of many different components of a single application, and the transferring of arbitrary data structures natural for the language.
This task is intended to demonstrate high-level communication facilities beyond just creating sockets.
| #Ada | Ada | package Server is
pragma Remote_Call_Interface;
procedure Foo;
function Bar return Natural;
end Server; |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with GNAT.Sockets; use GNAT.Sockets;
procedure DNSQuerying is
Host : Host_Entry_Type (1, 1);
Inet_Addr_V4 : Inet_Addr_Type (Family_Inet);
begin
Host := Get_Host_By_Name (Name => "www.kame.net");
Inet_Addr_V4 := Addresses (Host);
Put ("IPv4: " & Image (Value => Inet_Addr_V4));
end DNSQuerying; |
http://rosettacode.org/wiki/Draw_a_cuboid | Draw a cuboid | Task
Draw a cuboid with relative dimensions of 2 × 3 × 4.
The cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.
To fulfill the criteria of being a cuboid, three faces must be visible.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a sphere
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
real X, Y, Z, Farthest; \arrays: 3D coordinates of vertices
int I, J, K, SI, Segment;
def Size=50.0, Sz=0.008, Sx=-0.013; \drawing size and tumbling speeds
[X:= [-2.0, +2.0, +2.0, -2.0, -2.0, +2.0, +2.0, -2.0];
Y:= [-1.5, -1.5, +1.5, +1.5, -1.5, -1.5, +1.5, +1.5];
Z:= [-1.0, -1.0, -1.0, -1.0, +1.0, +1.0, +1.0, +1.0];
Segment:= [0,1, 1,2, 2,3, 3,0, 4,5, 5,6, 6,7, 7,4, 0,4, 1,5, 2,6, 3,7];
SetVid($101); \set 640x480 graphics with 256 colors
repeat Farthest:= 0.0; \find the farthest vertex
for I:= 0 to 8-1 do
if Z(I) > Farthest then [Farthest:= Z(I); SI:= I];
Clear; \erase screen
for I:= 0 to 2*12-1 do \for all the vertices...
[J:= Segment(I); I:= I+1; \get vertex number
Move(fix(X(J)*Size)+640/2, fix(Y(J)*Size)+480/2);
K:= Segment(I);
Line(fix(X(K)*Size)+640/2, fix(Y(K)*Size)+480/2,
if J=SI ! K=SI then $F009 \dashed blue\ else $C \red\);
];
Sound(0, 1, 1); \delay 1/18 second to prevent flicker
for I:= 0 to 8-1 do
[X(I):= X(I) + Y(I)*Sz; \rotate vertices in X-Y plane
Y(I):= Y(I) - X(I)*Sz;
Y(I):= Y(I) + Z(I)*Sx; \rotate vertices in Y-Z plane
Z(I):= Z(I) - Y(I)*Sx;
];
until KeyHit; \run until a key is struck
SetVid(3); \restore normal text mode (for DOS)
] |
http://rosettacode.org/wiki/Draw_a_cuboid | Draw a cuboid | Task
Draw a cuboid with relative dimensions of 2 × 3 × 4.
The cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.
To fulfill the criteria of being a cuboid, three faces must be visible.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a sphere
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #zkl | zkl | var [const] M=50.0;
fcn cuboid(w,h,z){
w*=M; h*=M; z*=M; // relative to abs dimensions
bitmap:=PPM(400,400);
clr:=0xff0000; // red facing rectangle
bitmap.line(0,0, w,0, clr); bitmap.line(0,0, 0,h, clr);
bitmap.line(0,h, w,h, clr); bitmap.line(w,0, w,h, clr);
r,a:=(w+z).toFloat().toPolar(0); // relative to the origin
a,b:=r.toRectangular((30.0).toRad() + a).apply("toInt"); c:=a; d:=b+h;
clr=0xff; // blue right side of cuboid
bitmap.line(w,0, a,b, clr); bitmap.line(a,b, c,d, clr);
bitmap.line(w,h, c,d, clr);
e:=c-w;
clr=0xfff00; // green top of cuboid
bitmap.line(0,h, e,d, clr); bitmap.line(c,d, e,d, clr);
bitmap.write(File("foo.ppm","wb"));
}(2,3,4); |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right.
*---R----* expands to * *
\ /
R L
\ /
*
*
/ \
L R
/ \
*---L---* expands to * *
The co-routines dcl and dcr in various examples do this recursively to a desired expansion level.
The curl direction right or left can be a parameter instead of two separate routines.
Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees.
*------->* becomes * * Recursive copies drawn
\ / from the ends towards
\ / the centre.
v v
*
This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen.
Successive approximation repeatedly re-writes each straight line as two new segments at a right angle,
*
*-----* becomes / \ bend to left
/ \ if N odd
* *
* *
*-----* becomes \ / bend to right
\ / if N even
*
Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing.
The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this.
Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently.
n = 1010110000
^
bit above lowest 1-bit, turn left or right as 0 or 1
LowMask = n BITXOR (n-1) # eg. giving 0000011111
AboveMask = LowMask + 1 # eg. giving 0000100000
BitAboveLowestOne = n BITAND AboveMask
The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there.
If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is.
Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction.
If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1.
Absolute direction to move at point n can be calculated by the number of bit-transitions in n.
n = 11 00 1111 0 1
^ ^ ^ ^ 4 places where change bit value
so direction=4*90degrees=East
This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ.
Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently.
Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this.
A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.)
The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section.
As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code.
Axiom F, angle 90 degrees
F -> F+S
S -> F-S
This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page.
Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around.
The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
| #M2000_Interpreter | M2000 Interpreter |
Module Checkit {
def double angle, d45, d90, change=5000
const sr2 as double= .70710676237
Cls 0
Pen 14
\\ move console full screen to second monitor
Window 12, 1
\\ reduce size (tv as second monitor cut pixels from edges)
Window 12, scale.x*.9, scale.y*.9;
\\ opacity 100%, but for 0 (black is 100%, and we can hit anything under console window)
Desktop 255, 0
\\ M2000 console can divide screen to characters/lines with automatic line space
Form 60, 30
\\ cut the border from window
Form
\\ scale.x and scale.y in twips
\\ all graphic/console commands works for printer also (except for Input)
Move scale.x/2,scale.y/10
\\ outline graphics, here outline text
\\ legend text$, font, size, angle, justify(2 for center), quality (non zero for antialiasing, works for angle 0), letter spacing.
Color {
Legend "DRAGON CURVE", "Courier",SCALE.Y/200,0,2, 1, SCALE.X/50
}
angle=0
d45=pi/4
d90=pi/2
Move scale.x/3, scale.y*2/3
bck=point
\\ twipsx is width in twips of pixel. twipsy are height in twips of a pixel
\\ so we use length:twips.x*scale.x/40 or scale.x/40 pixels.
\\ use % for integer - we can omit these, and we get integer by automatic conversion (overflow raise error)
dragon(twipsx*scale.x/40,14%, 1)
Pen 14
a$=key$
Cls 5
\\ set opacity to 100%
Desktop 255
End
\\ Subs are private to this module
\\ Subs have same scope as module
Sub turn(rand as double)
angle+=rand
End Sub
\\ angle is absolute, length is relative
Sub forward(length as double)
Draw Angle angle, length
End Sub
Sub dragon(length as double, split as integer, d as double)
If split=0 then {
forward(length)
} else {
Gosub turn(d*d45)
\\ we can omit Gosub
dragon(length*sr2,split-1,1)
turn(-d*d90)
dragon(length*sr2,split-1,-1)
turn(d*d45)
change--
If change else {
push 0: do {drop: push random(11,15) : over } until number<>pen: pen number
change=5000
}
}
End Sub
}
Checkit
|
http://rosettacode.org/wiki/Display_a_linear_combination | Display a linear combination | Task
Display a finite linear combination in an infinite vector basis
(
e
1
,
e
2
,
…
)
{\displaystyle (e_{1},e_{2},\ldots )}
.
Write a function that, when given a finite list of scalars
(
α
1
,
α
2
,
…
)
{\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )}
,
creates a string representing the linear combination
∑
i
α
i
e
i
{\displaystyle \sum _{i}\alpha ^{i}e_{i}}
in an explicit format often used in mathematics, that is:
α
i
1
e
i
1
±
|
α
i
2
|
e
i
2
±
|
α
i
3
|
e
i
3
±
…
{\displaystyle \alpha ^{i_{1}}e_{i_{1}}\pm |\alpha ^{i_{2}}|e_{i_{2}}\pm |\alpha ^{i_{3}}|e_{i_{3}}\pm \ldots }
where
α
i
k
≠
0
{\displaystyle \alpha ^{i_{k}}\neq 0}
The output must comply to the following rules:
don't show null terms, unless the whole combination is null.
e(1) is fine, e(1) + 0*e(3) or e(1) + 0 is wrong.
don't show scalars when they are equal to one or minus one.
e(3) is fine, 1*e(3) is wrong.
don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction.
e(4) - e(5) is fine, e(4) + -e(5) is wrong.
Show here output for the following lists of scalars:
1) 1, 2, 3
2) 0, 1, 2, 3
3) 1, 0, 3, 4
4) 1, 2, 0
5) 0, 0, 0
6) 0
7) 1, 1, 1
8) -1, -1, -1
9) -1, -2, 0, -3
10) -1
| #Ada | Ada | with Ada.Text_Io;
with Ada.Strings.Unbounded;
with Ada.Strings.Fixed;
procedure Display_Linear is
subtype Position is Positive;
type Coefficient is new Integer;
type Combination is array (Position range <>) of Coefficient;
function Linear_Combination (Comb : Combination) return String is
use Ada.Strings.Unbounded;
use Ada.Strings;
Accu : Unbounded_String;
begin
for Pos in Comb'Range loop
case Comb (Pos) is
when Coefficient'First .. -1 =>
Append (Accu, (if Accu = "" then "-" else " - "));
when 0 => null;
when 1 .. Coefficient'Last =>
Append (Accu, (if Accu /= "" then " + " else ""));
end case;
if Comb (Pos) /= 0 then
declare
Abs_Coeff : constant Coefficient := abs Comb (Pos);
Coeff_Image : constant String := Fixed.Trim (Coefficient'Image (Abs_Coeff), Left);
Exp_Image : constant String := Fixed.Trim (Position'Image (Pos), Left);
begin
if Abs_Coeff /= 1 then
Append (Accu, Coeff_Image & "*");
end if;
Append (Accu, "e(" & Exp_Image & ")");
end;
end if;
end loop;
return (if Accu = "" then "0" else To_String (Accu));
end Linear_Combination;
use Ada.Text_Io;
begin
Put_Line (Linear_Combination ((1, 2, 3)));
Put_Line (Linear_Combination ((0, 1, 2, 3)));
Put_Line (Linear_Combination ((1, 0, 3, 4)));
Put_Line (Linear_Combination ((1, 2, 0)));
Put_Line (Linear_Combination ((0, 0, 0)));
Put_Line (Linear_Combination ((1 => 0)));
Put_Line (Linear_Combination ((1, 1, 1)));
Put_Line (Linear_Combination ((-1, -1, -1)));
Put_Line (Linear_Combination ((-1, -2, 0, -3)));
Put_Line (Linear_Combination ((1 => -1)));
end Display_Linear; |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Ada | Ada | with Ada.Text_Io; use Ada.Text_Io;
generic
SortName : in String;
type DataType is (<>);
type SortArrayType is array (Integer range <>) of DataType;
with procedure Sort (SortArray : in out SortArrayType;
Comp, Write, Ex : in out Natural);
package Instrument is
-- This generic package essentially accomplishes turning the sort
-- procedures into first-class functions for this limited purpose.
-- Obviously it doesn't change the way that Ada works with them;
-- the same thing would have been much more straightforward to
-- program in a language that had true first-class functions
package Dur_Io is new Fixed_Io(Duration);
procedure TimeSort (Arr : in out SortArrayType);
procedure Put;
procedure Put (File : in out File_Type);
end Instrument; |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Arturo | Arturo | f: function [x :integer, y :integer][
;; description: « takes two integers and adds them up
;; options: [
;; double: « also multiply by two
;; ]
;; returns: :integer
result: x+y
if not? null? attr 'double -> result: result * 2
return result
]
info'f |
http://rosettacode.org/wiki/Diversity_prediction_theorem | Diversity prediction theorem | The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other.
Thus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.
Scott E. Page introduced the diversity prediction theorem:
The squared error of the collective prediction equals the average squared error minus the predictive diversity.
Therefore, when the diversity in a group is large, the error of the crowd is small.
Definitions
Average Individual Error: Average of the individual squared errors
Collective Error: Squared error of the collective prediction
Prediction Diversity: Average squared distance from the individual predictions to the collective prediction
Diversity Prediction Theorem: Given a crowd of predictive models, then
Collective Error = Average Individual Error ─ Prediction Diversity
Task
For a given true value and a number of number of estimates (from a crowd), show (here on this page):
the true value and the crowd estimates
the average error
the crowd error
the prediction diversity
Use (at least) these two examples:
a true value of 49 with crowd estimates of: 48 47 51
a true value of 49 with crowd estimates of: 48 47 51 42
Also see
Wikipedia entry: Wisdom of the crowd
University of Michigan: PDF paper (exists on a web archive, the Wayback Machine).
| #Ada | Ada | with Ada.Text_IO;
with Ada.Command_Line;
procedure Diversity_Prediction is
type Real is new Float;
type Real_Array is array (Positive range <>) of Real;
package Real_IO is new Ada.Text_Io.Float_IO (Real);
use Ada.Text_IO, Ada.Command_Line, Real_IO;
function Mean (Data : Real_Array) return Real is
Sum : Real := 0.0;
begin
for V of Data loop
Sum := Sum + V;
end loop;
return Sum / Real (Data'Length);
end Mean;
function Variance (Reference : Real; Data : Real_Array) return Real is
Res : Real_Array (Data'Range);
begin
for A in Data'Range loop
Res (A) := (Reference - Data (A)) ** 2;
end loop;
return Mean (Res);
end Variance;
procedure Diversity (Truth : Real; Estimates : Real_Array)
is
Average : constant Real := Mean (Estimates);
Average_Error : constant Real := Variance (Truth, Estimates);
Crowd_Error : constant Real := (Truth - Average) ** 2;
Diversity : constant Real := Variance (Average, Estimates);
begin
Real_IO.Default_Exp := 0;
Real_IO.Default_Aft := 5;
Put ("average-error : "); Put (Average_Error); New_Line;
Put ("crowd-error : "); Put (Crowd_Error); New_Line;
Put ("diversity : "); Put (Diversity); New_Line;
end Diversity;
begin
if Argument_Count <= 1 then
Put_Line ("Usage: diversity_prediction <truth> <data_1> <data_2> ...");
return;
end if;
declare
Truth : constant Real := Real'Value (Argument (1));
Estimates : Real_Array (2 .. Argument_Count);
begin
for A in 2 .. Argument_Count loop
Estimates (A) := Real'Value (Argument (A));
end loop;
Diversity (Truth, Estimates);
end;
end Diversity_Prediction; |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #Racket | Racket |
#lang typed/racket
(require plot/typed)
(plot3d (polar3d (λ (θ ρ) 1)) #:altitude 25)
|
http://rosettacode.org/wiki/Draw_a_clock | Draw a clock | Task
Draw a clock.
More specific:
Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be drawn; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK.
The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock.
A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task.
A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language.
Key points
animate simple object
timed event
polling system resources
code clarity
| #REXX | REXX | /*REXX program displays the current (local) time as a digital clock on the terminal.*/
trace off /*turn off tracing/possible host errors*/
parse arg ! /*obtain optional arguments from the CL*/
if !all(arg()) then exit /*was there a request for some help? */
if !cms then address '' /*If CMS, then initialize ADDRESS name*/
signal on halt /*initialize target label when HALTed. */
signal on noValue /* " " " " noValue.*/
signal on syntax /* " " " " syntax. */
parse var ! ops /*obtain optional arguments from the CL*/
ops = space(ops) /*elide superfluous blanks from options*/
blinkSecs = 1 /*amount of time between displays. */
creep = 1 /*moves the output "around" the screen.*/
tops = '.C=blue .BC=░ .BS=1 .BLOCK=12' /*options to be specified for $T.REXX */
do while ops\=='' /*process all the specified options. */
parse var ops _1 2 1 _ . 1 y ops /*extract various information from opt.*/
upper _ /*uppercase the _ REXX variavle. */
select
when _==',' then nop /*ignore any comma used.*/
when _1==. & pos("=",_)\==0 then tops= tops y /*add this value to TOPS*/
when abbn('BLINKSECs') then blinksecs= no() /*use/not use BLINKSECs.*/
when abbn('CREEPs') then creep= no() /* " " " CREEPs. */
otherwise call er 55,y /*whoops! Invalid option*/
end /*select*/
end /*while ops¬==''*/
if \!pcrexx then blinkSecs= 0 /*Not PC/REXX? Then turn off BLINKSECS*/
tops= space(tops) /*elide superfluous blanks in TOPS. */
parse value scrsize() with sd sw . /*obtain the terminal screen dimensions*/
oldTime= /*blank out the OLDTIME for comparison.*/
do until queued()\==0 /*if user entered some text, then QUIT.*/
ct= time() /*obtain the current (system) time. */
mn= substr(ct, 4, 2) /*extract the minutes part of the time.*/
ss= right(ct, 2) /* " " seconds " " " " */
i_= 0 /*REXX variable used for display creep.*/
p_= 0 /* " " " " " " */
call blinksec
if ct==oldTime then if !cms then 'CP SLEEP' /*sleep for one second. */
else call delay 1 /* " " " " */
if creep then do; p_ = 3 + right(mn, 1) /*perform display creep.*/
if sd>26 then p_ = p_ + left(mn, 1)
if sd>33 then p_ = p_ + left(mn, 1)
if sd>44 then p_ = p_ + left(mn, 1) + right(mn, 1)
end
_p= - p_ /*change the sign of the P_ number. */
i_= 2 + left(ct, 1) /*obtain indentation size base on HH. */
if sw>108 then ctt= ct /*maybe use wider format for the clock*/
else ctt= left(ct, 5) /*maybe use narrow " " " " */
r= $t('.P='_p ".I="i_ tops ctt) /*where the rubber meets the road. */
if r\==0 then leave /*Had an error in $T ? Then quit. */
oldTime= time() /*save the new time, it may be the same*/
end /*forever*/
exit 0 /*stick a fork in it, we're all done. */
/*═════════════════════════════general 1-line subs══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════*/
!all: !!=!;!=space(!);upper !;call !fid;!nt=right(!var('OS'),2)=='NT';!cls=word('CLS VMFCLEAR CLRSCREEN',1+!cms+!tso*2);if arg(1)\==1 then return 0;if wordpos(!,'? ?SAMPLES ?AUTHOR ?FLOW')==0 then return 0;!call=']$H';call '$H' !fn !;!call=;return 1
!cal: if symbol('!CALL')\=="VAR" then !call=; return !call
!env: !env= 'ENVIRONMENT'; if !sys=="MSDOS" | !brexx | !r4 | !roo then !env= 'SYSTEM'; if !os2 then !env= "OS2"!env; !ebcdic= 3=='f3'x; if !crx then !env= "DOS"; return
!fid: parse upper source !sys !fun !fid . 1 . . !fn !ft !fm .; call !sys; if !dos then do; _= lastpos('\', !fn); !fm= left(!fn, _); !fn= substr(!fn, _+1); parse var !fn !fn '.' !ft; end; return word(0 !fn !ft !fm, 1 +('0'arg(1)))
!rex: parse upper version !ver !vernum !verdate .; !brexx= 'BY'==!vernum; !kexx= "KEXX"==!ver; !pcrexx= 'REXX/PERSONAL'==!ver | "REXX/PC"==!ver; !r4= 'REXX-R4'==!ver; !regina="REXX-REGINA"==left(!ver, 11); !roo='REXX-ROO'==!ver; call !env; return
!sys: !cms= !sys=='CMS'; !os2= !sys=="OS2"; !tso= !sys=='TSO' | !sys=="MVS"; !vse= !sys=='VSE'; !dos= pos("DOS", !sys)\==0 | pos('WIN', !sys)\==0 | !sys=="CMD"; !crx= left(!sys, 6)=='DOSCRX'; call !rex; return
!var: call !fid; if !kexx then return space( dosenv( arg(1) ) ); return space( value( arg(1), , !env))
$t: !call= ']$T'; call "$T" arg(1); !call=; return result
abb: parse upper arg abbu; parse arg abb; return abbrev(abbu, _, abbl(abb) )
abbl: @abc = 'abcdefghijklmnopqrstuvwxyz'; return verify(arg(1)'a', @abc, 'M') - 1
abbn: parse arg abbn; return abb(abbn) | abb('NO'abbn)
blinksec: if \blinksecs then return; bsec= ' '; ss2= right(ss, 2); if sw<=80 then bsec= copies(" ", 2 + ss2) ss2; call scrwrite 1 + right(mn, 1), 1, bsec, , , 1; call cursor sd - right(mn, 1), sw - length(bsec); return
er: parse arg _1,_2; call '$ERR' "14"p(_1) p(word(_1, 2) !fid(1)) _2; if _1<0 then return _1; exit result
err: call er '-'arg(1),arg(2); return ''
erx: call er '-'arg(1),arg(2); exit 0
halt: call er .1
no: if arg(1)\=='' then call er 01,arg(2); return left(_, 2) \== 'NO'
noValue: !sigl= sigl; call er 17,!fid(2) !fid(3) !sigl condition('D') sourceline(!sigl)
p: return word( arg(1), 1)
syntax: !sigl= sigl; call er 13,!fid(2) !fid(3) !sigl !cal() condition('D') sourceline(!sigl) |
http://rosettacode.org/wiki/Distributed_programming | Distributed programming | Write two programs (or one program with two modes) which run on networked computers, and send some messages between them.
The protocol used may be language-specific or not, and should be suitable for general distributed programming; that is, the protocol should be generic (not designed just for the particular example application), readily capable of handling the independent communications of many different components of a single application, and the transferring of arbitrary data structures natural for the language.
This task is intended to demonstrate high-level communication facilities beyond just creating sockets.
| #AutoHotkey | AutoHotkey | #include <stdio.h>
#include <stdlib.h>
#include <pvm3.h>
int main(int c, char **v)
{
int tids[10];
int parent, spawn;
int i_data, i2;
double f_data;
if (c > 1) {
spawn = pvm_spawn("/tmp/a.out", 0, PvmTaskDefault, 0, 1, tids);
if (spawn <= 0) {
printf("Can't spawn task\n");
return 1;
}
printf("Spawning successful\n");
/* pvm_recv(task_id, msgtag). msgtag identifies what kind of data it is,
* for here: 1 = (int, double), 2 = (int, int)
* The receiving order is intentionally swapped, just to show.
* task_id = -1 means "receive from any task"
*/
pvm_recv(-1, 2);
pvm_unpackf("%d %d", &i_data, &i2);
printf("got msg type 2: %d %d\n", i_data, i2);
pvm_recv(-1, 1);
pvm_unpackf("%d %lf", &i_data, &f_data);
printf("got msg type 1: %d %f\n", i_data, f_data);
} else {
parent = pvm_parent();
pvm_initsend(PvmDataDefault);
i_data = rand();
f_data = (double)rand() / RAND_MAX;
pvm_packf("%d %lf", i_data, f_data);
pvm_send(parent, 1); /* send msg type 1 */
pvm_initsend(PvmDataDefault);
i2 = rand();
pvm_packf("%d %d", i_data, i2);
pvm_send(parent, 2); /* send msg type 2 */
}
pvm_exit();
return 0;
} |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program dnsquery.s */
/************************************/
/* Constantes */
/************************************/
.equ STDIN, 0 @ Linux input console
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall END PROGRAM
.equ FORK, 2 @ Linux syscall
.equ READ, 3 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
.equ OPEN, 5 @ Linux syscall
.equ CLOSE, 6 @ Linux syscall
.equ EXECVE, 0xB @ Linux syscall
.equ PIPE, 0x2A @ Linux syscall
.equ DUP2, 0x3F @ Linux syscall
.equ WAIT4, 0x72 @ Linux syscall
.equ WUNTRACED, 2 @ Wait, return status of stopped child
.equ TAILLEBUFFER, 500
/*********************************/
/* Initialized data */
/*********************************/
.data
szCarriageReturn: .asciz "\n"
szMessFinOK: .asciz "Fin normale du programme. \n"
szMessError: .asciz "Error occured !!!"
szCommand: .asciz "/usr/bin/host" @ command host
szNameHost: .asciz "www.kame.net" @ string query name
.align 4
stArg1: .int szCommand @ address command
.int szNameHost @ address argument
.int 0,0 @ zeroes
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
.align 4
iStatusThread: .skip 4
pipefd: .skip 8
sBuffer: .skip TAILLEBUFFER
stRusage: .skip TAILLEBUFFER
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
/* création pipe */
ldr r0,iAdrpipefd @ FDs address
mov r7, #PIPE @ create pipe
svc 0 @ call system Linux
cmp r0,#0 @ error ?
blt 99f
/* create child thread */
mov r0,#0
mov r7, #FORK @ call system
svc #0
cmp r0,#0 @ error ?
blt 99f
bne parent @ if <> zero r0 contains father pid
@ else is the child
/****************************************/
/* Child thread */
/****************************************/
/* redirection sysout -> pipe */
ldr r0,iAdrpipefd
ldr r0,[r0,#4]
mov r7, #DUP2 @ call system linux
mov r1, #STDOUT @
svc #0
cmp r0,#0 @ error ?
blt 99f
/* run command host */
ldr r0, iAdrszCommand @ r0 = address de "/usr/bin/host"
ldr r1,iAdrstArg1 @ address argument 1
mov r2,#0
mov r7, #EXECVE @ call system linux (execve)
svc #0 @ if ok -> no return !!!
b 100f @ never exec this label
/****************************************/
/* Father thread */
/****************************************/
parent:
mov r4,r0 @ save child pid
1: @ loop child signal
mov r0,r4
ldr r1,iAdriStatusThread @ return status thread
mov r2,#WUNTRACED @ flags
ldr r3,iAdrstRusage @ return structure thread
mov r7, #WAIT4 @ Call System
svc #0
cmp r0,#0 @ error ?
blt 99f
@ recup status
ldr r0,iAdriStatusThread @ analyse status
ldrb r0,[r0] @ firest byte
cmp r0,#0 @ normal end thread ?
bne 1b @ loop
/* close entry pipe */
ldr r0,iAdrpipefd
mov r7,#CLOSE @ call system
svc #0
/* read datas pipe */
ldr r0,iAdrpipefd
ldr r0,[r0]
ldr r1,iAdrsBuffer @ buffer address
mov r2,#TAILLEBUFFER @ buffer size
mov r7, #READ @ call system
svc #0
ldr r0,iAdrsBuffer @ display buffer
bl affichageMess
ldr r0,iAdrszMessFinOK @ display message Ok
bl affichageMess
mov r0, #0 @ return code
b 100f
99:
ldr r0,iAdrszMessError @ erreur
bl affichageMess
mov r0, #1 @ return code
b 100f
100: @ standard end of the program
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
iAdrszMessFinOK: .int szMessFinOK
iAdrszMessError: .int szMessError
iAdrsBuffer: .int sBuffer
iAdrpipefd: .int pipefd
iAdrszCommand: .int szCommand
iAdrstArg1: .int stArg1
iAdriStatusThread: .int iStatusThread
iAdrstRusage: .int stRusage
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registres
mov r2,#0 @ counter length
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call systeme
pop {r0,r1,r2,r7,lr} @ restaur des 2 registres */
bx lr @ return
|
http://rosettacode.org/wiki/Draw_a_cuboid | Draw a cuboid | Task
Draw a cuboid with relative dimensions of 2 × 3 × 4.
The cuboid can be represented graphically, or in ASCII art, depending on the language capabilities.
To fulfill the criteria of being a cuboid, three faces must be visible.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a sphere
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 LET width=50: LET height=width*1.5: LET depth=width*2
20 LET x=80: LET y=10
30 PLOT x,y
40 DRAW 0,height: DRAW width,0: DRAW 0,-height: DRAW -width,0: REM Front
50 PLOT x,y+height: DRAW depth/2,height: DRAW width,0: DRAW 0,-height: DRAW -width,-height
60 PLOT x+width,y+height: DRAW depth/2,height |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right.
*---R----* expands to * *
\ /
R L
\ /
*
*
/ \
L R
/ \
*---L---* expands to * *
The co-routines dcl and dcr in various examples do this recursively to a desired expansion level.
The curl direction right or left can be a parameter instead of two separate routines.
Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees.
*------->* becomes * * Recursive copies drawn
\ / from the ends towards
\ / the centre.
v v
*
This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen.
Successive approximation repeatedly re-writes each straight line as two new segments at a right angle,
*
*-----* becomes / \ bend to left
/ \ if N odd
* *
* *
*-----* becomes \ / bend to right
\ / if N even
*
Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing.
The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this.
Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently.
n = 1010110000
^
bit above lowest 1-bit, turn left or right as 0 or 1
LowMask = n BITXOR (n-1) # eg. giving 0000011111
AboveMask = LowMask + 1 # eg. giving 0000100000
BitAboveLowestOne = n BITAND AboveMask
The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there.
If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is.
Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction.
If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1.
Absolute direction to move at point n can be calculated by the number of bit-transitions in n.
n = 11 00 1111 0 1
^ ^ ^ ^ 4 places where change bit value
so direction=4*90degrees=East
This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ.
Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently.
Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this.
A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.)
The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section.
As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code.
Axiom F, angle 90 degrees
F -> F+S
S -> F-S
This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page.
Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around.
The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
| #M4 | M4 | # The macros which return a pair of values x,y expand to an unquoted 123,456
# which is suitable as arguments to a further macro. The quoting is slack
# because the values are always integers and so won't suffer unwanted macro
# expansion.
# 0,1 Vertex and segment x,y numbering.
# |
# | Segments are numbered as if a
# |s=0,1 square grid turned anti-clockwise
# | by 45 degrees.
# |
# -1,0 -------- 0,0 -------- 1,0 vertex_to_seg_east(x,y) returns
# s=-1,1 | s=0,0 the segment x,y to the East,
# | so vertex_to_seg_east(0,0) is 0,0
# |
# |s=-1,0 vertex_to_seg_west(x,y) returns
# | the segment x,y to the West,
# 0,-1 so vertex_to_seg_west(0,0) is -1,1
#
define(`vertex_to_seg_east', `eval($1 + $2), eval($2 - $1)')
define(`vertex_to_seg_west', `eval($1 + $2 - 1), eval($2 - $1 + 1)')
define(`vertex_to_seg_south', `eval($1 + $2 - 1), eval($2 - $1)')
# Some past BSD m4 didn't have "&" operator, so mod2(n) using % instead.
# mod2() returns 0,1 even if "%" gives -1 for negative odds.
#
define(`mod2', `ifelse(eval($1 % 2),0,0,1)')
# seg_to_even(x,y) returns x,y moved to an "even" position by subtracting an
# offset in a way which suits the segment predicate test.
#
# seg_offset_y(x,y) is a repeating pattern
#
# | 1,1,0,0
# | 1,1,0,0
# | 0,0,1,1
# | 0,0,1,1
# +---------
#
# seg_offset_x(x,y) is the same but offset by 1 in x,y
#
# | 0,1,1,0
# | 1,0,0,1
# | 1,0,0,1
# | 0,1,1,0
# +---------
#
# Incidentally these offset values also give n which is the segment number
# along the curve. "x_offset XOR y_offset" is 0,1 and is a bit of n from
# low to high.
#
define(`seg_offset_y', `mod2(eval(($1 >> 1) + ($2 >> 1)))')
define(`seg_offset_x', `seg_offset_y(eval($1+1), eval($2+1))')
define(`seg_to_even', `eval($1 - seg_offset_x($1,$2)),
eval($2 - seg_offset_y($1,$2))');
# xy_div_iplus1(x,y) returns x,y divided by complex number i+1.
# So (x+i*y)/(i+1) which means newx = (x+y)/2, newy = (y-x)/2.
# Must have x,y "even", meaning x+y even, so newx and newy are integers.
#
define(`xy_div_iplus1', `eval(($1 + $2)/2), eval(($2 - $1)/2)')
# seg_is_final(x,y) returns 1 if x,y is one of the final four points.
# On these four points xy_div_iplus1(seg_to_even(x,y)) returns x,y
# unchanged, so the seg_pred() recursion does not reduce any further.
#
# .. | ..
# final | final y=+1
# final | final y=0
# -------+--------
# .. | ..
# x=-1 x=0
#
define(`seg_is_final', `eval(($1==-1 || $1==0) && ($2==1 || $2==0))')
# seg_pred(x,y) returns 1 if segment x,y is on the dragon curve.
# If the final point reached is 0,0 then the original x,y was on the curve.
# (If a different final point then x,y was one of four rotated copies of the
# curve.)
#
define(`seg_pred', `ifelse(seg_is_final($1,$2), 1,
`eval($1==0 && $2==0)',
`seg_pred(xy_div_iplus1(seg_to_even($1,$2)))')')
# vertex_pred(x,y) returns 1 if point x,y is on the dragon curve.
# The curve always turns left or right at a vertex, it never crosses itself,
# so if a vertex is visited then either the segment to the east or to the
# west must have been traversed. Prefer ifelse() for the two checks since
# eval() || operator is not a short-circuit.
#
define(`vertex_pred', `ifelse(seg_pred(vertex_to_seg_east($1,$2)),1,1,
`seg_pred(vertex_to_seg_west($1,$2))')')
# forloop(varname, start,end, body)
# Expand body with varname successively define()ed to integers "start" to
# "end" inclusive. "start" to "end" can go either increasing or decreasing.
#
define(`forloop', `define(`$1',$2)$4`'dnl
ifelse($2,$3,,`forloop(`$1',eval($2 + 2*($2 < $3) - 1), $3, `$4')')')
#----------------------------------------------------------------------------
# dragon01(xmin,xmax, ymin,ymax) prints an array of 0s and 1s which are the
# vertex_pred() values. `y' runs from ymax down to ymin so that y
# coordinate increases up the screen.
#
define(`dragon01',
`forloop(`y',$4,$3, `forloop(`x',$1,$2, `vertex_pred(x,y)')
')')
# dragon_ascii(xmin,xmax, ymin,ymax) prints an ascii art dragon curve.
# Each y value results in two output lines. The first has "+" vertices and
# "--" horizontals. The second has "|" verticals.
#
define(`dragon_ascii',
`forloop(`y',$4,$3,
`forloop(`x',$1,$2,
`ifelse(vertex_pred(x,y),1, `+', ` ')dnl
ifelse(seg_pred(vertex_to_seg_east(x,y)), 1, `--', ` ')')
forloop(`x',$1,$2,
`ifelse(seg_pred(vertex_to_seg_south(x,y)), 1, `| ', ` ')')
')')
#--------------------------------------------------------------------------
divert`'dnl
# 0s and 1s directly from vertex_pred().
#
dragon01(-7,23, dnl X range
-11,10) dnl Y range
# ASCII art lines.
#
dragon_ascii(-6,5, dnl X range
-10,2) dnl Y range |
http://rosettacode.org/wiki/Display_a_linear_combination | Display a linear combination | Task
Display a finite linear combination in an infinite vector basis
(
e
1
,
e
2
,
…
)
{\displaystyle (e_{1},e_{2},\ldots )}
.
Write a function that, when given a finite list of scalars
(
α
1
,
α
2
,
…
)
{\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )}
,
creates a string representing the linear combination
∑
i
α
i
e
i
{\displaystyle \sum _{i}\alpha ^{i}e_{i}}
in an explicit format often used in mathematics, that is:
α
i
1
e
i
1
±
|
α
i
2
|
e
i
2
±
|
α
i
3
|
e
i
3
±
…
{\displaystyle \alpha ^{i_{1}}e_{i_{1}}\pm |\alpha ^{i_{2}}|e_{i_{2}}\pm |\alpha ^{i_{3}}|e_{i_{3}}\pm \ldots }
where
α
i
k
≠
0
{\displaystyle \alpha ^{i_{k}}\neq 0}
The output must comply to the following rules:
don't show null terms, unless the whole combination is null.
e(1) is fine, e(1) + 0*e(3) or e(1) + 0 is wrong.
don't show scalars when they are equal to one or minus one.
e(3) is fine, 1*e(3) is wrong.
don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction.
e(4) - e(5) is fine, e(4) + -e(5) is wrong.
Show here output for the following lists of scalars:
1) 1, 2, 3
2) 0, 1, 2, 3
3) 1, 0, 3, 4
4) 1, 2, 0
5) 0, 0, 0
6) 0
7) 1, 1, 1
8) -1, -1, -1
9) -1, -2, 0, -3
10) -1
| #C | C |
#include<stdlib.h>
#include<stdio.h>
#include<math.h> /*Optional, but better if included as fabs, labs and abs functions are being used. */
int main(int argC, char* argV[])
{
int i,zeroCount= 0,firstNonZero = -1;
double* vector;
if(argC == 1){
printf("Usage : %s <Vector component coefficients seperated by single space>",argV[0]);
}
else{
printf("Vector for [");
for(i=1;i<argC;i++){
printf("%s,",argV[i]);
}
printf("\b] -> ");
vector = (double*)malloc((argC-1)*sizeof(double));
for(i=1;i<=argC;i++){
vector[i-1] = atof(argV[i]);
if(vector[i-1]==0.0)
zeroCount++;
if(vector[i-1]!=0.0 && firstNonZero==-1)
firstNonZero = i-1;
}
if(zeroCount == argC){
printf("0");
}
else{
for(i=0;i<argC;i++){
if(i==firstNonZero && vector[i]==1)
printf("e%d ",i+1);
else if(i==firstNonZero && vector[i]==-1)
printf("- e%d ",i+1);
else if(i==firstNonZero && vector[i]<0 && fabs(vector[i])-abs(vector[i])>0.0)
printf("- %lf e%d ",fabs(vector[i]),i+1);
else if(i==firstNonZero && vector[i]<0 && fabs(vector[i])-abs(vector[i])==0.0)
printf("- %ld e%d ",labs(vector[i]),i+1);
else if(i==firstNonZero && vector[i]>0 && fabs(vector[i])-abs(vector[i])>0.0)
printf("%lf e%d ",vector[i],i+1);
else if(i==firstNonZero && vector[i]>0 && fabs(vector[i])-abs(vector[i])==0.0)
printf("%ld e%d ",vector[i],i+1);
else if(fabs(vector[i])==1.0 && i!=0)
printf("%c e%d ",(vector[i]==-1)?'-':'+',i+1);
else if(i!=0 && vector[i]!=0 && fabs(vector[i])-abs(vector[i])>0.0)
printf("%c %lf e%d ",(vector[i]<0)?'-':'+',fabs(vector[i]),i+1);
else if(i!=0 && vector[i]!=0 && fabs(vector[i])-abs(vector[i])==0.0)
printf("%c %ld e%d ",(vector[i]<0)?'-':'+',labs(vector[i]),i+1);
}
}
}
free(vector);
return 0;
}
|
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #AutoHotkey | AutoHotkey | ;
; Function: example_add
; Description:
; Adds two or three numbers (see [url=http://en.wikipedia.org/Number]Number [/url])
; Syntax: example_add(number1, number2[, number3=0])
; Parameters:
; number1 - First number to add.
; number2 - Second number to add.
; number3 - (Optional) Third number to add. You can just omit this parameter.
; Return Value:
; sum of parameters
; Example:
; MsgBox % example_add(example_add(2, 3, 4), 5)
;
example_add(number1, number2, number3=0){
return number1 + number2 + number3
} |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #C | C | /**
* \brief Perform addition on \p a and \p b.
*
* \param a One of the numbers to be added.
* \param b Another number to be added.
* \return The sum of \p a and \p b.
* \code
* int sum = add(1, 2);
* \endcode
*/
int add(int a, int b) {
return a + b;
}
|
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #C.23 | C# | /// <summary>
/// The XMLSystem class is here to help handle XML items in this site.
/// </summary>
public static class XMLSystem
{
static XMLSystem()
{
// Constructor
}
/// <summary>
/// A function to get the contents of an XML document.
/// </summary>
/// <param name="name">A valid name of an XML document in the data folder</param>
/// <returns>An XmlDocument containing the contents of the XML file</returns>
public static XmlDocument GetXML(string name)
{
return null;
}
} |
http://rosettacode.org/wiki/Diversity_prediction_theorem | Diversity prediction theorem | The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other.
Thus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.
Scott E. Page introduced the diversity prediction theorem:
The squared error of the collective prediction equals the average squared error minus the predictive diversity.
Therefore, when the diversity in a group is large, the error of the crowd is small.
Definitions
Average Individual Error: Average of the individual squared errors
Collective Error: Squared error of the collective prediction
Prediction Diversity: Average squared distance from the individual predictions to the collective prediction
Diversity Prediction Theorem: Given a crowd of predictive models, then
Collective Error = Average Individual Error ─ Prediction Diversity
Task
For a given true value and a number of number of estimates (from a crowd), show (here on this page):
the true value and the crowd estimates
the average error
the crowd error
the prediction diversity
Use (at least) these two examples:
a true value of 49 with crowd estimates of: 48 47 51
a true value of 49 with crowd estimates of: 48 47 51 42
Also see
Wikipedia entry: Wisdom of the crowd
University of Michigan: PDF paper (exists on a web archive, the Wayback Machine).
| #C | C |
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
float mean(float* arr,int size){
int i = 0;
float sum = 0;
while(i != size)
sum += arr[i++];
return sum/size;
}
float variance(float reference,float* arr, int size){
int i=0;
float* newArr = (float*)malloc(size*sizeof(float));
for(;i<size;i++)
newArr[i] = (reference - arr[i])*(reference - arr[i]);
return mean(newArr,size);
}
float* extractData(char* str, int *len){
float* arr;
int i=0,count = 1;
char* token;
while(str[i]!=00){
if(str[i++]==',')
count++;
}
arr = (float*)malloc(count*sizeof(float));
*len = count;
token = strtok(str,",");
i = 0;
while(token!=NULL){
arr[i++] = atof(token);
token = strtok(NULL,",");
}
return arr;
}
int main(int argC,char* argV[])
{
float* arr,reference,meanVal;
int len;
if(argC!=3)
printf("Usage : %s <reference value> <observations separated by commas>");
else{
arr = extractData(argV[2],&len);
reference = atof(argV[1]);
meanVal = mean(arr,len);
printf("Average Error : %.9f\n",variance(reference,arr,len));
printf("Crowd Error : %.9f\n",(reference - meanVal)*(reference - meanVal));
printf("Diversity : %.9f",variance(meanVal,arr,len));
}
return 0;
}
|
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #Raku | Raku | my $width = my $height = 255; # must be odd
my @light = normalize([ 3, 2, -5 ]);
my $depth = 255;
sub MAIN ($outfile = 'sphere-perl6.pgm') {
spurt $outfile, "P5\n$width $height\n$depth\n"; # .pgm header
my $out = open( $outfile, :a, :bin ) orelse .die;
$out.write( Blob.new(draw_sphere( ($width-1)/2, .9, .2) ) );
$out.close;
}
sub normalize (@vec) { @vec »/» ([+] @vec »*« @vec).sqrt }
sub dot (@x, @y) { -([+] @x »*« @y) max 0 }
sub draw_sphere ( $rad, $k, $ambient ) {
my @pixels[$height];
my $r2 = $rad * $rad;
my @range = -$rad .. $rad;
@range.hyper.map: -> $x {
my @row[$width];
@range.map: -> $y {
if (my $x2 = $x * $x) + (my $y2 = $y * $y) < $r2 {
my @vector = normalize([$x, $y, ($r2 - $x2 - $y2).sqrt]);
my $intensity = dot(@light, @vector) ** $k + $ambient;
my $pixel = (0 max ($intensity * $depth).Int) min $depth;
@row[$y+$rad] = $pixel;
}
else {
@row[$y+$rad] = 0;
}
}
@pixels[$x+$rad] = @row;
}
flat |@pixels.map: *.list;
} |
http://rosettacode.org/wiki/Draw_a_clock | Draw a clock | Task
Draw a clock.
More specific:
Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be drawn; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK.
The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock.
A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task.
A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language.
Key points
animate simple object
timed event
polling system resources
code clarity
| #Ruby | Ruby | Shoes.app(:width=>205, :height => 228, :title => "A Clock") do
def draw_ray(width, start, stop, ratio)
angle = Math::PI * 2 * ratio - Math::PI/2
strokewidth width
cos = Math::cos(angle)
sin = Math::sin(angle)
line 101+cos*start, 101+sin*start, 101+cos*stop, 101+sin*stop
end
def update
t = Time.now
@time.text = t.strftime("%H:%M:%S")
h, m, s = (t.hour % 12).to_f, t.min.to_f, t.sec.to_f
s += t.to_f - t.to_i # add the fractional seconds
@hands.clear do
draw_ray(3, 0, 70, (h + m/60)/12)
draw_ray(2, 0, 90, (m + s/60)/60)
draw_ray(1, 0, 95, s/60)
end
end
# a place for the text display
@time = para(:align=>"center", :family => "monospace")
# draw the clock face
stack(:width=>203, :height=>203) do
strokewidth 1
fill gradient(deepskyblue, aqua)
oval 1, 1, 200
fill black
oval 98, 98, 6
# draw the minute indicators
0.upto(59) {|m| draw_ray(1, (m % 5 == 0 ? 96 : 98), 100, m.to_f/60)}
end.move(0,23)
# the drawing area for the hands
@hands = stack(:width=>203, :height=>203) {}.move(0,23)
animate(5) {update}
end |
http://rosettacode.org/wiki/Distributed_programming | Distributed programming | Write two programs (or one program with two modes) which run on networked computers, and send some messages between them.
The protocol used may be language-specific or not, and should be suitable for general distributed programming; that is, the protocol should be generic (not designed just for the particular example application), readily capable of handling the independent communications of many different components of a single application, and the transferring of arbitrary data structures natural for the language.
This task is intended to demonstrate high-level communication facilities beyond just creating sockets.
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <pvm3.h>
int main(int c, char **v)
{
int tids[10];
int parent, spawn;
int i_data, i2;
double f_data;
if (c > 1) {
spawn = pvm_spawn("/tmp/a.out", 0, PvmTaskDefault, 0, 1, tids);
if (spawn <= 0) {
printf("Can't spawn task\n");
return 1;
}
printf("Spawning successful\n");
/* pvm_recv(task_id, msgtag). msgtag identifies what kind of data it is,
* for here: 1 = (int, double), 2 = (int, int)
* The receiving order is intentionally swapped, just to show.
* task_id = -1 means "receive from any task"
*/
pvm_recv(-1, 2);
pvm_unpackf("%d %d", &i_data, &i2);
printf("got msg type 2: %d %d\n", i_data, i2);
pvm_recv(-1, 1);
pvm_unpackf("%d %lf", &i_data, &f_data);
printf("got msg type 1: %d %f\n", i_data, f_data);
} else {
parent = pvm_parent();
pvm_initsend(PvmDataDefault);
i_data = rand();
f_data = (double)rand() / RAND_MAX;
pvm_packf("%d %lf", i_data, f_data);
pvm_send(parent, 1); /* send msg type 1 */
pvm_initsend(PvmDataDefault);
i2 = rand();
pvm_packf("%d %d", i_data, i2);
pvm_send(parent, 2); /* send msg type 2 */
}
pvm_exit();
return 0;
} |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #AutoHotkey | AutoHotkey | Url := "www.kame.net" , LogFile := "Ping_" A_Now ".log"
Runwait, %comspec% /c nslookup %Url%>%LogFile%, , hide
FileRead, Contents, %LogFile%
FileDelete, %LogFile%
RegExMatch(Contents,"Addresses:.+(`r?`n\s+.+)*",Match)
MsgBox, % RegExReplace(Match,"(Addresses:|[ `t])") |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #Batch_File | Batch File | :: DNS Query Task from Rosetta Code Wiki
:: Batch File Implementation
@echo off
set "domain=www.kame.net"
echo DOMAIN: "%domain%"
echo(
call :DNS_Lookup "%domain%"
pause
exit /b
::Main Procedure
::Uses NSLOOKUP Command. Also uses a dirty "parsing" to detect IP addresses.
:DNS_Lookup [domain]
::Define Variables and the TAB Character
set "dom=%~1"
set "record="
set "reccnt=0"
for /f "delims=" %%T in ('forfiles /p "%~dp0." /m "%~nx0" /c "cmd /c echo(0x09"') do set "TAB=%%T"
setlocal enabledelayedexpansion
for /f "tokens=1* delims=:" %%x in ('nslookup "!dom!" 2^>nul') do (
set "line=%%x"
if /i "!line:~0,4!"=="Name" set "record=yes"
if /i "!line:~0,5!"=="Alias" set "record="
if "!record!"=="yes" (
set /a reccnt+=1
if "%%y"=="" (set "catch_!reccnt!=%%x") else (set "catch_!reccnt!=%%x:%%y")
)
)
for /l %%c in (1,1,%reccnt%) do (
if /i "!catch_%%c:~0,7!"=="Address" echo(!catch_%%c:*s: =!
if /i "!catch_%%c:~0,1!"=="%TAB%" echo(!catch_%%c:%TAB% =!
)
endlocal
goto :EOF |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right.
*---R----* expands to * *
\ /
R L
\ /
*
*
/ \
L R
/ \
*---L---* expands to * *
The co-routines dcl and dcr in various examples do this recursively to a desired expansion level.
The curl direction right or left can be a parameter instead of two separate routines.
Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees.
*------->* becomes * * Recursive copies drawn
\ / from the ends towards
\ / the centre.
v v
*
This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen.
Successive approximation repeatedly re-writes each straight line as two new segments at a right angle,
*
*-----* becomes / \ bend to left
/ \ if N odd
* *
* *
*-----* becomes \ / bend to right
\ / if N even
*
Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing.
The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this.
Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently.
n = 1010110000
^
bit above lowest 1-bit, turn left or right as 0 or 1
LowMask = n BITXOR (n-1) # eg. giving 0000011111
AboveMask = LowMask + 1 # eg. giving 0000100000
BitAboveLowestOne = n BITAND AboveMask
The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there.
If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is.
Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction.
If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1.
Absolute direction to move at point n can be calculated by the number of bit-transitions in n.
n = 11 00 1111 0 1
^ ^ ^ ^ 4 places where change bit value
so direction=4*90degrees=East
This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ.
Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently.
Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this.
A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.)
The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section.
As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code.
Axiom F, angle 90 degrees
F -> F+S
S -> F-S
This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page.
Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around.
The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | FoldOutLine[{a_,b_}]:={{a,#},{b,#}}&[a+0.5(b-a)+{{0.,0.5},{-0.5,0.}}.(b-a)]
NextStep[in_]:=Flatten[FoldOutLine/@in,1]
lines={{{0.,0.},{1.,0.}}};
Graphics[Line/@Nest[NextStep,lines,11]] |
http://rosettacode.org/wiki/Display_a_linear_combination | Display a linear combination | Task
Display a finite linear combination in an infinite vector basis
(
e
1
,
e
2
,
…
)
{\displaystyle (e_{1},e_{2},\ldots )}
.
Write a function that, when given a finite list of scalars
(
α
1
,
α
2
,
…
)
{\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )}
,
creates a string representing the linear combination
∑
i
α
i
e
i
{\displaystyle \sum _{i}\alpha ^{i}e_{i}}
in an explicit format often used in mathematics, that is:
α
i
1
e
i
1
±
|
α
i
2
|
e
i
2
±
|
α
i
3
|
e
i
3
±
…
{\displaystyle \alpha ^{i_{1}}e_{i_{1}}\pm |\alpha ^{i_{2}}|e_{i_{2}}\pm |\alpha ^{i_{3}}|e_{i_{3}}\pm \ldots }
where
α
i
k
≠
0
{\displaystyle \alpha ^{i_{k}}\neq 0}
The output must comply to the following rules:
don't show null terms, unless the whole combination is null.
e(1) is fine, e(1) + 0*e(3) or e(1) + 0 is wrong.
don't show scalars when they are equal to one or minus one.
e(3) is fine, 1*e(3) is wrong.
don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction.
e(4) - e(5) is fine, e(4) + -e(5) is wrong.
Show here output for the following lists of scalars:
1) 1, 2, 3
2) 0, 1, 2, 3
3) 1, 0, 3, 4
4) 1, 2, 0
5) 0, 0, 0
6) 0
7) 1, 1, 1
8) -1, -1, -1
9) -1, -2, 0, -3
10) -1
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.Text;
namespace DisplayLinearCombination {
class Program {
static string LinearCombo(List<int> c) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < c.Count; i++) {
int n = c[i];
if (n < 0) {
if (sb.Length == 0) {
sb.Append('-');
} else {
sb.Append(" - ");
}
} else if (n > 0) {
if (sb.Length != 0) {
sb.Append(" + ");
}
} else {
continue;
}
int av = Math.Abs(n);
if (av != 1) {
sb.AppendFormat("{0}*", av);
}
sb.AppendFormat("e({0})", i + 1);
}
if (sb.Length == 0) {
sb.Append('0');
}
return sb.ToString();
}
static void Main(string[] args) {
List<List<int>> combos = new List<List<int>>{
new List<int> { 1, 2, 3},
new List<int> { 0, 1, 2, 3},
new List<int> { 1, 0, 3, 4},
new List<int> { 1, 2, 0},
new List<int> { 0, 0, 0},
new List<int> { 0},
new List<int> { 1, 1, 1},
new List<int> { -1, -1, -1},
new List<int> { -1, -2, 0, -3},
new List<int> { -1},
};
foreach (List<int> c in combos) {
var arr = "[" + string.Join(", ", c) + "]";
Console.WriteLine("{0,15} -> {1}", arr, LinearCombo(c));
}
}
}
} |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Clojure | Clojure | (def
#^{:doc "Metadata can contain documentation and can be added to vars like this."}
test1)
(defn test2
"defn and some other macros allow you add documentation like this. Works the same way"
[]) |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #COBOL | COBOL |
*>****L* cobweb/cobweb-gtk [0.2]
*> Author:
*> Author details
*> Colophon:
*> Part of the GnuCobol free software project
*> Copyright (C) 2014 person
*> Date 20130308
*> Modified 20141003
*> License GNU General Public License, GPL, 3.0 or greater
*> Documentation licensed GNU FDL, version 2.1 or greater
*> HTML Documentation thanks to ROBODoc --cobol
*> Purpose:
*> GnuCobol functional bindings to GTK+
*> Main module includes paperwork output and self test
*> Synopsis:
*> |dotfile cobweb-gtk.dot
*> |html <br />
*> Functions include
*> |exec cobcrun cobweb-gtk >cobweb-gtk.repository
*> |html <pre>
*> |copy cobweb-gtk.repository
*> |html </pre>
*> |exec rm cobweb-gtk.repository
*> Tectonics:
*> cobc -v -b -g -debug cobweb-gtk.cob voidcall_gtk.c
*> `pkg-config --libs gtk+-3.0` -lvte2_90 -lyelp
*> robodoc --cobol --src ./ --doc cobwebgtk --multidoc --rc robocob.rc --css cobodoc.css
*> cobc -E -Ddocpass cobweb-gtk.cob
*> make singlehtml # once Sphinx set up to read cobweb-gtk.i
*> Example:
*> COPY cobweb-gtk-preamble.
*> procedure division.
*> move TOP-LEVEL to window-type
*> move 640 to width-hint
*> move 480 to height-hint
*> move new-window("window title", window-type,
*> width-hint, height-hint)
*> to gtk-window-data
*> move gtk-go(gtk-window) to extraneous
*> goback.
*> Notes:
*> The interface signatures changed between 0.1 and 0.2
*> Screenshot:
*> image:cobweb-gtk1.png
*> Source:
REPLACE ==FIELDSIZE== BY ==80==
==AREASIZE== BY ==32768==
==FILESIZE== BY ==65536==.
id identification division.
program-id. cobweb-gtk.
...
done goback.
end program cobweb-gtk.
*>****
|
http://rosettacode.org/wiki/Diversity_prediction_theorem | Diversity prediction theorem | The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other.
Thus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.
Scott E. Page introduced the diversity prediction theorem:
The squared error of the collective prediction equals the average squared error minus the predictive diversity.
Therefore, when the diversity in a group is large, the error of the crowd is small.
Definitions
Average Individual Error: Average of the individual squared errors
Collective Error: Squared error of the collective prediction
Prediction Diversity: Average squared distance from the individual predictions to the collective prediction
Diversity Prediction Theorem: Given a crowd of predictive models, then
Collective Error = Average Individual Error ─ Prediction Diversity
Task
For a given true value and a number of number of estimates (from a crowd), show (here on this page):
the true value and the crowd estimates
the average error
the crowd error
the prediction diversity
Use (at least) these two examples:
a true value of 49 with crowd estimates of: 48 47 51
a true value of 49 with crowd estimates of: 48 47 51 42
Also see
Wikipedia entry: Wisdom of the crowd
University of Michigan: PDF paper (exists on a web archive, the Wayback Machine).
| #C.23 | C# |
using System;
using System.Linq;
using System.Collections.Generic;
public class MainClass {
static double Square(double x) => x * x;
static double AverageSquareDiff(double a, IEnumerable<double> predictions)
=> predictions.Select(x => Square(x - a)).Average();
static void DiversityTheorem(double truth, IEnumerable<double> predictions)
{
var average = predictions.Average();
Console.WriteLine($@"average-error: {AverageSquareDiff(truth, predictions)}
crowd-error: {Square(truth - average)}
diversity: {AverageSquareDiff(average, predictions)}");
}
public static void Main() {
DiversityTheorem(49, new []{48d,47,51});
DiversityTheorem(49, new []{48d,47,51,42});
}
} |
http://rosettacode.org/wiki/Diversity_prediction_theorem | Diversity prediction theorem | The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other.
Thus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.
Scott E. Page introduced the diversity prediction theorem:
The squared error of the collective prediction equals the average squared error minus the predictive diversity.
Therefore, when the diversity in a group is large, the error of the crowd is small.
Definitions
Average Individual Error: Average of the individual squared errors
Collective Error: Squared error of the collective prediction
Prediction Diversity: Average squared distance from the individual predictions to the collective prediction
Diversity Prediction Theorem: Given a crowd of predictive models, then
Collective Error = Average Individual Error ─ Prediction Diversity
Task
For a given true value and a number of number of estimates (from a crowd), show (here on this page):
the true value and the crowd estimates
the average error
the crowd error
the prediction diversity
Use (at least) these two examples:
a true value of 49 with crowd estimates of: 48 47 51
a true value of 49 with crowd estimates of: 48 47 51 42
Also see
Wikipedia entry: Wisdom of the crowd
University of Michigan: PDF paper (exists on a web archive, the Wayback Machine).
| #C.2B.2B | C++ |
#include <iostream>
#include <vector>
#include <numeric>
float sum(const std::vector<float> &array)
{
return std::accumulate(array.begin(), array.end(), 0.0);
}
float square(float x)
{
return x * x;
}
float mean(const std::vector<float> &array)
{
return sum(array) / array.size();
}
float averageSquareDiff(float a, const std::vector<float> &predictions)
{
std::vector<float> results;
for (float x : predictions)
results.push_back(square(x - a));
return mean(results);
}
void diversityTheorem(float truth, const std::vector<float> &predictions)
{
float average = mean(predictions);
std::cout
<< "average-error: " << averageSquareDiff(truth, predictions) << "\n"
<< "crowd-error: " << square(truth - average) << "\n"
<< "diversity: " << averageSquareDiff(average, predictions) << std::endl;
}
int main() {
diversityTheorem(49, {48,47,51});
diversityTheorem(49, {48,47,51,42});
return 0;
}
|
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #REXX | REXX | /*REXX program expresses a lighted sphere with simple characters used for shading. */
call drawSphere 19, 4, 2/10, '30 30 -50' /*draw a sphere with a radius of 19. */
call drawSphere 10, 2, 4/10, '30 30 -50' /* " " " " " " " ten. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
ceil: procedure; parse arg x; _= trunc(x); return _ +(x>0) * (x\=_)
floor: procedure; parse arg x; _= trunc(x); return _ -(x<0) * (x\=_)
norm: parse arg $a $b $c; _= sqrt($a**2 + $b**2 + $c**2); return $a/_ $b/_ $c/_
/*──────────────────────────────────────────────────────────────────────────────────────*/
drawSphere: procedure; parse arg r, k, ambient, lightSource /*obtain the four arguments*/
if 8=='f8'x then shading= ".:!*oe&#%@" /* EBCDIC dithering chars. */
else shading= "·:!°oe@░▒▓" /* ASCII " " */
parse value norm(lightSource) with s1 s2 s3 /*normalize light source. */
shadeLen= length(shading) - 1; rr= r**2; r2= r+r /*handy─dandy variables. */
do i=floor(-r ) to ceil(r ); x= i + .5; xx= x**2; $=
do j=floor(-r2) to ceil(r2); y= j * .5 + .5; yy= y**2; z= xx+yy
if z<=rr then do /*is point within sphere ? */
parse value norm(x y sqrt(rr - xx - yy) ) with v1 v2 v3
dot= min(0, s1*v1 + s2*v2 + s3*v3) /*the dot product of above.*/
b= -dot**k + ambient /*calculate the brightness.*/
if b<=0 then brite= shadeLen
else brite= max(0, (1-b) * shadeLen) % 1
$= $ || substr(shading, brite + 1, 1)
end /* [↑] build display line.*/
else $= $' ' /*append a blank to line. */
end /*j*/ /*[↓] strip trailing blanks*/
say strip($, 'T') /*show a line of the sphere*/
end /*i*/ /* [↑] display the sphere.*/
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
sqrt: procedure; parse arg x; if x=0 then return 0; d= digits(); numeric digits; h= d+6
numeric form; m.=9; parse value format(x,2,1,,0) 'E0' with g "E" _ .; g= g*.5'e'_%2
do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/
do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/; return g |
http://rosettacode.org/wiki/Draw_a_clock | Draw a clock | Task
Draw a clock.
More specific:
Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be drawn; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK.
The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock.
A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task.
A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language.
Key points
animate simple object
timed event
polling system resources
code clarity
| #Run_BASIC | Run BASIC | ' --------------------------------------------
' clock. I got nothing but time
' ---------------------------------------------
n = 12 ' num of points
r = 95 ' radius
pi = 22/7
alpha = pi * 2 / n
dim points(n)
graphic #g2, 200, 200
' --------------------------------------
' Draw the clock
' --------------------------------------
#g2 size(2) 'pen size
#g2 down()
#g2 font("arial", 20, "bold")
#g2 place(85,30)
#g2 "\12"
#g2 place(170,105)
#g2 "\3"
#g2 place(10,105)
#g2 "\9"
#g2 place(90,185)
#g2 "\6"
for i = 0 to n - 1
theta = alpha * i
px = cos( theta ) * r
py = sin( theta ) * r
px = px + 100
py = py + 100
#g2 place(px,py)
#g2 circle(2)
next i
[shoTime]
' -------------------------
' clear previous sec,min,hr
' -------------------------
r = 63
p = se
#g2 color("white")
gosub [h2Dot]
r = 50
p = mi
#g2 color("white")
gosub [h2Dot]
r = 30 ' radius
p = hr * 5
#g2 color("white")
gosub [h2Dot]
' -------------------------
' Show new time
' -------------------------
a$ = time$()
hr = val(word$(a$,1,":"))
mi = val(word$(a$,2,":"))
se = val(word$(a$,3,":"))
' put time on the clock - gimme a hand
#g2 size(4)
' second hand
n = 60
r = 63
p = se
#g2 color("blue")
gosub [h2Dot]
' minute hand
r = 50
p = mi
#g2 color("green")
gosub [h2Dot]
' hour hand
r = 30 ' radius
p = hr * 5
#g2 color("red")
gosub [h2Dot]
render #g2
end
' a one liner
[h2Dot]
alpha = pi * 2 / n
i = p - 15
theta = alpha * i
px = cos( theta ) * r
py = sin( theta ) * r
px = px + 100
py = py + 100
#g2 place(px,py)
#g2 circle(2)
#g2 line(100,100,px,py)
RETURN |
http://rosettacode.org/wiki/Distributed_programming | Distributed programming | Write two programs (or one program with two modes) which run on networked computers, and send some messages between them.
The protocol used may be language-specific or not, and should be suitable for general distributed programming; that is, the protocol should be generic (not designed just for the particular example application), readily capable of handling the independent communications of many different components of a single application, and the transferring of arbitrary data structures natural for the language.
This task is intended to demonstrate high-level communication facilities beyond just creating sockets.
| #C.23 | C# |
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading.Tasks;
using static System.Console;
class DistributedProgramming
{
const int Port = 555;
async static Task RunClient()
{
WriteLine("Connecting");
var client = new TcpClient();
await client.ConnectAsync("localhost", Port);
using (var stream = client.GetStream())
{
WriteLine("Sending loot");
var data = Serialize(new SampleData());
await stream.WriteAsync(data, 0, data.Length);
WriteLine("Receiving thanks");
var buffer = new byte[80000];
var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
var thanks = (string)Deserialize(buffer, bytesRead);
WriteLine(thanks);
}
client.Close();
}
async static Task RunServer()
{
WriteLine("Listening");
var listener = new TcpListener(IPAddress.Any, Port);
listener.Start();
var client = await listener.AcceptTcpClientAsync();
using (var stream = client.GetStream())
{
WriteLine("Receiving loot");
var buffer = new byte[80000];
var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
var data = (SampleData)Deserialize(buffer, bytesRead);
WriteLine($"{data.Loot} at {data.Latitude}, {data.Longitude}");
WriteLine("Sending thanks");
var thanks = Serialize("Thanks!");
await stream.WriteAsync(thanks, 0, thanks.Length);
}
client.Close();
listener.Stop();
Write("Press a key");
ReadKey();
}
static byte[] Serialize(object data)
{
using (var mem = new MemoryStream())
{
new BinaryFormatter().Serialize(mem, data);
return mem.ToArray();
}
}
static object Deserialize(byte[] data, int length)
{
using (var mem = new MemoryStream(data, 0, length))
{
return new BinaryFormatter().Deserialize(mem);
}
}
static void Main(string[] args)
{
if (args.Length == 0) return;
switch (args[0])
{
case "client": RunClient().Wait(); break;
case "server": RunServer().Wait(); break;
}
}
}
[Serializable]
class SampleData
{
public decimal Latitude = 44.33190m;
public decimal Longitude = 114.84129m;
public string Loot = "140 tonnes of jade";
}
|
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #BBC_BASIC | BBC BASIC | name$ = "www.kame.net"
AF_INET = 2
AF_INET6 = 23
WSASYS_STATUS_LEN = 128
WSADESCRIPTION_LEN = 256
SYS "LoadLibrary", "WS2_32.DLL" TO ws2%
SYS "GetProcAddress", ws2%, "WSAStartup" TO `WSAStartup`
SYS "GetProcAddress", ws2%, "WSACleanup" TO `WSACleanup`
SYS "GetProcAddress", ws2%, "getaddrinfo" TO `getaddrinfo`
DIM WSAdata{wVersion{l&,h&}, wHighVersion{l&,h&}, \
\ szDescription&(WSADESCRIPTION_LEN), szSystemStatus&(WSASYS_STATUS_LEN), \
\ iMaxSockets{l&,h&}, iMaxUdpDg{l&,h&}, lpVendorInfo%}
DIM addrinfo{ai_flags%, ai_family%, ai_socktype%, ai_protocol%, \
\ ai_addrlen%, lp_ai_canonname%, lp_ai_addr%, lp_ai_next%}
DIM ipv4info{} = addrinfo{}, ipv6info{} = addrinfo{}
DIM sockaddr_in{sin_family{l&,h&}, sin_port{l&,h&}, sin_addr&(3), sin_zero&(7)}
DIM sockaddr_in6{sin6_family{l&,h&}, sin6_port{l&,h&}, sin6_flowinfo%, \
\ sin6_addr&(15), sin6_scope_id%}
SYS `WSAStartup`, &202, WSAdata{} TO res%
IF res% ERROR 102, "WSAStartup failed"
addrinfo.ai_family% = AF_INET
SYS `getaddrinfo`, name$, 0, addrinfo{}, ^ipv4info{}+4 TO res%
IF res% ERROR 103, "getaddrinfo failed"
!(^sockaddr_in{}+4) = ipv4info.lp_ai_addr%
PRINT "IPv4 address = " ;
PRINT ;sockaddr_in.sin_addr&(0) "." sockaddr_in.sin_addr&(1) "." ;
PRINT ;sockaddr_in.sin_addr&(2) "." sockaddr_in.sin_addr&(3)
addrinfo.ai_family% = AF_INET6
SYS `getaddrinfo`, name$, 0, addrinfo{}, ^ipv6info{}+4 TO res%
IF res% ERROR 104, "getaddrinfo failed"
!(^sockaddr_in6{}+4) = ipv6info.lp_ai_addr%
PRINT "IPv6 address = " ;
PRINT ;~sockaddr_in6.sin6_addr&(0) * 256 + sockaddr_in6.sin6_addr&(1) ":" ;
PRINT ;~sockaddr_in6.sin6_addr&(2) * 256 + sockaddr_in6.sin6_addr&(3) ":" ;
PRINT ;~sockaddr_in6.sin6_addr&(4) * 256 + sockaddr_in6.sin6_addr&(5) ":" ;
PRINT ;~sockaddr_in6.sin6_addr&(6) * 256 + sockaddr_in6.sin6_addr&(7) ":" ;
PRINT ;~sockaddr_in6.sin6_addr&(8) * 256 + sockaddr_in6.sin6_addr&(9) ":" ;
PRINT ;~sockaddr_in6.sin6_addr&(10) * 256 + sockaddr_in6.sin6_addr&(11) ":" ;
PRINT ;~sockaddr_in6.sin6_addr&(12) * 256 + sockaddr_in6.sin6_addr&(13) ":" ;
PRINT ;~sockaddr_in6.sin6_addr&(14) * 256 + sockaddr_in6.sin6_addr&(15)
SYS `WSACleanup`
|
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #C | C | #include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h> /* getaddrinfo, getnameinfo */
#include <stdio.h> /* fprintf, printf */
#include <stdlib.h> /* exit */
#include <string.h> /* memset */
int
main()
{
struct addrinfo hints, *res, *res0;
int error;
char host[NI_MAXHOST];
/*
* Request only one socket type from getaddrinfo(). Else we
* would get both SOCK_DGRAM and SOCK_STREAM, and print two
* copies of each numeric address.
*/
memset(&hints, 0, sizeof hints);
hints.ai_family = PF_UNSPEC; /* IPv4, IPv6, or anything */
hints.ai_socktype = SOCK_DGRAM; /* Dummy socket type */
/*
* Use getaddrinfo() to resolve "www.kame.net" and allocate
* a linked list of addresses.
*/
error = getaddrinfo("www.kame.net", NULL, &hints, &res0);
if (error) {
fprintf(stderr, "%s\n", gai_strerror(error));
exit(1);
}
/* Iterate the linked list. */
for (res = res0; res; res = res->ai_next) {
/*
* Use getnameinfo() to convert res->ai_addr to a
* printable string.
*
* NI_NUMERICHOST means to present the numeric address
* without doing reverse DNS to get a domain name.
*/
error = getnameinfo(res->ai_addr, res->ai_addrlen,
host, sizeof host, NULL, 0, NI_NUMERICHOST);
if (error) {
fprintf(stderr, "%s\n", gai_strerror(error));
} else {
/* Print the numeric address. */
printf("%s\n", host);
}
}
/* Free the linked list. */
freeaddrinfo(res0);
return 0;
} |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right.
*---R----* expands to * *
\ /
R L
\ /
*
*
/ \
L R
/ \
*---L---* expands to * *
The co-routines dcl and dcr in various examples do this recursively to a desired expansion level.
The curl direction right or left can be a parameter instead of two separate routines.
Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees.
*------->* becomes * * Recursive copies drawn
\ / from the ends towards
\ / the centre.
v v
*
This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen.
Successive approximation repeatedly re-writes each straight line as two new segments at a right angle,
*
*-----* becomes / \ bend to left
/ \ if N odd
* *
* *
*-----* becomes \ / bend to right
\ / if N even
*
Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing.
The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this.
Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently.
n = 1010110000
^
bit above lowest 1-bit, turn left or right as 0 or 1
LowMask = n BITXOR (n-1) # eg. giving 0000011111
AboveMask = LowMask + 1 # eg. giving 0000100000
BitAboveLowestOne = n BITAND AboveMask
The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there.
If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is.
Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction.
If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1.
Absolute direction to move at point n can be calculated by the number of bit-transitions in n.
n = 11 00 1111 0 1
^ ^ ^ ^ 4 places where change bit value
so direction=4*90degrees=East
This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ.
Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently.
Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this.
A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.)
The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section.
As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code.
Axiom F, angle 90 degrees
F -> F+S
S -> F-S
This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page.
Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around.
The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
| #Metafont | Metafont | mode_setup;
dragoniter := 8;
beginchar("D", 25pt#, 25pt#, 0pt#);
pickup pencircle scaled .5pt;
x1 = 0; x2 = w; y1 = y2 = .5h;
mstep := .5; sg := -1;
for i = 1 upto dragoniter:
for v = 1 step mstep until (2-mstep):
if unknown z[v+mstep]:
pair t;
t := .7071[ z[v], z[v+2mstep] ];
z[v+mstep] = t rotatedaround(z[v], 45sg);
sg := -1*sg;
fi
endfor
mstep := mstep/2;
endfor
draw for v:=1 step 2mstep until (2-2mstep): z[v] -- endfor z[2];
endchar;
end |
http://rosettacode.org/wiki/Display_a_linear_combination | Display a linear combination | Task
Display a finite linear combination in an infinite vector basis
(
e
1
,
e
2
,
…
)
{\displaystyle (e_{1},e_{2},\ldots )}
.
Write a function that, when given a finite list of scalars
(
α
1
,
α
2
,
…
)
{\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )}
,
creates a string representing the linear combination
∑
i
α
i
e
i
{\displaystyle \sum _{i}\alpha ^{i}e_{i}}
in an explicit format often used in mathematics, that is:
α
i
1
e
i
1
±
|
α
i
2
|
e
i
2
±
|
α
i
3
|
e
i
3
±
…
{\displaystyle \alpha ^{i_{1}}e_{i_{1}}\pm |\alpha ^{i_{2}}|e_{i_{2}}\pm |\alpha ^{i_{3}}|e_{i_{3}}\pm \ldots }
where
α
i
k
≠
0
{\displaystyle \alpha ^{i_{k}}\neq 0}
The output must comply to the following rules:
don't show null terms, unless the whole combination is null.
e(1) is fine, e(1) + 0*e(3) or e(1) + 0 is wrong.
don't show scalars when they are equal to one or minus one.
e(3) is fine, 1*e(3) is wrong.
don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction.
e(4) - e(5) is fine, e(4) + -e(5) is wrong.
Show here output for the following lists of scalars:
1) 1, 2, 3
2) 0, 1, 2, 3
3) 1, 0, 3, 4
4) 1, 2, 0
5) 0, 0, 0
6) 0
7) 1, 1, 1
8) -1, -1, -1
9) -1, -2, 0, -3
10) -1
| #C.2B.2B | C++ | #include <iomanip>
#include <iostream>
#include <sstream>
#include <vector>
template<typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) {
auto it = v.cbegin();
auto end = v.cend();
os << '[';
if (it != end) {
os << *it;
it = std::next(it);
}
while (it != end) {
os << ", " << *it;
it = std::next(it);
}
return os << ']';
}
std::ostream& operator<<(std::ostream& os, const std::string& s) {
return os << s.c_str();
}
std::string linearCombo(const std::vector<int>& c) {
std::stringstream ss;
for (size_t i = 0; i < c.size(); i++) {
int n = c[i];
if (n < 0) {
if (ss.tellp() == 0) {
ss << '-';
} else {
ss << " - ";
}
} else if (n > 0) {
if (ss.tellp() != 0) {
ss << " + ";
}
} else {
continue;
}
int av = abs(n);
if (av != 1) {
ss << av << '*';
}
ss << "e(" << i + 1 << ')';
}
if (ss.tellp() == 0) {
return "0";
}
return ss.str();
}
int main() {
using namespace std;
vector<vector<int>> combos{
{1, 2, 3},
{0, 1, 2, 3},
{1, 0, 3, 4},
{1, 2, 0},
{0, 0, 0},
{0},
{1, 1, 1},
{-1, -1, -1},
{-1, -2, 0, -3},
{-1},
};
for (auto& c : combos) {
stringstream ss;
ss << c;
cout << setw(15) << ss.str() << " -> ";
cout << linearCombo(c) << '\n';
}
return 0;
} |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Common_Lisp | Common Lisp | CL-USER 83 > (defun add (a b)
"add two numbers a and b"
(+ a b))
ADD
|
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Crystal | Crystal | # Any block of comments *directly* before (no blank lines) a module, class, or method is used as a doc comment
# This one is for a module
module Documentation
# This comment documents a class, *and* it uses markdown
class Foo
# This comment doesn't do anything, because it isn't directly above a module, class, or method
# Finally, this comment documents a method
def initialize
end
end
end |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #D | D | /**
This is a documentation comment for someFunc and someFunc2.
$(DDOC_COMMENT comment inside a documentation comment
(results in a HTML comment not displayed by the browser))
Header:
content (does not need to be tabbed out; this is done for clarity
of the comments and has no effect on the resulting documentation)
Params:
arg1 = Something (listed as "int <i>arg1</i> Something")
arg2 = Something else
Returns:
Nothing
TODO:
Nothing at all
BUG:
None found
*/
void someFunc(int arg1, int arg2) {}
// This groups this function with the above (both have the
// same doc and are listed together)
/// ditto
void someFunc2(int arg1, int arg2) {}
/// Sum function.
int sum(in int x, in int y) pure nothrow {
return x + y;
}
// These unittests will become part of sum documentation:
///
unittest {
assert(sum(2, 3) == 5);
}
/++ Another documentation comment +/
void main() {} |
http://rosettacode.org/wiki/Diversity_prediction_theorem | Diversity prediction theorem | The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other.
Thus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.
Scott E. Page introduced the diversity prediction theorem:
The squared error of the collective prediction equals the average squared error minus the predictive diversity.
Therefore, when the diversity in a group is large, the error of the crowd is small.
Definitions
Average Individual Error: Average of the individual squared errors
Collective Error: Squared error of the collective prediction
Prediction Diversity: Average squared distance from the individual predictions to the collective prediction
Diversity Prediction Theorem: Given a crowd of predictive models, then
Collective Error = Average Individual Error ─ Prediction Diversity
Task
For a given true value and a number of number of estimates (from a crowd), show (here on this page):
the true value and the crowd estimates
the average error
the crowd error
the prediction diversity
Use (at least) these two examples:
a true value of 49 with crowd estimates of: 48 47 51
a true value of 49 with crowd estimates of: 48 47 51 42
Also see
Wikipedia entry: Wisdom of the crowd
University of Michigan: PDF paper (exists on a web archive, the Wayback Machine).
| #Clojure | Clojure |
(defn diversity-theorem [truth predictions]
(let [square (fn[x] (* x x))
mean (/ (reduce + predictions) (count predictions))
avg-sq-diff (fn[a] (/ (reduce + (for [x predictions] (square (- x a)))) (count predictions)))]
{:average-error (avg-sq-diff truth)
:crowd-error (square (- truth mean))
:diversity (avg-sq-diff mean)}))
(println (diversity-theorem 49 '(48 47 51)))
(println (diversity-theorem 49 '(48 47 51 42)))
|
http://rosettacode.org/wiki/Diversity_prediction_theorem | Diversity prediction theorem | The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other.
Thus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.
Scott E. Page introduced the diversity prediction theorem:
The squared error of the collective prediction equals the average squared error minus the predictive diversity.
Therefore, when the diversity in a group is large, the error of the crowd is small.
Definitions
Average Individual Error: Average of the individual squared errors
Collective Error: Squared error of the collective prediction
Prediction Diversity: Average squared distance from the individual predictions to the collective prediction
Diversity Prediction Theorem: Given a crowd of predictive models, then
Collective Error = Average Individual Error ─ Prediction Diversity
Task
For a given true value and a number of number of estimates (from a crowd), show (here on this page):
the true value and the crowd estimates
the average error
the crowd error
the prediction diversity
Use (at least) these two examples:
a true value of 49 with crowd estimates of: 48 47 51
a true value of 49 with crowd estimates of: 48 47 51 42
Also see
Wikipedia entry: Wisdom of the crowd
University of Michigan: PDF paper (exists on a web archive, the Wayback Machine).
| #D | D | import std.algorithm;
import std.stdio;
auto square = (real x) => x * x;
auto meanSquareDiff(R)(real a, R predictions) {
return predictions.map!(x => square(x - a)).mean;
}
void diversityTheorem(R)(real truth, R predictions) {
auto average = predictions.mean;
writeln("average-error: ", meanSquareDiff(truth, predictions));
writeln("crowd-error: ", square(truth - average));
writeln("diversity: ", meanSquareDiff(average, predictions));
writeln;
}
void main() {
diversityTheorem(49.0, [48.0, 47.0, 51.0]);
diversityTheorem(49.0, [48.0, 47.0, 51.0, 42.0]);
} |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #Ruby | Ruby | Shoes.app :width => 500, :height => 500, :resizable => false do
image 400, 470, :top => 30, :left => 50 do
nostroke
fill "#127"
image :top => 230, :left => 0 do
oval 70, 130, 260, 40
blur 30
end
oval 10, 10, 380, 380
image :top => 0, :left => 0 do
fill "#46D"
oval 30, 30, 338, 338
blur 10
end
fill gradient(rgb(1.0, 1.0, 1.0, 0.7), rgb(1.0, 1.0, 1.0, 0.0))
oval 80, 14, 240, 176
image :top => 0, :left => 0 do
fill "#79F"
oval 134, 134, 130, 130
blur 40
end
image :top => 150, :left => 40, :width => 320, :height => 260 do
fill gradient(rgb(0.7, 0.9, 1.0, 0.0), rgb(0.7, 0.9, 1.0, 0.6))
oval 60, 60, 200, 136
blur 20
end
end
end |
http://rosettacode.org/wiki/Display_an_outline_as_a_nested_table | Display an outline as a nested table |
Display an outline as a nested table.
Parse the outline to a tree,
count the leaves descending from each node,
and write out a table with 'colspan' values
measuring the indent of each line,
translating the indentation to a nested structure,
and padding the tree to even depth.
defining the width of a leaf as 1,
and the width of a parent node as a sum.
either as a wiki table,
or as HTML.
(The sum of the widths of its children)
The graphic representation of outlines is a staple of mind-mapping and the planning of papers, reports, and speeches.
Task
Given a outline with at least 3 levels of indentation, for example:
Display an outline as a nested table.
Parse the outline to a tree,
measuring the indent of each line,
translating the indentation to a nested structure,
and padding the tree to even depth.
count the leaves descending from each node,
defining the width of a leaf as 1,
and the width of a parent node as a sum.
(The sum of the widths of its children)
and write out a table with 'colspan' values
either as a wiki table,
or as HTML.
write a program in your language which translates your outline into a nested table, with WikiTable or HTML colspan values attached (where needed) to parent nodes in the nested table.
The WikiTable at the top of this page was generated from the indented outline shown above, producing the following markup string:
{| class="wikitable" style="text-align: center;"
|-
| style="background: #ffffe6; " colspan=7 | Display an outline as a nested table.
|-
| style="background: #ffebd2; " colspan=3 | Parse the outline to a tree,
| style="background: #f0fff0; " colspan=2 | count the leaves descending from each node,
| style="background: #e6ffff; " colspan=2 | and write out a table with 'colspan' values
|-
| style="background: #ffebd2; " | measuring the indent of each line,
| style="background: #ffebd2; " | translating the indentation to a nested structure,
| style="background: #ffebd2; " | and padding the tree to even depth.
| style="background: #f0fff0; " | defining the width of a leaf as 1,
| style="background: #f0fff0; " | and the width of a parent node as a sum.
| style="background: #e6ffff; " | either as a wiki table,
| style="background: #e6ffff; " | or as HTML.
|-
| |
| |
| |
| |
| style="background: #f0fff0; " | (The sum of the widths of its children)
| |
| |
|}
Extra credit
Use background color to distinguish the main stages of your outline, so that the subtree of each node at level two is consistently colored, and the edges between adjacent subtrees are immediately revealed.
Output
Display your nested table on this page.
| #AutoHotkey | AutoHotkey | outline2table(db, Delim:= "`t"){
oNum:=[], oMID:=[], oNod := [], oKid := [], oPnt := [], oMbr := [], oLvl := []
oCrl := ["#ffffe6;", "#ffebd2;", "#f0fff0;", "#e6ffff;", "#ffeeff;"]
col := 0, out := "", anc := ""
; create numerical index for each line
for i, line in StrSplit(db, "`n", "`r")
{
RegExMatch(line, "^(\t*)(.*)$", m)
out .= m1 . i "`n"
oNum[i] := m2
}
db := Trim(out, "`n")
; create list of members, parents, kids and their ancestors
for i, mbr in StrSplit(db, "`n", "`r")
{
lvl := 1
While (SubStr(mbr, 1, 1) = Delim)
lvl++, mbr := SubStr(mbr, 2)
if (pLvl >= lvl) && pMbr
col++
, oMbr[pLvl, pMbr] .= "col:" col ",anc:" anc
, oKid[pLvl, pMbr] .= "col:" col ",anc:" anc
if (pLvl > lvl) && pMbr
loop % pLvl - lvl
anc := RegExReplace(anc, "\d+_?$")
if (pLvl < lvl) && pMbr
anc .= pMbr "_"
, oMbr[pLvl, pMbr] .= "col:" col+1 ",anc:" anc
, oPnt[pLvl, pMbr] .= "col:" col+1 ",anc:" anc
pLvl := lvl
pMbr := mbr
;~ oMID[lvl] := TV_Add(mbr, oMID[lvl-1], "Expand")
}
; last one on the list
col++
oMbr[pLvl, pMbr] .= "col:" col ",anc:" anc
oKid[pLvl, pMbr] .= "col:" col ",anc:" anc
; setup node color
clr := 1
for lvl, obj in oMbr
for node, str in obj
if (lvl <= 2)
oNod[node, "clr"] := clr++
else
oNod[node, "clr"] := oNod[StrSplit(str, "_").2, "clr"]
; setup node level/column/width
for lvl, obj in oKid
for node, str in obj
{
x := StrSplit(str, ",")
col := StrReplace(x.1, "col:")
anc := Trim(StrReplace(x.2, "anc:"), "_")
for j, a in StrSplit(anc, "_")
oNod[a, "wid"] := (oNod[a, "wid"]?oNod[a, "wid"]:0) + 1
oNod[node, "lvl"] := lvl
oNod[node, "col"] := col
oNod[node, "wid"] := 1
}
for lvl, obj in oPnt
for node, str in obj
{
x := StrSplit(str, ",")
col := StrReplace(x.1, "col:")
anc := Trim(StrReplace(x.2, "anc:"), "_")
oNod[node, "lvl"] := lvl
oNod[node, "col"] := col
}
; setup members by level
for node, obj in oNod
oLvl[obj["lvl"], node] := 1
maxW := 0
for node in oLvl[1]
maxW += oNod[node, "wid"]
; setup HTML
html := "<table class=""wikitable"" style=""text-align: center;"">`n"
for lvl, obj in oLvl
{
pCol := 1
html .= "<tr>`n"
for node, bool in obj
{
while (oNod[node, "col"] <> pCol)
pCol++, html .= "`t<td style=""background: #F9F9F9;""></td>`n"
pCol += oNod[node, "wid"]
if !cNum := Mod(oNod[node, "clr"], 5)
cNum := 5
html .= "`t<td style=""background: " oCrl[cNum] """ colspan=""" oNod[node, "wid"] """>" oNum[node] "</td>`n"
}
while (pCOl <= maxW)
pCol++, html .= "`t<td style=""background: #F9F9F9;""></td>`n"
html .= "</tr>`n"
}
html .= "</table>"
; setup wikitable
wTable := "{| class=""wikitable"" style=""text-align: center;""`n"
for lvl, obj in oLvl
{
pCol := 1
wTable .= "|-`n"
for node, bool in obj
{
while (oNod[node, "col"] <> pCol)
pCol++, wTable .= "| | `n"
pCol += oNod[node, "wid"]
if !cNum := Mod(oNod[node, "clr"], 5)
cNum := 5
wTable .= "| style=""background: " oCrl[cNum] """ colspan=""" oNod[node, "wid"] " |" oNum[node] "`n"
}
while (pCOl <= maxW)
pCol++, wTable .= "| | `n"
}
wTable .= "|}`n"
return [html, wTable]
}
|
http://rosettacode.org/wiki/Draw_a_clock | Draw a clock | Task
Draw a clock.
More specific:
Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be drawn; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK.
The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock.
A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task.
A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language.
Key points
animate simple object
timed event
polling system resources
code clarity
| #Rust | Rust | // cargo-deps: time="0.1"
extern crate time;
use std::thread;
use std::time::Duration;
const TOP: &str = " ⡎⢉⢵ ⠀⢺⠀ ⠊⠉⡱ ⠊⣉⡱ ⢀⠔⡇ ⣏⣉⡉ ⣎⣉⡁ ⠊⢉⠝ ⢎⣉⡱ ⡎⠉⢱ ⠀⠶⠀";
const BOT: &str = " ⢗⣁⡸ ⢀⣸⣀ ⣔⣉⣀ ⢄⣀⡸ ⠉⠉⡏ ⢄⣀⡸ ⢇⣀⡸ ⢰⠁⠀ ⢇⣀⡸ ⢈⣉⡹ ⠀⠶⠀";
fn main() {
let top: Vec<&str> = TOP.split_whitespace().collect();
let bot: Vec<&str> = BOT.split_whitespace().collect();
loop {
let tm = &time::now().rfc822().to_string()[17..25];
let top_str: String = tm.chars().map(|x| top[x as usize - '0' as usize]).collect();
let bot_str: String = tm.chars().map(|x| bot[x as usize - '0' as usize]).collect();
clear_screen();
println!("{}", top_str);
println!("{}", bot_str);
thread::sleep(Duration::from_secs(1));
}
}
fn clear_screen() {
println!("{}[H{}[J", 27 as char, 27 as char);
} |
http://rosettacode.org/wiki/Distributed_programming | Distributed programming | Write two programs (or one program with two modes) which run on networked computers, and send some messages between them.
The protocol used may be language-specific or not, and should be suitable for general distributed programming; that is, the protocol should be generic (not designed just for the particular example application), readily capable of handling the independent communications of many different components of a single application, and the transferring of arbitrary data structures natural for the language.
This task is intended to demonstrate high-level communication facilities beyond just creating sockets.
| #D | D | import arsd.rpc;
struct S1 {
int number;
string name;
}
struct S2 {
string name;
int number;
}
interface ExampleNetworkFunctions {
string sayHello(string name);
int add(in int a, in int b) const pure nothrow;
S2 structTest(S1);
void die();
}
// The server must implement the interface.
class ExampleServer : ExampleNetworkFunctions {
override string sayHello(string name) {
return "Hello, " ~ name;
}
override int add(in int a, in int b) const pure nothrow {
return a + b;
}
override S2 structTest(S1 a) {
return S2(a.name, a.number);
}
override void die() {
throw new Exception("death requested");
}
mixin NetworkServer!ExampleNetworkFunctions;
}
class Client {
mixin NetworkClient!ExampleNetworkFunctions;
}
void main(in string[] args) {
import std.stdio;
if (args.length > 1) {
auto client = new Client("localhost", 5005);
// These work like the interface above, but instead of
// returning the value, they take callbacks for success (where
// the arg is the retval) and failure (the arg is the
// exception).
client.sayHello("whoa", (a) { writeln(a); }, null);
client.add(1,2, (a){ writeln(a); }, null);
client.add(10,20, (a){ writeln(a); }, null);
client.structTest(S1(20, "cool!"),
(a){ writeln(a.name, " -- ", a.number); },
null);
client.die(delegate(){ writeln("shouldn't happen"); },
delegate(a){ writeln(a); });
client.eventLoop;
} else {
auto server = new ExampleServer(5005);
server.eventLoop;
}
} |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #C.23 | C# |
private string LookupDns(string s)
{
try
{
System.Net.IPHostEntry ip = System.Net.Dns.GetHostEntry(s);
string result = ip.AddressList[0].ToString();
for (int i = 1; i < ip.AddressList.Length; ++i)
result += ", " + ip.AddressList[i].ToString();
return result;
}
catch (System.Net.Sockets.SocketException se)
{
return se.Message;
}
}
|
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #C.2B.2B | C++ |
#include <boost/asio.hpp>
#include <iostream>
int main() {
int rc {EXIT_SUCCESS};
try {
boost::asio::io_service io_service;
boost::asio::ip::tcp::resolver resolver {io_service};
auto entries = resolver.resolve({"www.kame.net", ""});
boost::asio::ip::tcp::resolver::iterator entries_end;
for (; entries != entries_end; ++entries) {
std::cout << entries->endpoint().address() << std::endl;
}
}
catch (std::exception& e) {
std::cerr << e.what() << std::endl;
rc = EXIT_FAILURE;
}
return rc;
}
|
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right.
*---R----* expands to * *
\ /
R L
\ /
*
*
/ \
L R
/ \
*---L---* expands to * *
The co-routines dcl and dcr in various examples do this recursively to a desired expansion level.
The curl direction right or left can be a parameter instead of two separate routines.
Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees.
*------->* becomes * * Recursive copies drawn
\ / from the ends towards
\ / the centre.
v v
*
This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen.
Successive approximation repeatedly re-writes each straight line as two new segments at a right angle,
*
*-----* becomes / \ bend to left
/ \ if N odd
* *
* *
*-----* becomes \ / bend to right
\ / if N even
*
Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing.
The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this.
Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently.
n = 1010110000
^
bit above lowest 1-bit, turn left or right as 0 or 1
LowMask = n BITXOR (n-1) # eg. giving 0000011111
AboveMask = LowMask + 1 # eg. giving 0000100000
BitAboveLowestOne = n BITAND AboveMask
The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there.
If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is.
Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction.
If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1.
Absolute direction to move at point n can be calculated by the number of bit-transitions in n.
n = 11 00 1111 0 1
^ ^ ^ ^ 4 places where change bit value
so direction=4*90degrees=East
This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ.
Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently.
Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this.
A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.)
The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section.
As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code.
Axiom F, angle 90 degrees
F -> F+S
S -> F-S
This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page.
Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around.
The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
| #Nim | Nim | import math
import imageman
const
## Separation of the two endpoints.
## Make this a power of 2 for prettier output.
Sep = 512
## Depth of recursion. Adjust as desired for different visual effects.
Depth = 18
S = sqrt(2.0) / 2
Sin = [float 0, S, 1, S, 0, -S, -1, -S]
Cos = [float 1, S, 0, -S, -1, -S, 0, S]
LineColor = ColorRGBU [byte 64, 192, 96]
Width = Sep * 11 div 6
Height = Sep * 4 div 3
Output = "dragon.png"
#---------------------------------------------------------------------------------------------------
func dragon(img: var Image; n, a, t: int; d, x, y: float) =
if n <= 1:
img.drawLine((x.toInt, y.toInt), ((x + d * Cos[a]).toInt, (y + d * Sin[a]).toInt), LineColor)
return
let d = d * S
let a1 = (a - t) and 7
let a2 = (a + t) and 7
img.dragon(n - 1, a1, 1, d, x, y)
img.dragon(n - 1, a2, -1, d, x + d * Cos[a1], y + d * Sin[a1])
#---------------------------------------------------------------------------------------------------
var image = initImage[ColorRGBU](Width, Height)
image.fill(ColorRGBU [byte 0, 0, 0])
image.dragon(Depth, 0, 1, Sep, Sep / 2, Sep * 5 / 6)
# Save into a PNG file.
image.savePNG(Output, compression = 9) |
http://rosettacode.org/wiki/Display_a_linear_combination | Display a linear combination | Task
Display a finite linear combination in an infinite vector basis
(
e
1
,
e
2
,
…
)
{\displaystyle (e_{1},e_{2},\ldots )}
.
Write a function that, when given a finite list of scalars
(
α
1
,
α
2
,
…
)
{\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )}
,
creates a string representing the linear combination
∑
i
α
i
e
i
{\displaystyle \sum _{i}\alpha ^{i}e_{i}}
in an explicit format often used in mathematics, that is:
α
i
1
e
i
1
±
|
α
i
2
|
e
i
2
±
|
α
i
3
|
e
i
3
±
…
{\displaystyle \alpha ^{i_{1}}e_{i_{1}}\pm |\alpha ^{i_{2}}|e_{i_{2}}\pm |\alpha ^{i_{3}}|e_{i_{3}}\pm \ldots }
where
α
i
k
≠
0
{\displaystyle \alpha ^{i_{k}}\neq 0}
The output must comply to the following rules:
don't show null terms, unless the whole combination is null.
e(1) is fine, e(1) + 0*e(3) or e(1) + 0 is wrong.
don't show scalars when they are equal to one or minus one.
e(3) is fine, 1*e(3) is wrong.
don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction.
e(4) - e(5) is fine, e(4) + -e(5) is wrong.
Show here output for the following lists of scalars:
1) 1, 2, 3
2) 0, 1, 2, 3
3) 1, 0, 3, 4
4) 1, 2, 0
5) 0, 0, 0
6) 0
7) 1, 1, 1
8) -1, -1, -1
9) -1, -2, 0, -3
10) -1
| #D | D | import std.array;
import std.conv;
import std.format;
import std.math;
import std.stdio;
string linearCombo(int[] c) {
auto sb = appender!string;
foreach (i, n; c) {
if (n==0) continue;
string op;
if (n < 0) {
if (sb.data.empty) {
op = "-";
} else {
op = " - ";
}
} else if (n > 0) {
if (!sb.data.empty) {
op = " + ";
}
}
auto av = abs(n);
string coeff;
if (av != 1) {
coeff = to!string(av) ~ "*";
}
sb.formattedWrite("%s%se(%d)", op, coeff, i+1);
}
if (sb.data.empty) {
return "0";
}
return sb.data;
}
void main() {
auto combos = [
[1, 2, 3],
[0, 1, 2, 3],
[1, 0, 3, 4],
[1, 2, 0],
[0, 0, 0],
[0],
[1, 1, 1],
[-1, -1, -1],
[-1, -2, 0, -3],
[-1],
];
foreach (c; combos) {
auto arr = c.format!"%s";
writefln("%-15s -> %s", arr, linearCombo(c));
}
} |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Delphi | Delphi | type
/// <summary>Sample class.</summary>
TMyClass = class
public
/// <summary>Converts a string into a number.</summary>
/// <param name="aValue">String parameter</param>
/// <returns>Numeric equivalent of aValue</returns>
/// <exception cref="EConvertError">aValue is not a valid integer.</exception>
function StringToNumber(aValue: string): Integer;
end; |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #E | E | ? /** This is an object with documentation */
> def foo {
> # ...
> }
# value: <foo>
? foo.__getAllegedType().getDocComment()
# value: " This is an object with documentation " |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Eiffel | Eiffel | note
description: "Objects that model Times of Day: 00:00:00 - 23:59:59"
author: "Eiffel Software Construction Students"
class
TIME_OF_DAY
create
make
feature -- Initialization
make
-- Initialize to 00:00:00
do
hour := 0
minute := 0
second := 0
ensure
initialized: hour = 0 and
minute = 0 and
second = 0
end
feature -- Access
hour: INTEGER
-- Hour expressed as 24-hour value
minute: INTEGER
-- Minutes past the hour
second: INTEGER
-- Seconds past the minute
feature -- Element change
set_hour (h: INTEGER)
-- Set the hour from `h'
require
argument_hour_valid: 0 <= h and h <= 23
do
hour := h
ensure
hour_set: hour = h
minute_unchanged: minute = old minute
second_unchanged: second = old second
end
set_minute (m: INTEGER)
-- Set the minute from `m'
require
argument_minute_valid: 0 <= m and m <= 59
do
minute := m
ensure
minute_set: minute = m
hour_unchanged: hour = old hour
second_unchanged: second = old second
end
set_second (s: INTEGER)
-- Set the second from `s'
require
argument_second_valid: 0 <= s and s <= 59
do
second := s
ensure
second_set: second = s
hour_unchanged: hour = old hour
minute_unchanged: minute = old minute
end
feature {NONE} -- Implementation
protected_routine
-- A protected routine (not available to client classes)
-- Will not be present in documentation (Contract) view
do
end
invariant
hour_valid: 0 <= hour and hour <= 23
minute_valid: 0 <= minute and minute <= 59
second_valid: 0 <= second and second <= 59
end -- class TIME_OF_DAY |
http://rosettacode.org/wiki/Diversity_prediction_theorem | Diversity prediction theorem | The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other.
Thus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.
Scott E. Page introduced the diversity prediction theorem:
The squared error of the collective prediction equals the average squared error minus the predictive diversity.
Therefore, when the diversity in a group is large, the error of the crowd is small.
Definitions
Average Individual Error: Average of the individual squared errors
Collective Error: Squared error of the collective prediction
Prediction Diversity: Average squared distance from the individual predictions to the collective prediction
Diversity Prediction Theorem: Given a crowd of predictive models, then
Collective Error = Average Individual Error ─ Prediction Diversity
Task
For a given true value and a number of number of estimates (from a crowd), show (here on this page):
the true value and the crowd estimates
the average error
the crowd error
the prediction diversity
Use (at least) these two examples:
a true value of 49 with crowd estimates of: 48 47 51
a true value of 49 with crowd estimates of: 48 47 51 42
Also see
Wikipedia entry: Wisdom of the crowd
University of Michigan: PDF paper (exists on a web archive, the Wayback Machine).
| #Factor | Factor | USING: kernel math math.statistics math.vectors prettyprint ;
TUPLE: div avg-err crowd-err diversity ;
: diversity ( x seq -- obj )
[ n-v dup v* mean ] [ mean swap - sq ]
[ nip dup mean v-n dup v* mean ] 2tri div boa ;
49 { 48 47 51 } diversity .
49 { 48 47 51 42 } diversity . |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #Rust | Rust | // [dependencies]
// image = "0.23"
use image::{GrayImage, Luma};
type Vector = [f64; 3];
fn normalize(v: &mut Vector) {
let inv_len = 1.0/dot_product(v, v).sqrt();
v[0] *= inv_len;
v[1] *= inv_len;
v[2] *= inv_len;
}
fn dot_product(v1: &Vector, v2: &Vector) -> f64 {
v1.iter().zip(v2.iter()).map(|(x, y)| *x * *y).sum()
}
fn draw_sphere(radius: u32, k: f64, ambient: f64, dir: &Vector) -> GrayImage {
let width = radius * 4;
let height = radius * 3;
let mut image = GrayImage::new(width, height);
let mut vec = [0.0; 3];
let diameter = radius * 2;
let r = radius as f64;
let xoffset = (width - diameter)/2;
let yoffset = (height - diameter)/2;
for i in 0..diameter {
let x = i as f64 - r;
for j in 0..diameter {
let y = j as f64 - r;
let z = r * r - x * x - y * y;
if z >= 0.0 {
vec[0] = x;
vec[1] = y;
vec[2] = z.sqrt();
normalize(&mut vec);
let mut s = dot_product(&dir, &vec);
if s < 0.0 {
s = 0.0;
}
let mut lum = 255.0 * (s.powf(k) + ambient)/(1.0 + ambient);
if lum < 0.0 {
lum = 0.0;
} else if lum > 255.0 {
lum = 255.0;
}
image.put_pixel(i + xoffset, j + yoffset, Luma([lum as u8]));
}
}
}
image
}
fn main() {
let mut dir = [-30.0, -30.0, 50.0];
normalize(&mut dir);
match draw_sphere(200, 1.5, 0.2, &dir).save("sphere.png") {
Ok(()) => {}
Err(error) => eprintln!("{}", error),
}
} |
http://rosettacode.org/wiki/Display_an_outline_as_a_nested_table | Display an outline as a nested table |
Display an outline as a nested table.
Parse the outline to a tree,
count the leaves descending from each node,
and write out a table with 'colspan' values
measuring the indent of each line,
translating the indentation to a nested structure,
and padding the tree to even depth.
defining the width of a leaf as 1,
and the width of a parent node as a sum.
either as a wiki table,
or as HTML.
(The sum of the widths of its children)
The graphic representation of outlines is a staple of mind-mapping and the planning of papers, reports, and speeches.
Task
Given a outline with at least 3 levels of indentation, for example:
Display an outline as a nested table.
Parse the outline to a tree,
measuring the indent of each line,
translating the indentation to a nested structure,
and padding the tree to even depth.
count the leaves descending from each node,
defining the width of a leaf as 1,
and the width of a parent node as a sum.
(The sum of the widths of its children)
and write out a table with 'colspan' values
either as a wiki table,
or as HTML.
write a program in your language which translates your outline into a nested table, with WikiTable or HTML colspan values attached (where needed) to parent nodes in the nested table.
The WikiTable at the top of this page was generated from the indented outline shown above, producing the following markup string:
{| class="wikitable" style="text-align: center;"
|-
| style="background: #ffffe6; " colspan=7 | Display an outline as a nested table.
|-
| style="background: #ffebd2; " colspan=3 | Parse the outline to a tree,
| style="background: #f0fff0; " colspan=2 | count the leaves descending from each node,
| style="background: #e6ffff; " colspan=2 | and write out a table with 'colspan' values
|-
| style="background: #ffebd2; " | measuring the indent of each line,
| style="background: #ffebd2; " | translating the indentation to a nested structure,
| style="background: #ffebd2; " | and padding the tree to even depth.
| style="background: #f0fff0; " | defining the width of a leaf as 1,
| style="background: #f0fff0; " | and the width of a parent node as a sum.
| style="background: #e6ffff; " | either as a wiki table,
| style="background: #e6ffff; " | or as HTML.
|-
| |
| |
| |
| |
| style="background: #f0fff0; " | (The sum of the widths of its children)
| |
| |
|}
Extra credit
Use background color to distinguish the main stages of your outline, so that the subtree of each node at level two is consistently colored, and the edges between adjacent subtrees are immediately revealed.
Output
Display your nested table on this page.
| #Go | Go | package main
import (
"fmt"
"strings"
)
type nNode struct {
name string
children []nNode
}
type iNode struct {
level int
name string
}
func toNest(iNodes []iNode, start, level int, n *nNode) {
if level == 0 {
n.name = iNodes[0].name
}
for i := start + 1; i < len(iNodes); i++ {
if iNodes[i].level == level+1 {
c := nNode{iNodes[i].name, nil}
toNest(iNodes, i, level+1, &c)
n.children = append(n.children, c)
} else if iNodes[i].level <= level {
return
}
}
}
func makeIndent(outline string, tab int) []iNode {
lines := strings.Split(outline, "\n")
iNodes := make([]iNode, len(lines))
for i, line := range lines {
line2 := strings.TrimLeft(line, " ")
le, le2 := len(line), len(line2)
level := (le - le2) / tab
iNodes[i] = iNode{level, line2}
}
return iNodes
}
func toMarkup(n nNode, cols []string, depth int) string {
var span int
var colSpan func(nn nNode)
colSpan = func(nn nNode) {
for i, c := range nn.children {
if i > 0 {
span++
}
colSpan(c)
}
}
for _, c := range n.children {
span = 1
colSpan(c)
}
var lines []string
lines = append(lines, `{| class="wikitable" style="text-align: center;"`)
const l1, l2 = "|-", "| |"
lines = append(lines, l1)
span = 1
colSpan(n)
s := fmt.Sprintf(`| style="background: %s " colSpan=%d | %s`, cols[0], span, n.name)
lines = append(lines, s, l1)
var nestedFor func(nn nNode, level, maxLevel, col int)
nestedFor = func(nn nNode, level, maxLevel, col int) {
if level == 1 && maxLevel > level {
for i, c := range nn.children {
nestedFor(c, 2, maxLevel, i)
}
} else if level < maxLevel {
for _, c := range nn.children {
nestedFor(c, level+1, maxLevel, col)
}
} else {
if len(nn.children) > 0 {
for i, c := range nn.children {
span = 1
colSpan(c)
cn := col + 1
if maxLevel == 1 {
cn = i + 1
}
s := fmt.Sprintf(`| style="background: %s " colspan=%d | %s`, cols[cn], span, c.name)
lines = append(lines, s)
}
} else {
lines = append(lines, l2)
}
}
}
for maxLevel := 1; maxLevel < depth; maxLevel++ {
nestedFor(n, 1, maxLevel, 0)
if maxLevel < depth-1 {
lines = append(lines, l1)
}
}
lines = append(lines, "|}")
return strings.Join(lines, "\n")
}
func main() {
const outline = `Display an outline as a nested table.
Parse the outline to a tree,
measuring the indent of each line,
translating the indentation to a nested structure,
and padding the tree to even depth.
count the leaves descending from each node,
defining the width of a leaf as 1,
and the width of a parent node as a sum.
(The sum of the widths of its children)
and write out a table with 'colspan' values
either as a wiki table,
or as HTML.`
const (
yellow = "#ffffe6;"
orange = "#ffebd2;"
green = "#f0fff0;"
blue = "#e6ffff;"
pink = "#ffeeff;"
)
cols := []string{yellow, orange, green, blue, pink}
iNodes := makeIndent(outline, 4)
var n nNode
toNest(iNodes, 0, 0, &n)
fmt.Println(toMarkup(n, cols, 4))
fmt.Println("\n")
const outline2 = `Display an outline as a nested table.
Parse the outline to a tree,
measuring the indent of each line,
translating the indentation to a nested structure,
and padding the tree to even depth.
count the leaves descending from each node,
defining the width of a leaf as 1,
and the width of a parent node as a sum.
(The sum of the widths of its children)
Propagating the sums upward as necessary.
and write out a table with 'colspan' values
either as a wiki table,
or as HTML.
Optionally add color to the nodes.`
cols2 := []string{blue, yellow, orange, green, pink}
var n2 nNode
iNodes2 := makeIndent(outline2, 4)
toNest(iNodes2, 0, 0, &n2)
fmt.Println(toMarkup(n2, cols2, 4))
} |
http://rosettacode.org/wiki/Draw_a_clock | Draw a clock | Task
Draw a clock.
More specific:
Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be drawn; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK.
The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock.
A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task.
A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language.
Key points
animate simple object
timed event
polling system resources
code clarity
| #Scala | Scala | import java.util.{ Timer, TimerTask }
import java.time.LocalTime
import scala.math._
object Clock extends App {
private val (width, height) = (80, 35)
def getGrid(localTime: LocalTime): Array[Array[Char]] = {
val (minute, second) = (localTime.getMinute, localTime.getSecond())
val grid = Array.fill[Char](height, width)(' ')
def toGridCoord(x: Double, y: Double): (Int, Int) =
(floor((y + 1.0) / 2.0 * height).toInt, floor((x + 1.0) / 2.0 * width).toInt)
def makeText(grid: Array[Array[Char]], r: Double, theta: Double, str: String) {
val (row, col) = toGridCoord(r * cos(theta), r * sin(theta))
(0 until str.length).foreach(i =>
if (row >= 0 && row < height && col + i >= 0 && col + i < width) grid(row)(col + i) = str(i))
}
def makeCircle(grid: Array[Array[Char]], r: Double, c: Char) {
var theta = 0.0
while (theta < 2 * Pi) {
val (row, col) = toGridCoord(r * cos(theta), r * sin(theta))
if (row >= 0 && row < height && col >= 0 && col < width) grid(row)(col) = c
theta = theta + 0.01
}
}
def makeHand(grid: Array[Array[Char]], maxR: Double, theta: Double, c: Char) {
var r = 0.0
while (r < maxR) {
val (row, col) = toGridCoord(r * cos(theta), r * sin(theta))
if (row >= 0 && row < height && col >= 0 && col < width) grid(row)(col) = c
r = r + 0.01
}
}
makeCircle(grid, 0.98, '@')
makeHand(grid, 0.6, (localTime.getHour() + minute / 60.0 + second / 3600.0) * Pi / 6 - Pi / 2, 'O')
makeHand(grid, 0.85, (minute + second / 60.0) * Pi / 30 - Pi / 2, '*')
makeHand(grid, 0.90, second * Pi / 30 - Pi / 2, '.')
(1 to 12).foreach(n => makeText(grid, 0.87, n * Pi / 6 - Pi / 2, n.toString))
grid
} // def getGrid(
private val timerTask = new TimerTask {
private def printGrid(grid: Array[Array[Char]]) = grid.foreach(row => println(row.mkString))
def run() = printGrid(getGrid(LocalTime.now()))
}
(new Timer).schedule(timerTask, 0, 1000)
} |
http://rosettacode.org/wiki/Distributed_programming | Distributed programming | Write two programs (or one program with two modes) which run on networked computers, and send some messages between them.
The protocol used may be language-specific or not, and should be suitable for general distributed programming; that is, the protocol should be generic (not designed just for the particular example application), readily capable of handling the independent communications of many different components of a single application, and the transferring of arbitrary data structures natural for the language.
This task is intended to demonstrate high-level communication facilities beyond just creating sockets.
| #E | E | def storage := [].diverge()
def logService {
to log(line :String) {
storage.push([timer.now(), line])
}
to search(substring :String) {
var matches := []
for [time, line] ? (line.startOf(substring) != -1) in storage {
matches with= [time, line]
}
return matches
}
}
introducer.onTheAir()
def sturdyRef := makeSturdyRef.temp(logService)
println(<captp>.sturdyToURI(sturdyRef))
interp.blockAtTop() |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #Cach.C3.A9_ObjectScript | Caché ObjectScript |
Class Utils.Net Extends %RegisteredObject
{
ClassMethod QueryDNS(pHost As %String, Output ip As %List) As %Status
{
// some initialisation
K ip S ip=""
// check host operating system and input parameters
S OS=$SYSTEM.Version.GetOS()
I '$LF($LB("Windows","UNIX"), OS) Q $$$ERROR($$$GeneralError, "Not implemented.")
I OS="Windows" S cmd="nslookup "_pHost
I OS="UNIX" S cmd="host "_pHost
I $MATCH(pHost, "^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$")=0 {
Q $$$ERROR($$$GeneralError, "Invalid host name.")
}
// invoke command
S list=##class(Utils.OS).Call(cmd, 0)
// iterate through list
S ptr=0, skip=1
WHILE $LISTNEXT(list,ptr,value) {
I value="" CONTINUE
I skip, OS="Windows" S skip=$S(value["Name:": 0, 1: 1) CONTINUE
S ipv4=..GetIPAddr("ipv4", value) I $L(ipv4) S $LI(ip, 4)=ipv4
S ipv6=..GetIPAddr("ipv6", value) I $L(ipv6) S $LI(ip, 6)=ipv6
}
// finished
I $LD(ip, 4)=0, $LD(ip, 6)=0 Q $$$ERROR($$$GeneralError, "Lookup failed.")
QUIT $$$OK
}
ClassMethod GetIPAddr(pType As %String = "", pValue As %String = "") As %String
{
I pType="ipv4" {
S pos=$LOCATE(pValue, "((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.|$)){4}")
I pos Q $P($E(pValue, pos, *), " ")
}
I pType="ipv6" {
S pos=$LOCATE(pValue, "([0-9A-Fa-f]{0,4}:){2,7}([0-9A-Fa-f]{1,4}$|((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4})")
I pos Q $P($E(pValue, pos, *), " ")
}
QUIT ""
}
}
|
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #Clojure | Clojure | (import java.net.InetAddress java.net.Inet4Address java.net.Inet6Address)
(doseq [addr (InetAddress/getAllByName "www.kame.net")]
(cond
(instance? Inet4Address addr) (println "IPv4:" (.getHostAddress addr))
(instance? Inet6Address addr) (println "IPv6:" (.getHostAddress addr)))) |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree angle. And a left dragon is a left followed by a right.
*---R----* expands to * *
\ /
R L
\ /
*
*
/ \
L R
/ \
*---L---* expands to * *
The co-routines dcl and dcr in various examples do this recursively to a desired expansion level.
The curl direction right or left can be a parameter instead of two separate routines.
Recursively, a curl direction can be eliminated by noting the dragon consists of two copies of itself drawn towards a central point at 45-degrees.
*------->* becomes * * Recursive copies drawn
\ / from the ends towards
\ / the centre.
v v
*
This can be seen in the SVG example. This is best suited to off-line drawing since the reversal in the second half means the drawing jumps backward and forward (in binary reflected Gray code order) which is not very good for a plotter or for drawing progressively on screen.
Successive approximation repeatedly re-writes each straight line as two new segments at a right angle,
*
*-----* becomes / \ bend to left
/ \ if N odd
* *
* *
*-----* becomes \ / bend to right
\ / if N even
*
Numbering from the start of the curve built so far, if the segment is at an odd position then the bend introduced is on the right side. If the segment is an even position then on the left. The process is then repeated on the new doubled list of segments. This constructs a full set of line segments before any drawing.
The effect of the splitting is a kind of bottom-up version of the recursions. See the Asymptote example for code doing this.
Iteratively the curve always turns 90-degrees left or right at each point. The direction of the turn is given by the bit above the lowest 1-bit of n. Some bit-twiddling can extract that efficiently.
n = 1010110000
^
bit above lowest 1-bit, turn left or right as 0 or 1
LowMask = n BITXOR (n-1) # eg. giving 0000011111
AboveMask = LowMask + 1 # eg. giving 0000100000
BitAboveLowestOne = n BITAND AboveMask
The first turn is at n=1, so reckon the curve starting at the origin as n=0 then a straight line segment to position n=1 and turn there.
If you prefer to reckon the first turn as n=0 then take the bit above the lowest 0-bit instead. This works because "...10000" minus 1 is "...01111" so the lowest 0 in n-1 is where the lowest 1 in n is.
Going by turns suits turtle graphics such as Logo or a plotter drawing with a pen and current direction.
If a language doesn't maintain a "current direction" for drawing then you can always keep that separately and apply turns by bit-above-lowest-1.
Absolute direction to move at point n can be calculated by the number of bit-transitions in n.
n = 11 00 1111 0 1
^ ^ ^ ^ 4 places where change bit value
so direction=4*90degrees=East
This can be calculated by counting the number of 1 bits in "n XOR (n RIGHTSHIFT 1)" since such a shift and xor leaves a single 1 bit at each position where two adjacent bits differ.
Absolute X,Y coordinates of a point n can be calculated in complex numbers by some powers (i+1)^k and add/subtract/rotate. This is done in the gnuplot code. This might suit things similar to Gnuplot which want to calculate each point independently.
Predicate test for whether a given X,Y point or segment is on the curve can be done. This might suit line-by-line output rather than building an entire image before printing. See M4 for an example of this.
A predicate works by dividing out complex number i+1 until reaching the origin, so it takes roughly a bit at a time from X and Y is thus quite efficient. Why it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.)
The number of steps in the predicate corresponds to doublings of the curve, so stopping the check at say 8 steps can limit the curve drawn to 2^8=256 points. The offsets arising in the predicate are bits of n the segment number, so can note those bits to calculate n and limit to an arbitrary desired length or sub-section.
As a Lindenmayer system of expansions. The simplest is two symbols F and S both straight lines, as used by the PGF code.
Axiom F, angle 90 degrees
F -> F+S
S -> F-S
This always has F at even positions and S at odd. Eg. after 3 levels F_S_F_S_F_S_F_S. The +/- turns in between bend to the left or right the same as the "successive approximation" method above. Read more at for instance Joel Castellanos' L-system page.
Variations are possible if you have only a single symbol for line draw, for example the Icon and Unicon and Xfractint code. The angles can also be broken into 45-degree parts to keep the expansion in a single direction rather than the endpoint rotating around.
The string rewrites can be done recursively without building the whole string, just follow its instructions at the target level. See for example C by IFS Drawing code. The effect is the same as "recursive with parameter" above but can draw other curves defined by L-systems.
| #OCaml | OCaml | (* This constant does not seem to be defined anywhere in the standard modules *)
let pi = acos (-1.0);
(*
** CLASS dragon_curve_computer:
** ----------------------------
** Computes the coordinates for the line drawing the curve.
** - initial_x initial_y: coordinates for starting point for curve
** - total_length: total length for the curve
** - total_splits: total number of splits to perform
*)
class dragon_curve_computer initial_x initial_y total_length total_splits =
object(self)
val mutable current_x = (float_of_int initial_x) (* current x coordinate in curve *)
val mutable current_y = (float_of_int initial_y) (* current y coordinate in curve *)
val mutable current_angle = 0.0 (* current angle *)
(*
** METHOD compute_coords:
** ----------------------
** Actually computes the coordinates in the line for the curve
** - length: length for current iteration
** - nb_splits: number of splits to perform for current iteration
** - direction: direction for current line (-1.0 or 1.0)
** Returns: the list of coordinates for the line in this iteration
*)
method compute_coords length nb_splits direction =
(* If all splits have been done *)
if nb_splits = 0
then
begin
(* Draw line segment, updating current coordinates *)
current_x <- current_x +. length *. cos current_angle;
current_y <- current_y +. length *. sin current_angle;
[(int_of_float current_x, int_of_float current_y)]
end
(* If there are still splits to perform *)
else
begin
(* Compute length for next iteration *)
let sub_length = length /. sqrt 2.0 in
(* Turn 45 degrees to left or right depending on current direction and draw part
of curve in this direction *)
current_angle <- current_angle +. direction *. pi /. 4.0;
let coords1 = self#compute_coords sub_length (nb_splits - 1) 1.0 in
(* Turn 90 degrees in the other direction and draw part of curve in that direction *)
current_angle <- current_angle -. direction *. pi /. 2.0;
let coords2 = self#compute_coords sub_length (nb_splits - 1) (-1.0) in
(* Turn back 45 degrees to set head in the initial direction again *)
current_angle <- current_angle +. direction *. pi /. 4.0;
(* Concatenate both sub-curves to get the full curve for this iteration *)
coords1 @ coords2
end
(*
** METHOD get_coords:
** ------------------
** Returns the coordinates for the curve with the parameters set in the object initializer
*)
method get_coords = self#compute_coords total_length total_splits 1.0
end;;
(*
** MAIN PROGRAM:
** =============
*)
let () =
(* Curve is displayed in a Tk canvas *)
let top=Tk.openTk() in
let c = Canvas.create ~width:400 ~height:400 top in
Tk.pack [c];
(* Create instance computing the curve coordinates *)
let dcc = new dragon_curve_computer 100 200 200.0 16 in
(* Create line with these coordinates in canvas *)
ignore (Canvas.create_line ~xys: dcc#get_coords c);
Tk.mainLoop ();
;; |
http://rosettacode.org/wiki/Display_a_linear_combination | Display a linear combination | Task
Display a finite linear combination in an infinite vector basis
(
e
1
,
e
2
,
…
)
{\displaystyle (e_{1},e_{2},\ldots )}
.
Write a function that, when given a finite list of scalars
(
α
1
,
α
2
,
…
)
{\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )}
,
creates a string representing the linear combination
∑
i
α
i
e
i
{\displaystyle \sum _{i}\alpha ^{i}e_{i}}
in an explicit format often used in mathematics, that is:
α
i
1
e
i
1
±
|
α
i
2
|
e
i
2
±
|
α
i
3
|
e
i
3
±
…
{\displaystyle \alpha ^{i_{1}}e_{i_{1}}\pm |\alpha ^{i_{2}}|e_{i_{2}}\pm |\alpha ^{i_{3}}|e_{i_{3}}\pm \ldots }
where
α
i
k
≠
0
{\displaystyle \alpha ^{i_{k}}\neq 0}
The output must comply to the following rules:
don't show null terms, unless the whole combination is null.
e(1) is fine, e(1) + 0*e(3) or e(1) + 0 is wrong.
don't show scalars when they are equal to one or minus one.
e(3) is fine, 1*e(3) is wrong.
don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction.
e(4) - e(5) is fine, e(4) + -e(5) is wrong.
Show here output for the following lists of scalars:
1) 1, 2, 3
2) 0, 1, 2, 3
3) 1, 0, 3, 4
4) 1, 2, 0
5) 0, 0, 0
6) 0
7) 1, 1, 1
8) -1, -1, -1
9) -1, -2, 0, -3
10) -1
| #EchoLisp | EchoLisp |
;; build an html string from list of coeffs
(define (linear->html coeffs)
(define plus #f)
(or*
(for/fold (html "") ((a coeffs) (i (in-naturals 1)))
(unless (zero? a)
(set! plus (if plus "+" "")))
(string-append html
(cond
((= a 1) (format "%a e<sub>%d</sub> " plus i))
((= a -1) (format "- e<sub>%d</sub> " i))
((> a 0) (format "%a %d*e<sub>%d</sub> " plus a i))
((< a 0) (format "- %d*e<sub>%d</sub> " (abs a) i))
(else ""))))
"0"))
(define linears '((1 2 3)
(0 1 2 3)
(1 0 3 4)
(1 2 0)
(0 0 0)
(0)
(1 1 1)
(-1 -1 -1)
(-1 -2 0 -3)
(-1)))
(define (task linears)
(html-print ;; send string to stdout
(for/string ((linear linears))
(format "%a -> <span style='color:blue'>%a</span> <br>" linear (linear->html linear)))))
|
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Elixir | Elixir |
def project do
[app: :repo
version: "0.1.0-dev",
name: "REPO",
source_url: "https://github.com/USER/REPO",
homepage_url: "http://YOUR_PROJECT_HOMEPAGE"
deps: deps]
end
|
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Emacs_Lisp | Emacs Lisp | (defun hello (n)
"Say hello to the user."
(message "hello %d" n)) |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Erlang | Erlang | def class Foo {
"""
This is a docstring. Every object in Fancy can have it's own docstring.
Either defined in the source code, like this one, or by using the Object#docstring: method
"""
def a_method {
"""
Same for methods. They can have docstrings, too.
"""
}
}
Foo docstring println # prints docstring Foo class
Foo instance_method: 'a_method . docstring println # prints method's docstring |
http://rosettacode.org/wiki/Diversity_prediction_theorem | Diversity prediction theorem | The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other.
Thus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.
Scott E. Page introduced the diversity prediction theorem:
The squared error of the collective prediction equals the average squared error minus the predictive diversity.
Therefore, when the diversity in a group is large, the error of the crowd is small.
Definitions
Average Individual Error: Average of the individual squared errors
Collective Error: Squared error of the collective prediction
Prediction Diversity: Average squared distance from the individual predictions to the collective prediction
Diversity Prediction Theorem: Given a crowd of predictive models, then
Collective Error = Average Individual Error ─ Prediction Diversity
Task
For a given true value and a number of number of estimates (from a crowd), show (here on this page):
the true value and the crowd estimates
the average error
the crowd error
the prediction diversity
Use (at least) these two examples:
a true value of 49 with crowd estimates of: 48 47 51
a true value of 49 with crowd estimates of: 48 47 51 42
Also see
Wikipedia entry: Wisdom of the crowd
University of Michigan: PDF paper (exists on a web archive, the Wayback Machine).
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import "fmt"
func averageSquareDiff(f float64, preds []float64) (av float64) {
for _, pred := range preds {
av += (pred - f) * (pred - f)
}
av /= float64(len(preds))
return
}
func diversityTheorem(truth float64, preds []float64) (float64, float64, float64) {
av := 0.0
for _, pred := range preds {
av += pred
}
av /= float64(len(preds))
avErr := averageSquareDiff(truth, preds)
crowdErr := (truth - av) * (truth - av)
div := averageSquareDiff(av, preds)
return avErr, crowdErr, div
}
func main() {
predsArray := [2][]float64{{48, 47, 51}, {48, 47, 51, 42}}
truth := 49.0
for _, preds := range predsArray {
avErr, crowdErr, div := diversityTheorem(truth, preds)
fmt.Printf("Average-error : %6.3f\n", avErr)
fmt.Printf("Crowd-error : %6.3f\n", crowdErr)
fmt.Printf("Diversity : %6.3f\n\n", div)
}
} |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #Scala | Scala | object Sphere extends App {
private val (shades, light) = (Seq('.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@'), Array(30d, 30d, -50d))
private def drawSphere(r: Double, k: Double, ambient: Double): Unit = {
def dot(x: Array[Double], y: Array[Double]) = {
val d = x.head * y.head + x(1) * y(1) + x.last * y.last
if (d < 0) -d else 0D
}
for (i <- math.floor(-r).toInt to math.ceil(r).toInt; x = i + .5)
println(
(for (j <- math.floor(-2 * r).toInt to math.ceil(2 * r).toInt; y = j / 2.0 + .5)
yield if (x * x + y * y <= r * r) {
def intensity(vec: Array[Double]) = {
val b = math.pow(dot(light, vec), k) + ambient
if (b <= 0) shades.length - 2
else math.max((1 - b) * (shades.length - 1), 0).toInt
}
shades(intensity(normalize(Array(x, y, scala.math.sqrt(r * r - x * x - y * y)))))
} else ' ').mkString)
}
private def normalize(v: Array[Double]): Array[Double] = {
val len = math.sqrt(v.head * v.head + v(1) * v(1) + v.last * v.last)
v.map(_ / len)
}
normalize(light).copyToArray(light)
drawSphere(20, 4, .1)
drawSphere(10, 2, .4)
} |
http://rosettacode.org/wiki/Display_an_outline_as_a_nested_table | Display an outline as a nested table |
Display an outline as a nested table.
Parse the outline to a tree,
count the leaves descending from each node,
and write out a table with 'colspan' values
measuring the indent of each line,
translating the indentation to a nested structure,
and padding the tree to even depth.
defining the width of a leaf as 1,
and the width of a parent node as a sum.
either as a wiki table,
or as HTML.
(The sum of the widths of its children)
The graphic representation of outlines is a staple of mind-mapping and the planning of papers, reports, and speeches.
Task
Given a outline with at least 3 levels of indentation, for example:
Display an outline as a nested table.
Parse the outline to a tree,
measuring the indent of each line,
translating the indentation to a nested structure,
and padding the tree to even depth.
count the leaves descending from each node,
defining the width of a leaf as 1,
and the width of a parent node as a sum.
(The sum of the widths of its children)
and write out a table with 'colspan' values
either as a wiki table,
or as HTML.
write a program in your language which translates your outline into a nested table, with WikiTable or HTML colspan values attached (where needed) to parent nodes in the nested table.
The WikiTable at the top of this page was generated from the indented outline shown above, producing the following markup string:
{| class="wikitable" style="text-align: center;"
|-
| style="background: #ffffe6; " colspan=7 | Display an outline as a nested table.
|-
| style="background: #ffebd2; " colspan=3 | Parse the outline to a tree,
| style="background: #f0fff0; " colspan=2 | count the leaves descending from each node,
| style="background: #e6ffff; " colspan=2 | and write out a table with 'colspan' values
|-
| style="background: #ffebd2; " | measuring the indent of each line,
| style="background: #ffebd2; " | translating the indentation to a nested structure,
| style="background: #ffebd2; " | and padding the tree to even depth.
| style="background: #f0fff0; " | defining the width of a leaf as 1,
| style="background: #f0fff0; " | and the width of a parent node as a sum.
| style="background: #e6ffff; " | either as a wiki table,
| style="background: #e6ffff; " | or as HTML.
|-
| |
| |
| |
| |
| style="background: #f0fff0; " | (The sum of the widths of its children)
| |
| |
|}
Extra credit
Use background color to distinguish the main stages of your outline, so that the subtree of each node at level two is consistently colored, and the edges between adjacent subtrees are immediately revealed.
Output
Display your nested table on this page.
| #Haskell | Haskell | {-# LANGUAGE TupleSections #-}
module OutlineTree where
import Data.Bifunctor (first)
import Data.Bool (bool)
import Data.Char (isSpace)
import Data.List (find, intercalate)
import Data.Tree (Tree (..), foldTree, levels)
---------------- NESTED TABLES FROM OUTLINE --------------
wikiTablesFromOutline :: [String] -> String -> String
wikiTablesFromOutline colorSwatch outline =
intercalate "\n\n" $
wikiTableFromTree colorSwatch
<$> ( forestFromLineIndents
. indentLevelsFromLines
. lines
)
outline
wikiTableFromTree :: [String] -> Tree String -> String
wikiTableFromTree colorSwatch =
wikiTableFromRows
. levels
. paintedTree colorSwatch
. widthLabelledTree
. (paddedTree "" <*> treeDepth)
--------------------------- TEST -------------------------
main :: IO ()
main =
( putStrLn
. wikiTablesFromOutline
[ "#ffffe6",
"#ffebd2",
"#f0fff0",
"#e6ffff",
"#ffeeff"
]
)
"Display an outline as a nested table.\n\
\ Parse the outline to a tree,\n\
\ measuring the indent of each line,\n\
\ translating the indentation to a nested structure,\n\
\ and padding the tree to even depth.\n\
\ count the leaves descending from each node,\n\
\ defining the width of a leaf as 1,\n\
\ and the width of a parent node as a sum.\n\
\ (The sum of the widths of its children)\n\
\ and write out a table with 'colspan' values\n\
\ either as a wiki table,\n\
\ or as HTML."
------------- TREE STRUCTURE FROM NESTED TEXT ------------
forestFromLineIndents :: [(Int, String)] -> [Tree String]
forestFromLineIndents = go
where
go [] = []
go ((n, s) : xs) =
let (subOutline, rest) = span ((n <) . fst) xs
in Node s (go subOutline) : go rest
indentLevelsFromLines :: [String] -> [(Int, String)]
indentLevelsFromLines xs =
let pairs = first length . span isSpace <$> xs
indentUnit = maybe 1 fst (find ((0 <) . fst) pairs)
in first (`div` indentUnit) <$> pairs
---------------- TREE PADDED TO EVEN DEPTH ---------------
paddedTree :: a -> Tree a -> Int -> Tree a
paddedTree padValue = go
where
go tree n
| 1 >= n = tree
| otherwise =
Node
(rootLabel tree)
( (`go` pred n)
<$> bool nest [Node padValue []] (null nest)
)
where
nest = subForest tree
treeDepth :: Tree a -> Int
treeDepth = foldTree go
where
go _ [] = 1
go _ xs = (succ . maximum) xs
----------------- SUBTREE WIDTHS MEASURED ----------------
widthLabelledTree :: Tree a -> Tree (a, Int)
widthLabelledTree = foldTree go
where
go x [] = Node (x, 1) []
go x xs =
Node
(x, foldr ((+) . snd . rootLabel) 0 xs)
xs
------------------- COLOR SWATCH APPLIED -----------------
paintedTree :: [String] -> Tree a -> Tree (String, a)
paintedTree [] tree = fmap ("",) tree
paintedTree (color : colors) tree =
Node
(color, rootLabel tree)
( zipWith
(fmap . (,))
(cycle colors)
(subForest tree)
)
-------------------- WIKITABLE RENDERED ------------------
wikiTableFromRows :: [[(String, (String, Int))]] -> String
wikiTableFromRows rows =
let wikiRow = unlines . fmap cellText
cellText (color, (txt, width))
| null txt = "| |"
| otherwise =
"| "
<> cw color width
<> "| "
<> txt
cw color width =
let go w
| 1 < w = " colspan=" <> show w
| otherwise = ""
in "style=\"background:"
<> color
<> "; \""
<> go width
<> " "
in "{| class=\"wikitable\" "
<> "style=\"text-align: center;\"\n|-\n"
<> intercalate "|-\n" (wikiRow <$> rows)
<> "|}" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.