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/Doubly-linked_list/Definition
Doubly-linked list/Definition
Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#AutoHotkey
AutoHotkey
/* double linked list */ #include <stdio.h> #include <stdlib.h>   struct List { struct MNode *head; struct MNode *tail; struct MNode *tail_pred; };   struct MNode { struct MNode *succ; struct MNode *pred; };   typedef struct MNode *NODE; typedef struct List *LIST;   /* ** LIST l = newList() ** create (alloc space for) and initialize a list */ LIST newList(void);   /* ** int isEmpty(LIST l) ** test if a list is empty */ int isEmpty(LIST);   /* ** NODE n = getTail(LIST l) ** get the tail node of the list, without removing it */ NODE getTail(LIST);   /* ** NODE n = getHead(LIST l) ** get the head node of the list, without removing it */ NODE getHead(LIST);   /* ** NODE rn = addTail(LIST l, NODE n) ** add the node n to the tail of the list l, and return it (rn==n) */ NODE addTail(LIST, NODE);   /* ** NODE rn = addHead(LIST l, NODE n) ** add the node n to the head of the list l, and return it (rn==n) */ NODE addHead(LIST, NODE);   /* ** NODE n = remHead(LIST l) ** remove the head node of the list and return it */ NODE remHead(LIST);   /* ** NODE n = remTail(LIST l) ** remove the tail node of the list and return it */ NODE remTail(LIST);   /* ** NODE rn = insertAfter(LIST l, NODE r, NODE n) ** insert the node n after the node r, in the list l; return n (rn==n) */ NODE insertAfter(LIST, NODE, NODE);   /* ** NODE rn = removeNode(LIST l, NODE n) ** remove the node n (that must be in the list l) from the list and return it (rn==n) */ NODE removeNode(LIST, NODE);     LIST newList(void) { LIST tl = malloc(sizeof(struct List)); if ( tl != NULL ) { tl->tail_pred = (NODE)&tl->head; tl->tail = NULL; tl->head = (NODE)&tl->tail; return tl; } return NULL; }   int isEmpty(LIST l) { return (l->head->succ == 0); }   NODE getHead(LIST l) { return l->head; }   NODE getTail(LIST l) { return l->tail_pred; }     NODE addTail(LIST l, NODE n) { n->succ = (NODE)&l->tail; n->pred = l->tail_pred; l->tail_pred->succ = n; l->tail_pred = n; return n; }   NODE addHead(LIST l, NODE n) { n->succ = l->head; n->pred = (NODE)&l->head; l->head->pred = n; l->head = n; return n; }   NODE remHead(LIST l) { NODE h; h = l->head; l->head = l->head->succ; l->head->pred = (NODE)&l->head; return h; }   NODE remTail(LIST l) { NODE t; t = l->tail_pred; l->tail_pred = l->tail_pred->pred; l->tail_pred->succ = (NODE)&l->tail; return t; }   NODE insertAfter(LIST l, NODE r, NODE n) { n->pred = r; n->succ = r->succ; n->succ->pred = n; r->succ = n; return n; }   NODE removeNode(LIST l, NODE n) { n->pred->succ = n->succ; n->succ->pred = n->pred; return n; }
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.
#Raku
Raku
my $outline = q:to/END/; 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. END   # Import outline paragraph into native data structure sub import (Str $trees, $level = ' ') { my $forest; my $last = -Inf;   for $trees.lines -> $branch { $branch ~~ / ($($level))* /; my $this = +$0; $forest ~= do { given $this cmp $last { when More { "\['{esc $branch.trim}', " } when Same { "'{esc $branch.trim}', " } when Less { "{']' x $last - $this}, '{esc $branch.trim}', " } } } $last = $this; }   sub esc { $^s.subst( /(<['\\]>)/, -> $/ { "\\$0" }, :g) }   $forest ~= ']' x 1 + $last; use MONKEY-SEE-NO-EVAL; $forest.EVAL; }   my @AoA = import $outline, ' '; my @layout;   # Collect information about node depth, position and children { my @width = 0; my $depth = -1; @AoA.&insert;   multi insert ($item) { @width[*-1]++; @layout.push: { :depth($depth.clone), :id(@width[*-1].clone), :text($item) }; }   multi insert (@array) { @width.push: @width[*-1] * 10; ++$depth; @array.map: &insert; --$depth; @width.pop; } }   my $max-depth = @layout.max( *.<depth> )<depth>;   # Pad ragged nodes for (^$max-depth) -> $d { my @nodes = @layout.grep( *.<depth> == $d ); for @nodes.sort( +*.<id> ) -> $n { unless @layout.first( *.<id> == $n<id> ~ 1 ) { @layout.push: { :depth($n<depth> + 1), :id($n<id> *10 + 1), :text('') }; } } }   # Calculate spans (child nodes) for (0..$max-depth).reverse -> $d { my @nodes = @layout.grep( *.<depth> == $d ); for @nodes.sort( +*.<id> ) -> $n { my @span = @layout.grep: {.<depth> == $d + 1 && .<id>.starts-with: $n<id> }; $n<span> = ( sum @span.map( { .<span> // 0} )) || +@span || 1; } }   # Programatically assign colors for (0..$max-depth) -> $d { my @nodes = @layout.grep( *.<depth> == $d ); my $incr = 1 / (1 + @nodes); for @nodes.sort( +*.<id> ) -> $n { my $color = $d > 1 ?? @layout.first( *.<id> eq $n<id>.chop )<color> !! "style=\"background: #" ~ hsv2rgb( ++$ * $incr, .1, 1) ~ '" '; $n<color> = $n<text> ?? $color !! ''; } }   # Generate wikitable say '{| class="wikitable" style="text-align: center;"' ~ "\n" ~ (join "\n|-\n", (0..$max-depth).map: -> $d { my @nodes = @layout.grep( *.<depth> == $d ); (join "\n", @nodes.sort( +*.<id> ).map( -> $node { '| ' ~ ($node<color> // '' ) ~ ($node<span> > 1 ?? "colspan=$node<span>" !! '' ) ~ ' | ' ~ $node<text> } )) }) ~ "\n|}";   say "\n\nSometimes it makes more sense to display an outline as... well... as an outline, rather than as a table." ~ Q|¯\_(ツ)_/¯| ~ "\n";   { ## Outline - Ordered List ####### my @type = <upper-roman upper-latin decimal lower-latin lower-roman>; my $depth = 0;   multi ol ($item) { "\<li>$item\n" }   multi ol (@array) { my $li = $depth ?? "</li>" !! ''; $depth++; my $list = "<ol style=\"list-style: {@type[$depth - 1]};\">\n" ~ ( @array.map( &ol ).join ) ~ "</ol>$li\n"; $depth--; $list }   say "<div style=\"background: #fee;\">\n" ~ @AoA.&ol ~ "</div>"; }   sub hsv2rgb ( $h, $s, $v ){ my $c = $v * $s; my $x = $c * (1 - abs( (($h*6) % 2) - 1 ) ); my $m = $v - $c; my ($r, $g, $b) = do given $h { when 0..^(1/6) { $c, $x, 0 } when 1/6..^(1/3) { $x, $c, 0 } when 1/3..^(1/2) { 0, $c, $x } when 1/2..^(2/3) { 0, $x, $c } when 2/3..^(5/6) { $x, 0, $c } when 5/6..1 { $c, 0, $x } } ( $r, $g, $b ).map( ((*+$m) * 255).Int)».base(16).join }
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
#Yabasic
Yabasic
clear screen open window 300,100 backcolor 0, 0, 0 window origin "cc"   // Display digital clock sub digital_clock() local t$(1), void static as$   void = token(time$, t$(), "-")   if t$(3) <> as$ then draw_clock(t$(1), t$(2), t$(3)) as$ = t$(3) end if end sub   sub draw_clock(hour$, mint$, ssec$) local d$(1), void   void = token(date$, d$(), "-") clear window color 200, 255, 0 text -140, -30, d$(3) + "/" + d$(2) + "/" + d$(4), "modern12" text 0, 0, hour$ + ":" + mint$ + ":" + ssec$, "cc", "swiss50" end sub   if peek$("library") = "main" then repeat digital_clock() until(upper$(inkey$(.01))="ESC") exit end if
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.
#Phix
Phix
without js -- (zmq dll/so) puts(1, "durapub:\n") include zmq/zmq.e atom context = zmq_init(1) zmq_assert(context, "zmq_init") --// subscriber tells us when it's ready here atom sync = zmq_socket(context, ZMQ_PULL) zmq_bind(sync, "tcp://*:5564") --// send update via this socket atom publisher = zmq_socket(context, ZMQ_PUB) zmq_bind(publisher, "tcp://*:5565") --// broadcast 10 updates, with pause for update_nbr = 1 to 10 do string s = sprintf("Update %d", { update_nbr }) zmq_s_send(publisher, s) sleep(1) end for zmq_s_send(publisher, "END") sleep(1) zmq_close(sync) zmq_close(publisher) zmq_term(context)
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.
#Julia
Julia
  julia> using Sockets   julia> getaddrinfo("www.kame.net") ip"203.178.141.194"   julia> getaddrinfo("www.kame.net", IPv6) ip"2001:200:dff:fff1:216:3eff:feb1:44d7"    
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.
#Kotlin
Kotlin
// version 1.1.3   import java.net.InetAddress import java.net.Inet4Address import java.net.Inet6Address   fun showIPAddresses(host: String) { try { val ipas = InetAddress.getAllByName(host) println("The IP address(es) for '$host' is/are:\n") for (ipa in ipas) { print(when (ipa) { is Inet4Address -> " ipv4 : " is Inet6Address -> " ipv6 : " else -> " ipv? : " }) println(ipa.hostAddress) } } catch (ex: Exception) { println(ex.message) } }   fun main(args: Array<String>) { showIPAddresses("www.kame.net") }
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.
#PostScript
PostScript
%!PS %%BoundingBox: 0 0 550 400 /ifpendown false def /rotation 0 def /srootii 2 sqrt def /turn { rotation add /rotation exch def } def /forward { dup rotation cos mul exch rotation sin mul ifpendown { rlineto } { rmoveto } ifelse } def /penup { /ifpendown false def } def /pendown { /ifpendown true def } def   /dragon { % [ length, split, d ] dup dup 1 get 0 eq { 0 get forward } { dup 2 get 45 mul turn dup aload pop pop 1 sub exch srootii div exch 1 3 array astore dragon pop dup 2 get 90 mul neg turn dup aload pop pop 1 sub exch srootii div exch -1 3 array astore dragon dup 2 get 45 mul turn } ifelse pop } def 150 150 moveto pendown [ 300 12 1 ] dragon stroke % 0 0 moveto 550 0 rlineto 0 400 rlineto -550 0 rlineto closepath stroke showpage %%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
#jq
jq
def linearCombo: reduce to_entries[] as {key: $k,value: $v} (""; if $v == 0 then . else (if $v < 0 and length==0 then "-" elif $v < 0 then " - " elif $v > 0 and length==0 then "" else " + " end) as $sign | ($v|fabs) as $av | (if ($av == 1) then "" else "\($av)*" end) as $coeff | . + "\($sign)\($coeff)e\($k)" end) | if length==0 then "0" else . end ;   # The exercise def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;   [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] | "\(lpad(15)) => \(linearCombo)"  
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
#Julia
Julia
# v0.6   linearcombination(coef::Array) = join(collect("$c * e($i)" for (i, c) in enumerate(coef) if c != 0), " + ")   for c in [[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]] @printf("%20s -> %s\n", c, linearcombination(c)) end
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Nim
Nim
## Nim directly supports documentation using comments that start with two ## hashes (##). To create the documentation run ``nim doc file.nim``. ## ``nim doc2 file.nim`` is the same, but run after semantic checking, which ## allows it to process macros and output more information. ## ## These are the comments for the entire module. We can have long descriptions ## here. Syntax is reStructuredText. Only exported symbols (*) get ## documentation created for them. ## ## Here comes a code block inside our documentation: ## ## .. code-block:: nim ## var inputStrings : seq[string] ## newSeq(inputStrings, 3) ## inputStrings[0] = "The fourth" ## inputStrings[1] = "assignment" ## inputStrings[2] = "would crash" ## #inputStrings[3] = "out of bounds"   type TPerson* = object ## This type contains a description of a person name: string age: int   var numValues*: int ## \ ## `numValues` stores the number of values   proc helloWorld*(times: int) = ## A useful procedure for i in 1..times: echo "hello world"
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Objeck
Objeck
#~ Sets the named row value @param name name @param value value @return true of value was set, false otherwise ~# method : public : Set(name : String, value : String) ~ Bool { return Set(@table->GetRowId(name), value); }  
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Objective-C
Objective-C
/*! @function add @abstract Adds two numbers @discussion Use add to sum two numbers. @param a an integer. @param b another integer. @return the sum of a and b */ int add(int a, int b) { return a + b; }
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).
#Kotlin
Kotlin
// version 1.1.4-3   fun square(d: Double) = d * d   fun averageSquareDiff(d: Double, predictions: DoubleArray) = predictions.map { square(it - d) }.average()   fun diversityTheorem(truth: Double, predictions: DoubleArray): String { val average = predictions.average() val f = "%6.3f" return "average-error : ${f.format(averageSquareDiff(truth, predictions))}\n" + "crowd-error  : ${f.format(square(truth - average))}\n" + "diversity  : ${f.format(averageSquareDiff(average, predictions))}\n" }   fun main(args: Array<String>) { println(diversityTheorem(49.0, doubleArrayOf(48.0, 47.0, 51.0))) println(diversityTheorem(49.0, doubleArrayOf(48.0, 47.0, 51.0, 42.0))) }
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).
#Lua
Lua
function square(x) return x * x end   function mean(a) local s = 0 local c = 0 for i,v in pairs(a) do s = s + v c = c + 1 end return s / c end   function averageSquareDiff(a, predictions) local results = {} for i,x in pairs(predictions) do table.insert(results, square(x - a)) end return mean(results) end   function diversityTheorem(truth, predictions) local average = mean(predictions) print("average-error: " .. averageSquareDiff(truth, predictions)) print("crowd-error: " .. square(truth - average)) print("diversity: " .. averageSquareDiff(average, predictions)) end   function main() diversityTheorem(49, {48, 47, 51}) diversityTheorem(49, {48, 47, 51, 42}) end   main()
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
#VBScript
VBScript
shades = Array(".", ":", "!", "*", "o", "e", "&", "#", "%", "@") light = Array(30, 30, -50)   Sub Normalize(v) length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2)) v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length End Sub   Function Dot(x, y) d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2) If d < 0 Then Dot = -d Else Dot = 0 End If End Function   'floor function is the Int function 'ceil function implementation Function Ceil(x) Ceil = Int(x) If Ceil <> x Then Ceil = Ceil + 1 End if End Function   Sub DrawSphere(R, k, ambient) Dim i, j, intensity, inten, b, x, y Dim vec(3) For i = Int(-R) to Ceil(R) x = i + 0.5 line = "" For j = Int(-2*R) to Ceil(2*R) y = j / 2 + 0.5 If x * x + y * y <= R*R Then vec(0) = x vec(1) = y vec(2) = Sqr(R * R - x * x - y * y) Normalize vec b = dot(light, vec)^k + ambient intensity = Int((1 - b) * UBound(shades)) If intensity < 0 Then intensity = 0 End If If intensity >= UBound(shades) Then intensity = UBound(shades) End If line = line & shades(intensity) Else line = line & " " End If Next WScript.StdOut.WriteLine line Next End Sub   Normalize light DrawSphere 20, 4, 0.1 DrawSphere 10,2,0.4
http://rosettacode.org/wiki/Doubly-linked_list/Definition
Doubly-linked list/Definition
Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#C
C
/* double linked list */ #include <stdio.h> #include <stdlib.h>   struct List { struct MNode *head; struct MNode *tail; struct MNode *tail_pred; };   struct MNode { struct MNode *succ; struct MNode *pred; };   typedef struct MNode *NODE; typedef struct List *LIST;   /* ** LIST l = newList() ** create (alloc space for) and initialize a list */ LIST newList(void);   /* ** int isEmpty(LIST l) ** test if a list is empty */ int isEmpty(LIST);   /* ** NODE n = getTail(LIST l) ** get the tail node of the list, without removing it */ NODE getTail(LIST);   /* ** NODE n = getHead(LIST l) ** get the head node of the list, without removing it */ NODE getHead(LIST);   /* ** NODE rn = addTail(LIST l, NODE n) ** add the node n to the tail of the list l, and return it (rn==n) */ NODE addTail(LIST, NODE);   /* ** NODE rn = addHead(LIST l, NODE n) ** add the node n to the head of the list l, and return it (rn==n) */ NODE addHead(LIST, NODE);   /* ** NODE n = remHead(LIST l) ** remove the head node of the list and return it */ NODE remHead(LIST);   /* ** NODE n = remTail(LIST l) ** remove the tail node of the list and return it */ NODE remTail(LIST);   /* ** NODE rn = insertAfter(LIST l, NODE r, NODE n) ** insert the node n after the node r, in the list l; return n (rn==n) */ NODE insertAfter(LIST, NODE, NODE);   /* ** NODE rn = removeNode(LIST l, NODE n) ** remove the node n (that must be in the list l) from the list and return it (rn==n) */ NODE removeNode(LIST, NODE);     LIST newList(void) { LIST tl = malloc(sizeof(struct List)); if ( tl != NULL ) { tl->tail_pred = (NODE)&tl->head; tl->tail = NULL; tl->head = (NODE)&tl->tail; return tl; } return NULL; }   int isEmpty(LIST l) { return (l->head->succ == 0); }   NODE getHead(LIST l) { return l->head; }   NODE getTail(LIST l) { return l->tail_pred; }     NODE addTail(LIST l, NODE n) { n->succ = (NODE)&l->tail; n->pred = l->tail_pred; l->tail_pred->succ = n; l->tail_pred = n; return n; }   NODE addHead(LIST l, NODE n) { n->succ = l->head; n->pred = (NODE)&l->head; l->head->pred = n; l->head = n; return n; }   NODE remHead(LIST l) { NODE h; h = l->head; l->head = l->head->succ; l->head->pred = (NODE)&l->head; return h; }   NODE remTail(LIST l) { NODE t; t = l->tail_pred; l->tail_pred = l->tail_pred->pred; l->tail_pred->succ = (NODE)&l->tail; return t; }   NODE insertAfter(LIST l, NODE r, NODE n) { n->pred = r; n->succ = r->succ; n->succ->pred = n; r->succ = n; return n; }   NODE removeNode(LIST l, NODE n) { n->pred->succ = n->succ; n->succ->pred = n->pred; return n; }
http://rosettacode.org/wiki/Disarium_numbers
Disarium numbers
A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number. E.G. 135 is a Disarium number: 11 + 32 + 53 == 1 + 9 + 125 == 135 There are a finite number of Disarium numbers. Task Find and display the first 18 Disarium numbers. Stretch Find and display all 20 Disarium numbers. See also Geeks for Geeks - Disarium numbers OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...) Related task: Narcissistic decimal number Related task: Own digits power sum Which seems to be the same task as Narcissistic decimal number...
#ALGOL_68
ALGOL 68
BEGIN # find some Disarium numbers - numbers whose digit position-power sums # # are equal to the number, e.g. 135 = 1^1 + 3^2 + 5^3 # # compute the nth powers of 0-9 # [ 1 : 9, 0 : 9 ]INT power; FOR d FROM 0 TO 9 DO power[ 1, d ] := d OD; FOR n FROM 2 TO 9 DO power[ n, 0 ] := 0; FOR d TO 9 DO power[ n, d ] := power[ n - 1, d ] * d OD OD; # print the first few Disarium numbers # INT max disarium = 19; INT count := 0; INT power of ten := 10; INT length := 1; FOR n FROM 0 WHILE count < max disarium DO IF n = power of ten THEN # the number of digits just increased # power of ten *:= 10; length +:= 1 FI; # form the digit power sum # INT v := n; INT dps := 0; FOR p FROM length BY -1 TO 1 DO dps +:= power[ p, v MOD 10 ]; v OVERAB 10 OD; IF dps = n THEN # n is Disarium # count +:= 1; print( ( " ", whole( n, 0 ) ) ) FI OD 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.
#Wren
Wren
import "/dynamic" for Struct import "/fmt" for Fmt   var NNode = Struct.create("NNode", ["name", "children"]) var INode = Struct.create("INode", ["level", "name"])   var toNest // recursive function toNest = Fn.new { |iNodes, start, level, n| if (level == 0) n.name = iNodes[0].name var i = start + 1 while (i < iNodes.count) { if (iNodes[i].level == level+1) { var c = NNode.new(iNodes[i].name, []) toNest.call(iNodes, i, level+1, c) n.children.add(c) } else if (iNodes[i].level <= level) { return } i = i + 1 } }   var makeIndent = Fn.new { |outline, tab| var lines = outline.split("\n") var iNodes = List.filled(lines.count, null) var i = 0 for (line in lines) { var line2 = line.trimStart(" ") var le = line.count var le2 = line2.count var level = ((le - le2) / tab).floor iNodes[i] = INode.new(level, line2) i = i + 1 } return iNodes }   var toMarkup = Fn.new { |n, cols, depth| var span = 0 var colSpan // recursive closure colSpan = Fn.new { |nn| var i = 0 for (c in nn.children) { if (i > 0) span = span + 1 colSpan.call(c) i = i + 1 } }   for (c in n.children) { span = 1 colSpan.call(c) } var lines = [] lines.add("{| class=\"wikitable\" style=\"text-align: center;\"") var l1 = "|-" var l2 = "| |" lines.add(l1) span = 1 colSpan.call(n) var s = Fmt.swrite("| style=\"background: $s \" colSpan=$d | $s", cols[0], span, n.name) lines.add(s) lines.add(l1)   var nestedFor // recursive function nestedFor = Fn.new { |nn, level, maxLevel, col| if (level == 1 && maxLevel > level) { var i = 0 for (c in nn.children) { nestedFor.call(c, 2, maxLevel, i) i = i + 1 } } else if (level < maxLevel) { for (c in nn.children) { nestedFor.call(c, level+1, maxLevel, col) } } else { if (nn.children.count > 0) { var i = 0 for (c in nn.children) { span = 1 colSpan.call(c) var cn = col + 1 if (maxLevel == 1) cn = i + 1 var s = Fmt.swrite("| style=\"background: $s \" colspan=$d | $s", cols[cn], span, c.name) lines.add(s) i = i + 1 } } else { lines.add(l2) } } } for (maxLevel in 1...depth) { nestedFor.call(n, 1, maxLevel, 0) if (maxLevel < depth-1) lines.add(l1) } lines.add("|}") return lines.join("\n") }   var 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. """ var yellow = "#ffffe6;" var orange = "#ffebd2;" var green = "#f0fff0;" var blue = "#e6ffff;" var pink = "#ffeeff;"   var cols = [yellow, orange, green, blue, pink] var iNodes = makeIndent.call(outline, 4) var n = NNode.new("", []) toNest.call(iNodes, 0, 0, n) System.print(toMarkup.call(n, cols, 4))   System.print("\n") var 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. """ var cols2 = [blue, yellow, orange, green, pink] var n2 = NNode.new("", []) var iNodes2 = makeIndent.call(outline2, 4) toNest.call(iNodes2, 0, 0, n2) System.print(toMarkup.call(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
#zkl
zkl
var t=T("⡎⢉⢵","⠀⢺⠀","⠊⠉⡱","⠊⣉⡱","⢀⠔⡇","⣏⣉⡉","⣎⣉⡁","⠊⢉⠝","⢎⣉⡱","⡎⠉⢱","⠀⠶⠀"), b=T("⢗⣁⡸","⢀⣸⣀","⣔⣉⣀","⢄⣀⡸","⠉⠉⡏","⢄⣀⡸","⢇⣀⡸","⢰⠁⠀","⢇⣀⡸","⢈⣉⡹","⠀⠶ "); while(True){ x:=Time.Date.ctime()[11,8] // or Time.Date.to24HString() (no seconds) .pump(List,fcn(n){ n.toAsc() - 0x30 }); //-->L(2,3,10,4,3,10,5,2) print("\e[H\e[J"); // home and clear screen on ANSI terminals println(x.pump(String,t.get),"\n",x.pump(String,b.get)); Atomic.sleep(1); }
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.
#PicoLisp
PicoLisp
(task (port 12321) # Background server task (let? Sock (accept @) (unless (fork) # Handle request in child process (in Sock (while (rd) # Handle requests (out Sock (pr (eval @)) ) ) ) # Evaluate and send reply (bye) ) # Exit child process (close Sock) ) ) # Close socket in parent process
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.
#Python
Python
#!/usr/bin/env python # -*- coding: utf-8 -*-   import SimpleXMLRPCServer   class MyHandlerInstance: def echo(self, data): '''Method for returning data got from client''' return 'Server responded: %s' % data   def div(self, num1, num2): '''Method for divide 2 numbers''' return num1/num2   def foo_function(): '''A function (not an instance method)''' return True   HOST = "localhost" PORT = 8000   server = SimpleXMLRPCServer.SimpleXMLRPCServer((HOST, PORT))   # register built-in system.* functions. server.register_introspection_functions()   # register our instance server.register_instance(MyHandlerInstance())   # register our function as well server.register_function(foo_function)   try: # serve forever server.serve_forever() except KeyboardInterrupt: print 'Exiting...' server.server_close()
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.
#Lasso
Lasso
dns_lookup('www.kame.net', -type='A')
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.
#Lua
Lua
local socket = require('socket') local ip_tbl = socket.dns.getaddrinfo('www.kame.net')   for _, v in ipairs(ip_tbl) do io.write(string.format('%s: %s\n', v.family, v.addr)) end  
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.
#Neko
Neko
/* dns in neko */ var host_resolve = $loader.loadprim("std@host_resolve", 1); var host_to_string = $loader.loadprim("std@host_to_string", 1); var host_reverse = $loader.loadprim("std@host_reverse", 1);   var ip = host_resolve("www.kame.net");   $print("www.kame.net: ", ip, ", ", host_to_string(ip), "\n"); $print(host_to_string(ip), ": ", host_reverse(ip), "\n");
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.
#POV-Ray
POV-Ray
# handy constants with script-wide scope [Single]$script:QUARTER_PI=0.7853982 [Single]$script:HALF_PI=1.570796   # leverage GDI (Forms and Drawing) Add-Type -AssemblyName System.Drawing Add-Type -AssemblyName System.Windows.Forms $script:TurtlePen = New-Object Drawing.Pen darkGreen $script:Form = New-Object Windows.Forms.Form $script:Canvas = $Form.CreateGraphics()   # implement a turtle graphics model Class Turtle { # relies on the script-scoped $TurtlePen and $Canvas # member properties for turtle's position and orientation [Single]$TurtleX [Single]$TurtleY [Single]$TurtleAngle   # constructors Turtle() { $this.TurtleX, $this.TurtleY = 44.0, 88.0 $this.TurtleAngle = 0.0 } Turtle([Single]$InitX, [Single]$InitY, [Single]$InitAngle) { $this.TurtleX, $this.TurtleY = $InitX, $InitY $this.TurtleAngle = $InitAngle }   # methods for turning and drawing [Void]Turn([Single]$Angle) { # $Angle measured in radians $this.TurtleAngle += $Angle # use positive $Angle for right turn, negative for left turn } [Void]Forward([Single]$Distance) { # draw line segment $TargetX = $this.TurtleX + $Distance * [Math]::Cos($this.TurtleAngle) $TargetY = $this.TurtleY + $Distance * [Math]::Sin($this.TurtleAngle) $script:Canvas.DrawLine($script:TurtlePen, $this.TurtleX, $this.TurtleY, $TargetX, $TargetY) # relocate turtle to other end of segment $this.TurtleX = $TargetX $this.TurtleY = $TargetY } } # end of Turtle class definition   # Implement dragon curve drawing methods in a subclass that inherits Turtle Class DragonTurtle : Turtle {   # DCL: recursive dragon curve, starting with left turns [Void]DCL([Byte]$Step, [Single]$Length) { $AdjustedStep = $Step - 1 $AdjustedLength = $Length / [Math]::Sqrt(2.0)   $this.Turn(-$script:QUARTER_PI) if ($AdjustedStep -gt 0) { $this.DCR($AdjustedStep, $AdjustedLength) } else { $this.Forward($AdjustedLength) } $this.Turn($script:HALF_PI) if ($AdjustedStep -gt 0) { $this.DCL($AdjustedStep, $AdjustedLength) } else { $this.Forward($AdjustedLength) } $this.Turn(-$script:QUARTER_PI) }   # DCR: recursive dragon curve, starting with right turns [Void]DCR([Byte]$Step, [Single]$Length) { $AdjustedStep = $Step - 1 $AdjustedLength = $Length / [Math]::Sqrt(2.0)   $this.Turn($script:QUARTER_PI) if ($AdjustedStep -gt 0) { $this.DCR($AdjustedStep, $AdjustedLength) } else { $this.Forward($AdjustedLength) } $this.Turn(-$script:HALF_PI) if ($AdjustedStep -gt 0) { $this.DCL($AdjustedStep, $AdjustedLength) } else { $this.Forward($AdjustedLength) } $this.Turn($script:QUARTER_PI) } } # end of DragonTurtle subclass definition   # prepare anonymous dragon-curve painting function for WinForms dialog $Form.add_paint({ [DragonTurtle]$Dragon = [DragonTurtle]::new() $Dragon.DCR(14,128) })   # display the GDI Form window, which triggers its prepared anonymous drawing function $Form.ShowDialog()  
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
#Kotlin
Kotlin
// version 1.1.2   fun linearCombo(c: IntArray): String { val sb = StringBuilder() for ((i, n) in c.withIndex()) { if (n == 0) continue val op = when { n < 0 && sb.isEmpty() -> "-" n < 0 -> " - " n > 0 && sb.isEmpty() -> "" else -> " + " } val av = Math.abs(n) val coeff = if (av == 1) "" else "$av*" sb.append("$op${coeff}e(${i + 1})") } return if(sb.isEmpty()) "0" else sb.toString() }   fun main(args: Array<String>) { val combos = arrayOf( intArrayOf(1, 2, 3), intArrayOf(0, 1, 2, 3), intArrayOf(1, 0, 3, 4), intArrayOf(1, 2, 0), intArrayOf(0, 0, 0), intArrayOf(0), intArrayOf(1, 1, 1), intArrayOf(-1, -1, -1), intArrayOf(-1, -2, 0, -3), intArrayOf(-1) ) for (c in combos) { println("${c.contentToString().padEnd(15)} -> ${linearCombo(c)}") } }
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#OCaml
OCaml
  ; note: use this script to generate a markdown file ; sed -n 's/\s*;!\s*//gp'   (import (owl parse))   ;! # Documentation   ;! ## Functions   ;! ### whitespace ;! Returns a #true if argument is a space, newline, return or tab character. (define whitespace (byte-if (lambda (x) (has? '(#\tab #\newline #\space #\return) x))))   ;! ### maybe-whitespaces ;! Returns any amount (including 0) of whitespaces. Used as whitespace characters skipper in parses. (define maybe-whitespaces (greedy* whitespace))  
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Ol
Ol
  ; note: use this script to generate a markdown file ; sed -n 's/\s*;!\s*//gp'   (import (owl parse))   ;! # Documentation   ;! ## Functions   ;! ### whitespace ;! Returns a #true if argument is a space, newline, return or tab character. (define whitespace (byte-if (lambda (x) (has? '(#\tab #\newline #\space #\return) x))))   ;! ### maybe-whitespaces ;! Returns any amount (including 0) of whitespaces. Used as whitespace characters skipper in parses. (define maybe-whitespaces (greedy* whitespace))  
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#PARI.2FGP
PARI/GP
addhelp(funcName, "funcName(v, n): This is a description of the function named funcName.");
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).
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[DiversityPredictionTheorem] DiversityPredictionTheorem[trueval_?NumericQ, estimates_List] := Module[{avg, avgerr, crowderr, diversity}, avg = Mean[estimates]; avgerr = Mean[(estimates - trueval)^2]; crowderr = (trueval - avg)^2; diversity = Mean[(estimates - avg)^2]; <| "TrueValue" -> trueval, "CrowdEstimates" -> estimates, "AverageError" -> avgerr, "CrowdError" -> crowderr, "Diversity" -> diversity |> ] DiversityPredictionTheorem[49, {48, 47, 51}] // Dataset DiversityPredictionTheorem[49, {48, 47, 51, 42}] // Dataset
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).
#Nim
Nim
import strutils, math, stats   func meanSquareDiff(refValue: float; estimates: seq[float]): float = ## Compute the mean of the squares of the differences ## between estimated values and a reference value. for estimate in estimates: result += (estimate - refValue)^2 result /= estimates.len.toFloat     const Samples = [(trueValue: 49.0, estimates: @[48.0, 47.0, 51.0]), (trueValue: 49.0, estimates: @[48.0, 47.0, 51.0, 42.0])]   for (trueValue, estimates, ) in Samples: let m = mean(estimates) echo "True value: ", trueValue echo "Estimates: ", estimates.join(", ") echo "Average error: ", meanSquareDiff(trueValue, estimates) echo "Crowd error: ", (m - trueValue)^2 echo "Prediction diversity: ", meanSquareDiff(m, estimates) echo ""
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
#Wren
Wren
var shades = ".:!*oe&#\%@" var light = [30, 30, -50]   var normalize = Fn.new { |v| var len = (v[0]*v[0] + v[1]*v[1] + v[2]*v[2]).sqrt for (i in 0..2) v[i] = v[i] / len }   var dot = Fn.new { |x, y| var d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2] return (d < 0) ? -d : 0 }   var drawSphere = Fn.new { |r, k, ambient| var vec = [0] * 3 for (i in (-r).floor..r.ceil) { var x = i + 0.5 for (j in (-2*r).floor..(2*r).ceil) { var y = j/2 + 0.5 if (x*x + y*y <= r*r) { var vec = [x, y, (r*r - x*x - y*y).sqrt] normalize.call(vec) var b = dot.call(light, vec).pow(k) + ambient var intensity = ((1 - b) * (shades.count - 1)).truncate if (intensity < 0) intensity = 0 if (intensity >= shades.count - 1) intensity = shades.count - 2 System.write(shades[intensity]) } else { System.write(" ") } } System.print() } }   normalize.call(light) drawSphere.call(20, 4, 0.1) drawSphere.call(10, 2, 0.4)
http://rosettacode.org/wiki/Doubly-linked_list/Definition
Doubly-linked list/Definition
Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#C.23
C#
using System.Collections.Generic;   class Program { static void Main(string[] args) { LinkedList<string> list = new LinkedList<string>(); list.AddFirst(".AddFirst() adds at the head."); list.AddLast(".AddLast() adds at the tail."); LinkedListNode<string> head = list.Find(".AddFirst() adds at the head."); list.AddAfter(head, ".AddAfter() adds after a specified node."); LinkedListNode<string> tail = list.Find(".AddLast() adds at the tail."); list.AddBefore(tail, "Betcha can't guess what .AddBefore() does.");   System.Console.WriteLine("Forward:"); foreach (string nodeValue in list) { System.Console.WriteLine(nodeValue); }   System.Console.WriteLine("\nBackward:"); LinkedListNode<string> current = tail; while (current != null) { System.Console.WriteLine(current.Value); current = current.Previous; } } }
http://rosettacode.org/wiki/Disarium_numbers
Disarium numbers
A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number. E.G. 135 is a Disarium number: 11 + 32 + 53 == 1 + 9 + 125 == 135 There are a finite number of Disarium numbers. Task Find and display the first 18 Disarium numbers. Stretch Find and display all 20 Disarium numbers. See also Geeks for Geeks - Disarium numbers OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...) Related task: Narcissistic decimal number Related task: Own digits power sum Which seems to be the same task as Narcissistic decimal number...
#ALGOL_W
ALGOL W
begin % find some Disarium numbers - numbers whose digit position-power sums  %  % are equal to the number, e.g. 135 = 1^1 + 3^2 + 5^3  % integer array power ( 1 :: 9, 0 :: 9 ); integer MAX_DISARIUM; integer count, powerOfTen, length, n;  % compute the nth powers of 0-9  % for d := 0 until 9 do power( 1, d ) := d; for n := 2 until 9 do begin power( n, 0 ) := 0; for d := 1 until 9 do power( n, d ) := power( n - 1, d ) * d end for_n;  % print the first few Disarium numbers  % MAX_DISARIUM := 19; count := 0; powerOfTen := 10; length := 1; n := 0; while count < MAX_DISARIUM do begin integer v, dps; if n = powerOfTen then begin  % the number of digits just increased  % powerOfTen := powerOfTen * 10; length := length + 1 end if_m_eq_powerOfTen ;  % form the digit power sum  % v := n; dps := 0; for p := length step -1 until 1 do begin dps := dps + power( p, v rem 10 ); v := v div 10; end FOR_P; if dps = n then begin  % n is Disarium  % count := count + 1; writeon( i_w := 1, s_w := 0, " ", n ) end if_dps_eq_n ; n := n + 1 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.
#zkl
zkl
fcn parseOutline(outline){ //--> "tree" annotated with spans var [const] indent=" "*100; // no tabs   parse:=fcn(ow,tree,parent,col,prevD,unit){ rows,span,spans,cell := 0, 0,List(), Void; foreach line in (ow){ if(not line) continue; d,text,d := line.prefix(indent), line[d,*], d/unit; // d==0 is boo-boo if(d==prevD){ // assume a leaf rows=rows.max(d); // zero based col+=1; span+=1; cell=List(d,col,1,text); // cell: (depth, col offset, span, text) tree.append(cell); } else if(d>prevD){ // down a level ow.push(line); r,s := self.fcn(ow,tree,cell,col-1,d,unit); rows = rows.max(r); spans.append(s); } else{ // d<prevD: done with this branch, back out to level above ow.push(line); break; } } span=( spans and (spans.sum(0) + span - 1) or span ).max(1); parent[2]=span; return(rows,span); };   ow,title,trees := outline.walker(11), ow.next(), List(); line,unit := ow.peek(), line.prefix(indent); // no leading space == bad rows,cols := 0,0; foreach line in (ow){ // the major (same color) columns tree:=List(0, cell:=List(1, 1,1, line.strip()) ); trees.append(tree); r,c := parse(ow,tree,cell,0,2,unit); tree[0]=c; // span for this "branch" rows,cols = rows.max(r), cols + c; } return(rows+1,cols,title,trees); }   fcn makeMarkup(rows,cols,title,trees){ var [const] colors=L("#ffebd2","#f0fff0","#e6ffff","#ffeeff"); out,cell := Data(Void), 0'~| style="background: %s " colspan=%d | %s~.fmt; out.writeln(0'~{| class="wikitable" style="text-align: center;"~,"\n|-\n", cell("#ffffe6;",cols,title)); foreach row in ([1..rows-1]){ clrs:=Walker.cycle(colors); out.writeln("|-"); foreach t in (trees){ // create this row span,clr := t[0], clrs.next(); col,cols := 1, t[1,*].filter('wrap([(d,_,text)]){ d==row }); foreach _,cpos,cspan,text in (cols){ if(col<cpos){ out.writeln(cell(clr,cpos-col,"")); col=cpos } out.writeln(cell(clr,cspan,text)); col+=cspan; } // col is span+1 after loop if all cells had text if(col<=span) out.writeln(cell(clr,span-col+1,"")); } } out.writeln("|}"); out.text }
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
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 REM First we draw the clock face 20 FOR n=1 TO 12 30 PRINT AT 10-10*COS (n/6*PI),16+10*SIN (n/6*PI);n 40 NEXT n 50 DEF FN t()=INT (65536*PEEK 23674+256*PEEK 23673+PEEK 23672)/50: REM number of seconds since start 100 REM Now we start the clock 110 LET t1=FN t() 120 LET a=t1/30*PI: REM a is the angle of the second hand in radians 130 LET sx=72*SIN a: LET sy=72*COS a 140 PLOT 131,91: DRAW OVER 1;sx,sy: REM draw hand 200 LET t=FN t() 210 IF INT t<=INT t1 THEN GO TO 200: REM wait for time for next hand; the INTs were not in the original but force it to wait for the next second 220 PLOT 131,91: DRAW OVER 1;sx,sy: REM rub out old hand 230 LET t1=t: GO TO 120
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.
#Racket
Racket
  #lang racket/base (require racket/place/distributed racket/place)   (define (fib n) (if (<= n 1) n (+ (fib (- n 1)) (fib (- n 2)))))   (provide work) (define (work) (place ch (place-channel-put ch (fib (place-channel-get ch)))))   (module+ main (define places (for/list ([host '("localhost" "localhost" "localhost" "localhost")] [port (in-naturals 12345)]) (define-values [node place] (spawn-node-supervise-place-at host #:listen-port port #:thunk #t (quote-module-path "..") 'work)) place)) (message-router (after-seconds 1 (for ([p places]) (*channel-put p 42)) (printf "Results: ~s\n" (map *channel-get places)) (exit))))  
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.
#Raku
Raku
./server.raku --usage Usage: server.p6 [--server=<Any>] [--port=<Any>]
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.
#NetRexx
NetRexx
  /* NetRexx */ options replace format comments java crossref symbols nobinary   ir = InetAddress addresses = InetAddress[] InetAddress.getAllByName('www.kame.net') loop ir over addresses if ir <= Inet4Address then do say 'IPv4 :' ir.getHostAddress end if ir <= Inet6Address then do say 'IPv6 :' ir.getHostAddress end end ir  
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.
#NewLISP
NewLISP
    (define (dnsLookup site , ipv) ;; captures current IPv mode (set 'ipv (net-ipv)) ;; IPv mode agnostic lookup (println "IPv4: " (begin (net-ipv 4) (net-lookup site))) (println "IPv6: " (begin (net-ipv 6) (net-lookup site))) ;; returns newLISP to previous IPv mode (net-ipv ipv) )   (dnsLookup "www.kame.net")  
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.
#PowerShell
PowerShell
# handy constants with script-wide scope [Single]$script:QUARTER_PI=0.7853982 [Single]$script:HALF_PI=1.570796   # leverage GDI (Forms and Drawing) Add-Type -AssemblyName System.Drawing Add-Type -AssemblyName System.Windows.Forms $script:TurtlePen = New-Object Drawing.Pen darkGreen $script:Form = New-Object Windows.Forms.Form $script:Canvas = $Form.CreateGraphics()   # implement a turtle graphics model Class Turtle { # relies on the script-scoped $TurtlePen and $Canvas # member properties for turtle's position and orientation [Single]$TurtleX [Single]$TurtleY [Single]$TurtleAngle   # constructors Turtle() { $this.TurtleX, $this.TurtleY = 44.0, 88.0 $this.TurtleAngle = 0.0 } Turtle([Single]$InitX, [Single]$InitY, [Single]$InitAngle) { $this.TurtleX, $this.TurtleY = $InitX, $InitY $this.TurtleAngle = $InitAngle }   # methods for turning and drawing [Void]Turn([Single]$Angle) { # $Angle measured in radians $this.TurtleAngle += $Angle # use positive $Angle for right turn, negative for left turn } [Void]Forward([Single]$Distance) { # draw line segment $TargetX = $this.TurtleX + $Distance * [Math]::Cos($this.TurtleAngle) $TargetY = $this.TurtleY + $Distance * [Math]::Sin($this.TurtleAngle) $script:Canvas.DrawLine($script:TurtlePen, $this.TurtleX, $this.TurtleY, $TargetX, $TargetY) # relocate turtle to other end of segment $this.TurtleX = $TargetX $this.TurtleY = $TargetY } } # end of Turtle class definition   # Implement dragon curve drawing methods in a subclass that inherits Turtle Class DragonTurtle : Turtle {   # DCL: recursive dragon curve, starting with left turns [Void]DCL([Byte]$Step, [Single]$Length) { $AdjustedStep = $Step - 1 $AdjustedLength = $Length / [Math]::Sqrt(2.0)   $this.Turn(-$script:QUARTER_PI) if ($AdjustedStep -gt 0) { $this.DCR($AdjustedStep, $AdjustedLength) } else { $this.Forward($AdjustedLength) } $this.Turn($script:HALF_PI) if ($AdjustedStep -gt 0) { $this.DCL($AdjustedStep, $AdjustedLength) } else { $this.Forward($AdjustedLength) } $this.Turn(-$script:QUARTER_PI) }   # DCR: recursive dragon curve, starting with right turns [Void]DCR([Byte]$Step, [Single]$Length) { $AdjustedStep = $Step - 1 $AdjustedLength = $Length / [Math]::Sqrt(2.0)   $this.Turn($script:QUARTER_PI) if ($AdjustedStep -gt 0) { $this.DCR($AdjustedStep, $AdjustedLength) } else { $this.Forward($AdjustedLength) } $this.Turn(-$script:HALF_PI) if ($AdjustedStep -gt 0) { $this.DCL($AdjustedStep, $AdjustedLength) } else { $this.Forward($AdjustedLength) } $this.Turn($script:QUARTER_PI) } } # end of DragonTurtle subclass definition   # prepare anonymous dragon-curve painting function for WinForms dialog $Form.add_paint({ [DragonTurtle]$Dragon = [DragonTurtle]::new() $Dragon.DCR(14,128) })   # display the GDI Form window, which triggers its prepared anonymous drawing function $Form.ShowDialog()  
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
#Lambdatalk
Lambdatalk
    {def linearcomb {def linearcomb.r {lambda {:a :n :i} {if {= :i :n} then else {let { {:e e({+ :i 1})} {:v {abs {A.get :i :a}}} {:s {if {< {A.get :i :a} 0} then - else +}} } {if {= :v 0} then else {if {= :v 1} then :s :e else :s :v*:e}}} {linearcomb.r :a :n {+ :i 1}} }}} {lambda {:a} {S.replace _LAMB_[^\s]+ by 0 in {let { {:r {linearcomb.r {A.new :a} {S.length :a} 0}} } {if {W.equal? {S.first :r} +} then {S.rest :r} else :r} }}}} -> linearcomb   {linearcomb 1 2 3} -> e(1) + 2*e(2) + 3*e(3) {linearcomb -1 -2 0 -3} -> - e(1) - 2*e(2) - 3*e(4) {linearcomb 0 1 2 3} -> e(2) + 2*e(3) + 3*e(4) {linearcomb 1 0 3 4} -> e(1) + 3*e(3) + 4*e(4) {linearcomb 1 2 0} -> e(1) + 2*e(2) {linearcomb 0 0 0} -> 0 {linearcomb 0} -> 0 {linearcomb 1 1 1} -> e(1) + e(2) + e(3) {linearcomb -1 -1 -1} -> - e(1) - e(2) - e(3) {linearcomb -1} -> - e(1)    
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Perl
Perl
procedure StoreVar(integer N, integer NTyp) -- -- Store a variable, applying any final operator as needed. -- If N is zero, PopFactor (ie store in a new temporary variable of -- the specified type). Otherwise N should be an index to symtab. -- If storeConst is 1, NTyp is ignored/overridden, otherwise it -- should usually be the declared or local type of N. -- ... end procedure
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Phix
Phix
procedure StoreVar(integer N, integer NTyp) -- -- Store a variable, applying any final operator as needed. -- If N is zero, PopFactor (ie store in a new temporary variable of -- the specified type). Otherwise N should be an index to symtab. -- If storeConst is 1, NTyp is ignored/overridden, otherwise it -- should usually be the declared or local type of N. -- ... end procedure
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#PHP
PHP
: (doc 'car) # View documentation of a function   : (doc '+Entity) # View documentation of a class   : (doc '+ 'firefox) # Explicitly specify a browser
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).
#Perl
Perl
sub diversity { my($truth, @pred) = @_; my($ae,$ce,$cp,$pd,$stats);   $cp += $_/@pred for @pred; # collective prediction $ae = avg_error($truth, @pred); # average individual error $ce = ($cp - $truth)**2; # collective error $pd = avg_error($cp, @pred); # prediction diversity   my $fmt = "%13s: %6.3f\n"; $stats = sprintf $fmt, 'average-error', $ae; $stats .= sprintf $fmt, 'crowd-error', $ce; $stats .= sprintf $fmt, 'diversity', $pd; }   sub avg_error { my($m, @v) = @_; my($avg_err); $avg_err += ($_ - $m)**2 for @v; $avg_err/@v; }   print diversity(49, qw<48 47 51>) . "\n"; print diversity(49, qw<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
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations def R=100, R2=R*R; \radius, in pixels; radius squared def X0=640/2, Y0=480/2; \coordinates of center of screen int X, Y, Z, C, D2; \coords, color, distance from center squared [SetVid($112); \set 640x480x24 graphics mode for Y:= -R to +R do \for all the coordinates near the circle for X:= -R to +R do \ which is under the sphere [D2:= X*X + Y*Y; C:= 0; \default color is black if D2 <= R2 then \coordinate is inside circle under sphere [Z:= sqrt(R2-D2); \height of point on surface of sphere above X,Y C:= Z-(X+Y)/2+130; \color is proportional; offset X and Y, and ]; \ shift color to upper limit of its range Point(X+X0, Y+Y0, C<<8+C); \green + blue = cyan ]; repeat until KeyHit; \wait for keystroke SetVid($03); \restore normal text mode ]
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot product of two vectors directly:   each vector must be the same length   multiply corresponding terms from each vector   sum the products   (to produce the answer) Related task   Vector products
#11l
11l
print(dot((1, 3, -5), (4, -2, -1)))
http://rosettacode.org/wiki/Doubly-linked_list/Definition
Doubly-linked list/Definition
Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#C.2B.2B
C++
#include <iostream> #include <list>   int main () { std::list<int> numbers {1, 5, 7, 0, 3, 2}; numbers.insert(numbers.begin(), 9); //Insert at the beginning numbers.insert(numbers.end(), 4); //Insert at the end auto it = std::next(numbers.begin(), numbers.size() / 2); //Iterator to the middle of the list numbers.insert(it, 6); //Insert in the middle for(const auto& i: numbers) std::cout << i << ' '; std::cout << '\n'; }
http://rosettacode.org/wiki/Disarium_numbers
Disarium numbers
A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number. E.G. 135 is a Disarium number: 11 + 32 + 53 == 1 + 9 + 125 == 135 There are a finite number of Disarium numbers. Task Find and display the first 18 Disarium numbers. Stretch Find and display all 20 Disarium numbers. See also Geeks for Geeks - Disarium numbers OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...) Related task: Narcissistic decimal number Related task: Own digits power sum Which seems to be the same task as Narcissistic decimal number...
#Arturo
Arturo
disarium?: function [x][ j: 0 psum: sum map digits x 'dig [ j: j + 1 dig ^ j ] return psum = x ]   cnt: 0 i: 0 while [cnt < 18][ if disarium? i [ print i cnt: cnt + 1 ] i: i + 1 ]
http://rosettacode.org/wiki/Disarium_numbers
Disarium numbers
A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number. E.G. 135 is a Disarium number: 11 + 32 + 53 == 1 + 9 + 125 == 135 There are a finite number of Disarium numbers. Task Find and display the first 18 Disarium numbers. Stretch Find and display all 20 Disarium numbers. See also Geeks for Geeks - Disarium numbers OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...) Related task: Narcissistic decimal number Related task: Own digits power sum Which seems to be the same task as Narcissistic decimal number...
#AWK
AWK
  # syntax: GAWK -f DISARIUM_NUMBERS.AWK BEGIN { stop = 19 printf("The first %d Disarium numbers:\n",stop) while (count < stop) { if (is_disarium(n)) { printf("%d ",n) count++ } n++ } printf("\n") exit(0) } function is_disarium(n, leng,sum,x) { x = n leng = length(n) while (x != 0) { sum += (x % 10) ^ leng leng-- x = int(x/10) } return((sum == n) ? 1 : 0) }  
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.
#Ruby
Ruby
require 'drb/drb'   # The URI for the server to connect to URI="druby://localhost:8787"   class TimeServer   def get_current_time return Time.now end   end   # The object that handles requests on the server FRONT_OBJECT = TimeServer.new   $SAFE = 1 # disable eval() and friends   DRb.start_service(URI, FRONT_OBJECT) # Wait for the drb server thread to finish before exiting. DRb.thread.join
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.
#Tcl
Tcl
proc main {} { global connections set connections [dict create] socket -server handleConnection 12345 vwait dummyVar ;# enter the event loop }   proc handleConnection {channel clientaddr clientport} { global connections dict set connections $channel address "$clientaddr:$clientport" fconfigure $channel -buffering line fileevent $channel readable [list handleMessage $channel] }   proc handleMessage {channel} { global connections if {[gets $channel line] == -1} { disconnect $channel } else { if {[string index [string trimleft $line] 0] eq "/"} { set words [lassign [split [string trim $line]] command] handleCommand $command $words $channel } else { echo $line $channel } } }   proc disconnect {channel} { global connections dict unset connections $channel fileevent $channel readable "" close $channel }   proc handleCommand {command words channel} { global connections switch -exact -- [string tolower $command] { /nick { dict set connections $channel nick [lindex $words 0] } /quit { echo bye $channel disconnect $channel } default { puts $channel "\"$command\" not implemented" } } }   proc echo {message senderchannel} { global connections foreach channel [dict keys $connections] { if {$channel ne $senderchannel} { set time [clock format [clock seconds] -format "%T"] set nick [dict get $connections $channel nick] puts $channel [format "\[%s\] %s: %s" $time $nick $message] } } }   main
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.
#Nim
Nim
import nativesockets   iterator items(ai: ptr AddrInfo): ptr AddrInfo = var current = ai while current != nil: yield current current = current.aiNext   proc main() = let addrInfos = getAddrInfo("www.kame.net", Port 80, AfUnspec) defer: freeAddrInfo addrInfos   for i in addrInfos: echo getAddrString i.aiAddr   when isMainModule: main()
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.
#Oberon-2
Oberon-2
  MODULE DNSQuery; IMPORT IO:Address, Out := NPCT:Console;   PROCEDURE Do() RAISES Address.UnknownHostException; VAR ip: Address.Inet; BEGIN ip := Address.GetByName("www.kame.net"); Out.String(ip.ToString());Out.Ln END Do;   BEGIN Do; END DNSQuery.  
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.
#Objeck
Objeck
use System.IO.Net;   class Rosetta { function : Main(args : String[]) ~ Nil { resoloved := TCPSocket->Resolve("www.kame.net"); each(i : resoloved) { resoloved[i]->PrintLine(); }; } }
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.
#Processing
Processing
float l = 3; int ints = 13;   void setup() { size(700, 600); background(0, 0, 255); translate(150, 100); stroke(255); turn_left(l, ints); turn_right(l, ints); }   void turn_right(float l, int ints) { if (ints == 0) { line(0, 0, 0, -l); translate(0, -l); } else { turn_left(l, ints-1); rotate(radians(90)); turn_right(l, ints-1); } }   void turn_left(float l, int ints) { if (ints == 0) { line(0, 0, 0, -l); translate(0, -l); } else { turn_left(l, ints-1); rotate(radians(-90)); turn_right(l, ints-1); } }
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
#Lua
Lua
function t2s(t) local s = "[" for i,v in pairs(t) do if i > 1 then s = s .. ", " .. v else s = s .. v end end return s .. "]" end   function linearCombo(c) local sb = "" for i,n in pairs(c) do local skip = false   if n < 0 then if sb:len() == 0 then sb = sb .. "-" else sb = sb .. " - " end elseif n > 0 then if sb:len() ~= 0 then sb = sb .. " + " end else skip = true end   if not skip then local av = math.abs(n) if av ~= 1 then sb = sb .. av .. "*" end sb = sb .. "e(" .. i .. ")" end end if sb:len() == 0 then sb = "0" end return sb end   function main() local 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 i,c in pairs(combos) do local arr = t2s(c) print(string.format("%15s -> %s", arr, linearCombo(c))) end end   main()
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#PicoLisp
PicoLisp
: (doc 'car) # View documentation of a function   : (doc '+Entity) # View documentation of a class   : (doc '+ 'firefox) # Explicitly specify a browser
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#PL.2FI
PL/I
  help about_comment_based_help  
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#PowerShell
PowerShell
  help about_comment_based_help  
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#PureBasic
PureBasic
; This is a small demo-code to demonstrate PureBasic’s internal ; documentation system.   ;- All Includes ; By starting the line with ‘;-‘ marks that specific line as a special comment, ; and this will be included in the overview, while normal comments will not.   IncludeFile "MyLibs.pbi" IncludeFile "Combustion_Data.pbi"   ;- ;- Start of functions and Macros ;- Engeneering stuff   ; A small function to calculate gas properties Procedure.f CalcR( p.f, V.f, T.f) ProcedureReturn p*V/T EndProcedure   ; Example of a Macro ; These are indicated by '+' in the overview Macro HalfPI() (#PI/2) EndMacro   ;- ;- - - - - - - - - - - ;- IO-Functions   Procedure Write_and_Close( File, Text$) If IsFile(File) WriteString(File,Text$) CloseFile(file) EndIf EndProcedure
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).
#Phix
Phix
with javascript_semantics function mean(sequence s) return sum(s)/length(s) end function function variance(sequence s, atom d) return mean(sq_power(sq_sub(s,d),2)) end function function diversity_theorem(atom reference, sequence observations) atom average_error = variance(observations,reference), average = mean(observations), crowd_error = power(reference-average,2), diversity = variance(observations,average) return {{"average_error",average_error}, {"crowd_error",crowd_error}, {"diversity",diversity}} end function procedure test(atom reference, sequence observations) sequence res = diversity_theorem(reference, observations) for i=1 to length(res) do printf(1," %14s : %g\n",res[i]) end for end procedure test(49, {48, 47, 51}) test(49, {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
#Yabasic
Yabasic
ancho = 640 : alto = 480 open window 640,480 backcolor 16,16,16 clear window sphera()   sub sphera() local n   for n = 1 to 100 color 2*n, 2*n, 2*n fill circle ancho/2-2*n/3, alto/2-n/2, 150-n next n end sub
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot product of two vectors directly:   each vector must be the same length   multiply corresponding terms from each vector   sum the products   (to produce the answer) Related task   Vector products
#360_Assembly
360 Assembly
* Dot product 03/05/2016 DOTPROD CSECT USING DOTPROD,R15 SR R7,R7 p=0 LA R6,1 i=1 LOOPI CH R6,=AL2((B-A)/4) do i=1 to hbound(a) BH ELOOPI LR R1,R6 i SLA R1,2 *4 L R3,A-4(R1) a(i) L R4,B-4(R1) b(i) MR R2,R4 a(i)*b(i) AR R7,R3 p=p+a(i)*b(i) LA R6,1(R6) i=i+1 B LOOPI ELOOPI XDECO R7,PG edit p XPRNT PG,80 print buffer XR R15,R15 rc=0 BR R14 return A DC F'1',F'3',F'-5' B DC F'4',F'-2',F'-1' PG DC CL80' ' buffer YREGS END DOTPROD
http://rosettacode.org/wiki/Doubly-linked_list/Definition
Doubly-linked list/Definition
Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Clojure
Clojure
(ns double-list)   (defprotocol PDoubleList (get-head [this]) (add-head [this x]) (get-tail [this]) (add-tail [this x]) (remove-node [this node]) (add-before [this node x]) (add-after [this node x]) (get-nth [this n]))   (defrecord Node [prev next data])   (defn make-node "Create an internal or finalized node" ([prev next data] (Node. prev next data)) ([m key] (when-let [node (get m key)] (assoc node :m m :key key))))   (defn get-next [node] (make-node (:m node) (:next node))) (defn get-prev [node] (make-node (:m node) (:prev node)))   (defn- seq* [m start next] (seq (for [x (iterate #(get m (next %)) (get m start))  :while x] (:data x))))   (defmacro when-> ([x pred form] `(let [x# ~x] (if ~pred (-> x# ~form) x#))) ([x pred form & more] `(when-> (when-> ~x ~pred ~form) ~@more)))   (declare get-nth-key)   (deftype DoubleList [m head tail] Object (equals [this x] (and (instance? DoubleList x) (= m (.m ^DoubleList x)))) (hashCode [this] (hash (or this ()))) clojure.lang.Sequential clojure.lang.Counted (count [_] (count m)) clojure.lang.Seqable (seq [_] (seq* m head :next)) clojure.lang.Reversible (rseq [_] (seq* m tail :prev)) clojure.lang.IPersistentCollection (empty [_] (DoubleList. (empty m) nil nil)) (equiv [this x] (and (sequential? x) (= (seq x) (seq this)))) (cons [this x] (.add-tail this x)) PDoubleList (get-head [_] (make-node m head)) (add-head [this x] (let [new-key (Object.) m (when-> (assoc m new-key (make-node nil head x)) head (assoc-in [head :prev] new-key)) tail (if tail tail new-key)] (DoubleList. m new-key tail))) (get-tail [_] (make-node m tail)) (add-tail [this x] (if-let [tail (.get-tail this)] (.add-after this tail x) (.add-head this x))) (remove-node [this node] (if (get m (:key node)) (let [{:keys [prev next key]} node head (if prev head next) tail (if next tail prev) m (when-> (dissoc m key) prev (assoc-in [prev :next] next) next (assoc-in [next :prev] prev))] (DoubleList. m head tail)) this)) (add-after [this node x] (if (get m (:key node)) (let [{:keys [prev next key]} node new-key (Object.) m (when-> (-> (assoc m new-key (make-node key next x)) (assoc-in , [key :next] new-key)) next (assoc-in [next :prev] new-key)) tail (if next tail new-key)] (DoubleList. m head tail)) this)) (add-before [this node x] (if (:prev node) (.add-after this (get-prev node) x) (.add-head this x))) (get-nth [this n] (make-node m (get-nth-key this n))))   (defn get-nth-key [^DoubleList this n] (if (< -1 n (.count this)) (let [[start next n] (if (< n (/ (.count this) 2)) [(.head this) :next n] [(.tail this) :prev (- (.count this) n 1)])] (nth (iterate #(get-in (.m this) [% next]) start) n)) (throw (IndexOutOfBoundsException.))))   (defn double-list ([] (DoubleList. nil nil nil)) ([coll] (into (double-list) coll)))   (defmethod print-method DoubleList [dl w] (print-method (interpose '<-> (seq dl)) w))   (defmethod print-method Node [n w] (print-method (symbol "#:double_list.Node") w) (print-method (into {} (dissoc n :m)) w))
http://rosettacode.org/wiki/Disarium_numbers
Disarium numbers
A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number. E.G. 135 is a Disarium number: 11 + 32 + 53 == 1 + 9 + 125 == 135 There are a finite number of Disarium numbers. Task Find and display the first 18 Disarium numbers. Stretch Find and display all 20 Disarium numbers. See also Geeks for Geeks - Disarium numbers OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...) Related task: Narcissistic decimal number Related task: Own digits power sum Which seems to be the same task as Narcissistic decimal number...
#BASIC
BASIC
function isDisarium(n) digitos = length(string(n)) suma = 0 x = n while x <> 0 suma += (x % 10) ^ digitos digitos -= 1 x = x \ 10 end while if suma = n then return True else return False end function   limite = 19 cont = 0 : n = 0 print "The first"; limite; " Disarium numbers are:" while cont < limite if isDisarium(n) then print n; " "; cont += 1 endif n += 1 end while end
http://rosettacode.org/wiki/Disarium_numbers
Disarium numbers
A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number. E.G. 135 is a Disarium number: 11 + 32 + 53 == 1 + 9 + 125 == 135 There are a finite number of Disarium numbers. Task Find and display the first 18 Disarium numbers. Stretch Find and display all 20 Disarium numbers. See also Geeks for Geeks - Disarium numbers OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...) Related task: Narcissistic decimal number Related task: Own digits power sum Which seems to be the same task as Narcissistic decimal number...
#C.2B.2B
C++
#include <vector> #include <iostream> #include <cmath> #include <algorithm>   std::vector<int> decompose( int n ) { std::vector<int> digits ; while ( n != 0 ) { digits.push_back( n % 10 ) ; n /= 10 ; } std::reverse( digits.begin( ) , digits.end( ) ) ; return digits ; }   bool isDisarium( int n ) { std::vector<int> digits( decompose( n ) ) ; int exposum = 0 ; for ( int i = 1 ; i < digits.size( ) + 1 ; i++ ) { exposum += static_cast<int>( std::pow( static_cast<double>(*(digits.begin( ) + i - 1 )) , static_cast<double>(i) )) ; } return exposum == n ; }   int main( ) { std::vector<int> disariums ; int current = 0 ; while ( disariums.size( ) != 18 ){ if ( isDisarium( current ) ) disariums.push_back( current ) ; current++ ; } for ( int d : disariums ) std::cout << d << " " ; std::cout << std::endl ; return 0 ; }
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.
#UnixPipes
UnixPipes
: >/tmp/buffer tail -f /tmp/buffer | nc -l 127.0.0.1 1234 | sh >/tmp/buffer 2>&1
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.
#Wren
Wren
/* distributed_programming_server.wren */   class Rpc { foreign static register()   foreign static handleHTTP() }   foreign class Listener { construct listen(network, address) {} }   class HTTP { foreign static serve(listener) }   Rpc.register() Rpc.handleHTTP() var listener = Listener.listen("tcp", ":1234") HTTP.serve(listener)
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.
#OCaml
OCaml
let dns_query ~host ~ai_family = let opts = [ Unix.AI_FAMILY ai_family; Unix.AI_SOCKTYPE Unix.SOCK_DGRAM; ] in let addr_infos = Unix.getaddrinfo host "" opts in match addr_infos with | [] -> failwith "dns_query" | ai :: _ -> match ai.Unix.ai_addr with | Unix.ADDR_INET (addr, _) -> (Unix.string_of_inet_addr addr) | Unix.ADDR_UNIX addr -> failwith "addr_unix"   let () = let host = "www.kame.net" in Printf.printf "primary addresses of %s are:\n" host;   Printf.printf " IPv4 address: %s\n" (dns_query host Unix.PF_INET); Printf.printf " IPv6 address: %s\n" (dns_query host Unix.PF_INET6); ;;
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.
#Perl
Perl
use feature 'say'; use Socket qw(getaddrinfo getnameinfo);   my ($err, @res) = getaddrinfo('orange.kame.net', 0, { protocol=>Socket::IPPROTO_TCP } ); die "getaddrinfo error: $err" if $err;   say ((getnameinfo($_->{addr}, Socket::NI_NUMERICHOST))[1]) for @res
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.
#Prolog
Prolog
dragonCurve(N) :- dcg_dg(N, [left], DCL, []), Side = 4, Angle is -N * (pi/4), dcg_computePath(Side, Angle, DCL, point(180,400), P, []), new(D, window('Dragon Curve')), send(D, size, size(800,600)), new(Path, path(poly)), send_list(Path, append, P), send(D, display, Path), send(D, open).     % compute the list of points of the Dragon Curve dcg_computePath(Side, Angle, [left | DCT], point(X1, Y1)) --> [point(X1, Y1)], { X2 is X1 + Side * cos(Angle), Y2 is Y1 + Side * sin(Angle), Angle1 is Angle + pi / 2 }, dcg_computePath(Side, Angle1, DCT, point(X2, Y2)).   dcg_computePath(Side, Angle, [right | DCT], point(X1, Y1)) --> [point(X1, Y1)], { X2 is X1 + Side * cos(Angle), Y2 is Y1 + Side * sin(Angle), Angle1 is Angle - pi / 2 }, dcg_computePath(Side, Angle1, DCT, point(X2, Y2)).     dcg_computePath(_Side, _Angle, [], point(X1, Y1)) --> [ point(X1, Y1)].     % compute the list of the "turns" of the Dragon Curve dcg_dg(1, L) --> L.   dcg_dg(N, L) --> {dcg_dg(L, L1, []), N1 is N - 1}, dcg_dg(N1, L1).   % one interation of the process dcg_dg(L) --> L, [left], inverse(L).   inverse([H | T]) --> inverse(T), inverse(H).   inverse([]) --> [].   inverse(left) --> [right].   inverse(right) --> [left].
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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
tests = {{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}}; Column[TraditionalForm[Total[MapIndexed[#1 e[#2[[1]]] &, #]]] & /@ tests]
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
#Modula-2
Modula-2
MODULE Linear; FROM FormatString IMPORT FormatString; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   PROCEDURE WriteInt(n : INTEGER); VAR buf : ARRAY[0..15] OF CHAR; BEGIN FormatString("%i", buf, n); WriteString(buf) END WriteInt;   PROCEDURE WriteLinear(c : ARRAY OF INTEGER); VAR buf : ARRAY[0..15] OF CHAR; i,j : CARDINAL; b : BOOLEAN; BEGIN b := TRUE; j := 0;   FOR i:=0 TO HIGH(c) DO IF c[i]=0 THEN CONTINUE END;   IF c[i]<0 THEN IF b THEN WriteString("-") ELSE WriteString(" - ") END; ELSIF c[i]>0 THEN IF NOT b THEN WriteString(" + ") END; END;   IF c[i] > 1 THEN WriteInt(c[i]); WriteString("*") ELSIF c[i] < -1 THEN WriteInt(-c[i]); WriteString("*") END;   FormatString("e(%i)", buf, i+1); WriteString(buf);   b := FALSE; INC(j) END;   IF j=0 THEN WriteString("0") END; WriteLn END WriteLinear;   TYPE Array1 = ARRAY[0..0] OF INTEGER; Array3 = ARRAY[0..2] OF INTEGER; Array4 = ARRAY[0..3] OF INTEGER; BEGIN WriteLinear(Array3{1,2,3}); WriteLinear(Array4{0,1,2,3}); WriteLinear(Array4{1,0,3,4}); WriteLinear(Array3{1,2,0}); WriteLinear(Array3{0,0,0}); WriteLinear(Array1{0}); WriteLinear(Array3{1,1,1}); WriteLinear(Array3{-1,-1,-1}); WriteLinear(Array4{-1,-2,0,-3}); WriteLinear(Array1{-1});   ReadChar END Linear.
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Python
Python
class Doc(object): """ This is a class docstring. Traditionally triple-quoted strings are used because they can span multiple lines and you can include quotation marks without escaping. """ def method(self, num): """This is a method docstring.""" pass
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#R
R
example(package.skeleton)
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Racket
Racket
  #lang scribble/manual (require (for-label "sandwiches.rkt"))   @defproc[(make-sandwich [ingredients (listof ingredient?)]) sandwich?]{ Returns a sandwich given the right ingredients. }  
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).
#PureBasic
PureBasic
Define.f ref=49.0, mea NewList argV.f()   Macro put Print(~"\n["+StrF(ref)+"]"+#TAB$) ForEach argV() : Print(StrF(argV())+#TAB$) : Next PrintN(~"\nAverage Error : "+StrF(vari(argV(),ref),5)) PrintN("Crowd Error  : "+StrF((ref-mea)*(ref-mea),5)) PrintN("Diversity  : "+StrF(vari(argV(),mea),5)) EndMacro   Macro LetArgV(v) AddElement(argV()) : argV()=v EndMacro   Procedure.f mean(List x.f()) Define.f m ForEach x() : m+x() : Next ProcedureReturn m/ListSize(x()) EndProcedure   Procedure.f vari(List x.f(),r.f) NewList nx.f() ForEach x() : AddElement(nx()) : nx()=(r-x())*(r-x()) : Next ProcedureReturn mean(nx()) EndProcedure   If OpenConsole()=0 : End 1 : EndIf Gosub SetA : ClearList(argV()) Gosub SetB : Input() End   SetA: LetArgV(48.0) : LetArgV(47.0) : LetArgV(51.0) mea=mean(argV()) : put Return   SetB: LetArgV(48.0) : LetArgV(47.0) : LetArgV(51.0) : LetArgV(42.0) mea=mean(argV()) : put Return
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
#zkl
zkl
img:=PPM(640,480); R:=100; R2:=R*R; //radius, in pixels; radius squared X0:=640/2; Y0:=480/2; //coordinates of center of screen foreach Y in ([-R..R]){ //for all the coordinates near the circle foreach X in ([-R..R]){ // which is under the sphere D2:=X*X + Y*Y; C:=0; //default color is black if(D2<=R2){ //coordinate is inside circle under sphere Z:=(R2-D2).toFloat().sqrt();//height of point on surface of sphere above X,Y C=0x82+Z-(X+Y)/2; //color is proportional; offset X and Y, and } // shift color to upper limit of its range img[X+X0,Y+Y0]=C.shiftLeft(8)+C; //green + blue = cyan } } img.write(File("foo.ppm","wb"));
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot product of two vectors directly:   each vector must be the same length   multiply corresponding terms from each vector   sum the products   (to produce the answer) Related task   Vector products
#8th
8th
[1,3,-5] [4,-2,-1] ' n:* ' n:+ a:dot . cr
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot product of two vectors directly:   each vector must be the same length   multiply corresponding terms from each vector   sum the products   (to produce the answer) Related task   Vector products
#ABAP
ABAP
report zdot_product data: lv_n type i, lv_sum type i, lt_a type standard table of i, lt_b type standard table of i.   append: '1' to lt_a, '3' to lt_a, '-5' to lt_a. append: '4' to lt_b, '-2' to lt_b, '-1' to lt_b. describe table lt_a lines lv_n.   perform dot_product using lt_a lt_b lv_n changing lv_sum.   write lv_sum left-justified.   form dot_product using it_a like lt_a it_b like lt_b iv_n type i changing ev_sum type i. field-symbols: <wa_a> type i, <wa_b> type i.   do iv_n times. read table: it_a assigning <wa_a> index sy-index, it_b assigning <wa_b> index sy-index. lv_sum = lv_sum + ( <wa_a> * <wa_b> ). enddo. endform.
http://rosettacode.org/wiki/Doubly-linked_list/Definition
Doubly-linked list/Definition
Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Common_Lisp
Common Lisp
(defstruct dlist head tail) (defstruct dlink content prev next)   (defun insert-between (dlist before after data) "Insert a fresh link containing DATA after existing link BEFORE if not nil and before existing link AFTER if not nil" (let ((new-link (make-dlink :content data :prev before :next after))) (if (null before) (setf (dlist-head dlist) new-link) (setf (dlink-next before) new-link)) (if (null after) (setf (dlist-tail dlist) new-link) (setf (dlink-prev after) new-link)) new-link))   (defun insert-before (dlist dlink data) "Insert a fresh link containing DATA before existing link DLINK" (insert-between dlist (dlink-prev dlink) dlink data))   (defun insert-after (dlist dlink data) "Insert a fresh link containing DATA after existing link DLINK" (insert-between dlist dlink (dlink-next dlink) data))   (defun insert-head (dlist data) "Insert a fresh link containing DATA at the head of DLIST" (insert-between dlist nil (dlist-head dlist) data))   (defun insert-tail (dlist data) "Insert a fresh link containing DATA at the tail of DLIST" (insert-between dlist (dlist-tail dlist) nil data))   (defun remove-link (dlist dlink) "Remove link DLINK from DLIST and return its content" (let ((before (dlink-prev dlink)) (after (dlink-next dlink))) (if (null before) (setf (dlist-head dlist) after) (setf (dlink-next before) after)) (if (null after) (setf (dlist-tail dlist) before) (setf (dlink-prev after) before))))   (defun dlist-elements (dlist) "Returns the elements of DLIST as a list" (labels ((extract-values (dlink acc) (if (null dlink) acc (extract-values (dlink-next dlink) (cons (dlink-content dlink) acc))))) (reverse (extract-values (dlist-head dlist) nil))))
http://rosettacode.org/wiki/Disarium_numbers
Disarium numbers
A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number. E.G. 135 is a Disarium number: 11 + 32 + 53 == 1 + 9 + 125 == 135 There are a finite number of Disarium numbers. Task Find and display the first 18 Disarium numbers. Stretch Find and display all 20 Disarium numbers. See also Geeks for Geeks - Disarium numbers OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...) Related task: Narcissistic decimal number Related task: Own digits power sum Which seems to be the same task as Narcissistic decimal number...
#Factor
Factor
USING: io kernel lists lists.lazy math.ranges math.text.utils math.vectors prettyprint sequences ;   : disarium? ( n -- ? ) dup 1 digit-groups dup length 1 [a,b] v^ sum = ;   : disarium ( -- list ) 0 lfrom [ disarium? ] lfilter ;   19 disarium ltake [ pprint bl ] leach nl
http://rosettacode.org/wiki/Disarium_numbers
Disarium numbers
A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number. E.G. 135 is a Disarium number: 11 + 32 + 53 == 1 + 9 + 125 == 135 There are a finite number of Disarium numbers. Task Find and display the first 18 Disarium numbers. Stretch Find and display all 20 Disarium numbers. See also Geeks for Geeks - Disarium numbers OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...) Related task: Narcissistic decimal number Related task: Own digits power sum Which seems to be the same task as Narcissistic decimal number...
#Go
Go
package main   import ( "fmt" "strconv" )   const DMAX = 20 // maximum digits const LIMIT = 20 // maximum number of disariums to find   func main() { // Pre-calculated exponential and power serials EXP := make([][]uint64, 1+DMAX) POW := make([][]uint64, 1+DMAX)   EXP[0] = make([]uint64, 11) EXP[1] = make([]uint64, 11) POW[0] = make([]uint64, 11) POW[1] = make([]uint64, 11) for i := uint64(1); i <= 10; i++ { EXP[1][i] = i } for i := uint64(1); i <= 9; i++ { POW[1][i] = i } POW[1][10] = 9   for i := 2; i <= DMAX; i++ { EXP[i] = make([]uint64, 11) POW[i] = make([]uint64, 11) } for i := 1; i < DMAX; i++ { for j := 0; j <= 9; j++ { EXP[i+1][j] = EXP[i][j] * 10 POW[i+1][j] = POW[i][j] * uint64(j) } EXP[i+1][10] = EXP[i][10] * 10 POW[i+1][10] = POW[i][10] + POW[i+1][9] }   // Digits of candidate and values of known low bits DIGITS := make([]int, 1+DMAX) // Digits form Exp := make([]uint64, 1+DMAX) // Number form Pow := make([]uint64, 1+DMAX) // Powers form   var exp, pow, min, max uint64 start := 1 final := DMAX count := 0 for digit := start; digit <= final; digit++ { fmt.Println("# of digits:", digit) level := 1 DIGITS[0] = 0 for { // Check limits derived from already known low bit values // to find the most possible candidates for 0 < level && level < digit { // Reset path to try next if checking in level is done if DIGITS[level] > 9 { DIGITS[level] = 0 level-- DIGITS[level]++ continue }   // Update known low bit values Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]] Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]   // Max possible value pow = Pow[level] + POW[digit-level][10]   if pow < EXP[digit][1] { // Try next since upper limit is invalidly low DIGITS[level]++ continue }   max = pow % EXP[level][10] pow -= max if max < Exp[level] { pow -= EXP[level][10] } max = pow + Exp[level]   if max < EXP[digit][1] { // Try next since upper limit is invalidly low DIGITS[level]++ continue }   // Min possible value exp = Exp[level] + EXP[digit][1] pow = Pow[level] + 1   if exp > max || max < pow { // Try next since upper limit is invalidly low DIGITS[level]++ continue }   if pow > exp { min = pow % EXP[level][10] pow -= min if min > Exp[level] { pow += EXP[level][10] } min = pow + Exp[level] } else { min = exp }   // Check limits existence if max < min { DIGITS[level]++ // Try next number since current limits invalid } else { level++ // Go for further level checking since limits available } }   // All checking is done, escape from the main check loop if level < 1 { break }   // Finally check last bit of the most possible candidates // Update known low bit values Exp[level] = Exp[level-1] + EXP[level][DIGITS[level]] Pow[level] = Pow[level-1] + POW[digit+1-level][DIGITS[level]]   // Loop to check all last bits of candidates for DIGITS[level] < 10 { // Print out new Disarium number if Exp[level] == Pow[level] { s := "" for i := DMAX; i > 0; i-- { s += fmt.Sprintf("%d", DIGITS[i]) } n, _ := strconv.ParseUint(s, 10, 64) fmt.Println(n) count++ if count == LIMIT { fmt.Println("\nFound the first", LIMIT, "Disarium numbers.") return } }   // Go to followed last bit candidate DIGITS[level]++ Exp[level] += EXP[level][1] Pow[level]++ }   // Reset to try next path DIGITS[level] = 0 level-- DIGITS[level]++ } fmt.Println() } }
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.
#Phix
Phix
without js include builtins\cffi.e constant AF_UNSPEC = 0, -- AF_INET = 2, -- AF_INET6 = 23, -- SOCK_STREAM = 1, SOCK_DGRAM = 2, -- IPPROTO_TCP = 6, NI_MAXHOST = 1025, NI_NUMERICHOST = iff(platform()=LINUX?1:2) constant tWAD = """ typedef struct WSAData { WORD wVersion; WORD wHighVersion; char szDescription[257]; char szSystemStatus[129]; unsigned short iMaxSockets; unsigned short iMaxUdpDg; char *lpVendorInfo; } WSADATA, *LPWSADATA; """, tWAS = """ int WSAStartup( _In_ WORD wVersionRequested, _Out_ LPWSADATA lpWSAData ); """, tWAC = """ int WSACleanup(void); """, tAI_W=""" typedef struct addrinfo { int ai_flags; int ai_family; int ai_socktype; int ai_protocol; size_t ai_addrlen; char *ai_canonname; struct sockaddr *ai_addr; struct addrinfo *ai_next; } ADDRINFOA, *PADDRINFOA; """, tAI_L=""" typedef struct addrinfo { int ai_flags; int ai_family; int ai_socktype; int ai_protocol; int ai_addrlen; struct sockaddr *ai_addr; char *ai_canonname; struct addrinfo *ai_next; }; """, tGAI = """ int getaddrinfo( _In_opt_ PCSTR pNodeName, _In_opt_ PCSTR pServiceName, _In_opt_ const ADDRINFOA *pHints, _Out_ PADDRINFOA *ppResult ); """, --int getaddrinfo(const char *node, const char *service, -- const struct addrinfo *hints, -- struct addrinfo **res); tGNI = """ int getnameinfo( _In_ sockaddr *sa, _In_ int salen, _Out_ char *host, _In_ DWORD hostlen, _Out_ char *serv, _In_ DWORD servlen, _In_ int flags ); """, --int getnameinfo(const struct sockaddr *addr, socklen_t addrlen, -- char *host, socklen_t hostlen, -- char *serv, socklen_t servlen, int flags); tFAI = """ void freeaddrinfo( _In_ struct addrinfo *ai ); """ --void freeaddrinfo(struct addrinfo *res); integer xgetaddrinfo = NULL, xgetnameinfo, xfreeaddrinfo, idAI, xwsastartup, xwsacleanup, error function get_name_info(string fqdn) if xgetaddrinfo=NULL then atom lib if platform()=WINDOWS then integer idWAD = define_struct(tWAD) atom pWAD = allocate_struct(idWAD,cleanup:=true) lib = open_dll("Ws2_32.dll") xwsastartup = define_cffi_func(lib,tWAS) xwsacleanup = define_cffi_func(lib,tWAC) error = c_func(xwsastartup,{#00020002,pWAD}) if error then ?9/0 end if idAI = define_struct(tAI_W) elsif platform()=LINUX then lib = open_dll("libc.so.6") idAI = define_struct(tAI_L) end if xgetaddrinfo = define_cffi_func(lib,tGAI) xgetnameinfo = define_cffi_func(lib,tGNI) xfreeaddrinfo = define_cffi_proc(lib,tFAI) end if atom hints = allocate_struct(idAI,cleanup:=true), res = allocate(machine_word(),cleanup:=true), host = allocate(NI_MAXHOST,cleanup:=true) set_struct_field(idAI,hints,"ai_family",AF_UNSPEC) -- set_struct_field(idAI,hints,"ai_socktype",SOCK_STREAM) set_struct_field(idAI,hints,"ai_socktype",SOCK_DGRAM) error = c_func(xgetaddrinfo,{fqdn,NULL,hints,res}) if error then ?9/0 end if res = peekNS(res,machine_word(),false) atom ptr = res sequence results = {} while ptr!=NULL do atom addr = get_struct_field(idAI,ptr,"ai_addr") integer len = get_struct_field(idAI,ptr,"ai_addrlen") error = c_func(xgetnameinfo,{addr, len, host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST}) if error then ?9/0 end if results = append(results,peek_string(host)) ptr = get_struct_field(idAI,ptr,"ai_next") end while c_proc(xfreeaddrinfo,{res}) return results end function procedure WSACleanup() if platform()=WINDOWS then error = c_func(xwsacleanup,{}) if error then crash("WSACleanup failed: %d\n",{error}) end if end if end procedure ?get_name_info("www.kame.net") WSACleanup()
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.
#PureBasic
PureBasic
#SqRt2 = 1.4142136 #SizeH = 800: #SizeV = 550 Global angle.d, px, py, imageNum   Procedure turn(degrees.d) angle + degrees * #PI / 180 EndProcedure   Procedure forward(length.d) Protected w = Cos(angle) * length Protected h = Sin(angle) * length LineXY(px, py, px + w, py + h, RGB(255,255,255)) px + w: py + h EndProcedure   Procedure dragon(length.d, split, d.d) If split = 0 forward(length) Else turn(d * 45) dragon(length / #SqRt2, split - 1, 1) turn(-d * 90) dragon(length / #SqRt2, split - 1, -1) turn(d * 45) EndIf EndProcedure   OpenWindow(0, 0, 0, #SizeH, #SizeV, "DragonCurve", #PB_Window_SystemMenu) imageNum = CreateImage(#PB_Any, #SizeH, #SizeV, 32) ImageGadget(0, 0, 0, 0, 0, ImageID(imageNum))   angle = 0: px = 185: py = 190 If StartDrawing(ImageOutput(imageNum)) dragon(400, 15, 1) StopDrawing() SetGadgetState(0, ImageID(imageNum)) EndIf   Repeat: Until WaitWindowEvent(10) = #PB_Event_CloseWindow
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
#Nim
Nim
import strformat   proc linearCombo(c: openArray[int]): string =   for i, n in c: if n == 0: continue let op = if n < 0: if result.len == 0: "-" else: " - " else: if n > 0 and result.len == 0: "" else: " + " let av = abs(n) let coeff = if av == 1: "" else: $av & '*' result &= fmt"{op}{coeff}e({i + 1})" if result.len == 0: result = "0"   const 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 c in Combos: echo fmt"{($c)[1..^1]:15} → {linearCombo(c)}"
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
#Perl
Perl
use strict; use warnings; use feature 'say';   sub linear_combination { my(@coef) = @$_; my $e = ''; for my $c (1..+@coef) { $e .= "$coef[$c-1]*e($c) + " if $coef[$c-1] } $e =~ s/ \+ $//; $e =~ s/1\*//g; $e =~ s/\+ -/- /g; $e or 0; }   say linear_combination($_) for [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 ]
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Raku
Raku
  #= it's yellow sub marine { ... } say &marine.WHY; # "it's yellow"   #= a shaggy little thing class Sheep { #= not too scary method roar { 'roar!' } } say Sheep.WHY; # "a shaggy little thing" say Sheep.^find_method('roar').WHY; # "not too scary"
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#REBOL
REBOL
rebol [ Title: "Documentation" URL: http://rosettacode.org/wiki/Documentation Purpose: {To demonstrate documentation of REBOL pograms.} ]   ; Notice the fields in the program header. The header is required for ; valid REBOL programs, although the fields don't have to be filled ; in. Standard fields are defined (see 'system/script/header'), but ; I can also define other fields as I like and they'll be available ; there.   ; This is a comment. The semicolon can be inserted anywhere outside of ; a string and will escape to end of line. See the inline comments ; below.   ; Functions can have a documentation string as the first part of the ; argument definition block. Each argument can specify what types it ; will accept as well as a description. All typing/documentation ; entries are optional. Notice that local variables can be documented ; as well.   sum: func [ "Add numbers in block." data [block! list!] "List of numbers to add together." /average "Calculate average instead of sum." /local i "Iteration variable." x "Variable to hold results." ] [ x: 0 repeat i data [x: x + i] either average [x / length? data][x] ; Functions return last result. ]   print [sum [1 2 3 4 5 6] crlf sum/average [7 8 9 10] crlf]   ; The help message is constructed from the public information about ; the function. Internal variable information isn't shown.   help sum print ""   ; The source command provides the source to any user functions, ; reconstructing the documentation strings if they're provided:   source sum print ""   ; This is an object, describing a person, whose name is Bob.   bob: make object! [ name: "Bob Sorkopath" age: 24 hi: func ["Say hello."][print "Hello!"] ]   ; I can use the 'help' word to get a list of the fields of the object   help bob print ""   ; If I want see the documentation or source for 'bob/hi', I have to ; get a little tricky to get it from the object's namespace:   x: get in bob 'hi help x print ""   probe get in bob 'hi
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).
#Python
Python
'''Diversity prediction theorem'''   from itertools import chain from functools import reduce     # diversityValues :: Num a => a -> [a] -> # { mean-Error :: a, crowd-error :: a, diversity :: a } def diversityValues(x): '''The mean error, crowd error and diversity, for a given observation x and a non-empty list of predictions ps. ''' def go(ps): mp = mean(ps) return { 'mean-error': meanErrorSquared(x)(ps), 'crowd-error': pow(x - mp, 2), 'diversity': meanErrorSquared(mp)(ps) } return go     # meanErrorSquared :: Num -> [Num] -> Num def meanErrorSquared(x): '''The mean of the squared differences between the observed value x and a non-empty list of predictions ps. ''' def go(ps): return mean([ pow(p - x, 2) for p in ps ]) return go     # ------------------------- TEST ------------------------- # main :: IO () def main(): '''Observed value: 49, prediction lists: various. '''   print(unlines(map( showDiversityValues(49), [ [48, 47, 51], [48, 47, 51, 42], [50, '?', 50, {}, 50], # Non-numeric values. [] # Missing predictions. ] ))) print(unlines(map( showDiversityValues('49'), # String in place of number. [ [50, 50, 50], [40, 35, 40], ] )))     # ---------------------- FORMATTING ----------------------   # showDiversityValues :: Num -> [Num] -> Either String String def showDiversityValues(x): '''Formatted string representation of diversity values for a given observation x and a non-empty list of predictions p. ''' def go(ps): def showDict(dct): w = 4 + max(map(len, dct.keys()))   def showKV(a, kv): k, v = kv return a + k.rjust(w, ' ') + ( ' : ' + showPrecision(3)(v) + '\n' ) return 'Predictions: ' + showList(ps) + ' ->\n' + ( reduce(showKV, dct.items(), '') )   def showProblem(e): return ( unlines(map(indented(1), e)) if ( isinstance(e, list) ) else indented(1)(repr(e)) ) + '\n'   return 'Observation: ' + repr(x) + '\n' + ( either(showProblem)(showDict)( bindLR(numLR(x))( lambda n: bindLR(numsLR(ps))( compose(Right, diversityValues(n)) ) ) ) ) return go     # ------------------ GENERIC FUNCTIONS -------------------   # Left :: a -> Either a b def Left(x): '''Constructor for an empty Either (option type) value with an associated string. ''' return {'type': 'Either', 'Right': None, 'Left': x}     # Right :: b -> Either a b def Right(x): '''Constructor for a populated Either (option type) value''' return {'type': 'Either', 'Left': None, 'Right': x}     # bindLR (>>=) :: Either a -> (a -> Either b) -> Either b def bindLR(m): '''Either monad injection operator. Two computations sequentially composed, with any value produced by the first passed as an argument to the second. ''' def go(mf): return ( mf(m.get('Right')) if None is m.get('Left') else m ) return go     # compose :: ((a -> a), ...) -> (a -> a) def compose(*fs): '''Composition, from right to left, of a series of functions. ''' def go(f, g): def fg(x): return f(g(x)) return fg return reduce(go, fs, identity)     # concatMap :: (a -> [b]) -> [a] -> [b] def concatMap(f): '''A concatenated list over which a function has been mapped. The list monad can be derived by using a function f which wraps its output in a list, (using an empty list to represent computational failure). ''' def go(xs): return chain.from_iterable(map(f, xs)) return go     # either :: (a -> c) -> (b -> c) -> Either a b -> c def either(fl): '''The application of fl to e if e is a Left value, or the application of fr to e if e is a Right value. ''' return lambda fr: lambda e: fl(e['Left']) if ( None is e['Right'] ) else fr(e['Right'])     # identity :: a -> a def identity(x): '''The identity function.''' return x     # indented :: Int -> String -> String def indented(n): '''String indented by n multiples of four spaces. ''' return lambda s: (4 * ' ' * n) + s   # mean :: [Num] -> Float def mean(xs): '''Arithmetic mean of a list of numeric values. ''' return sum(xs) / float(len(xs))     # numLR :: a -> Either String Num def numLR(x): '''Either Right x if x is a float or int, or a Left explanatory message.''' return Right(x) if ( isinstance(x, (float, int)) ) else Left( 'Expected number, saw: ' + ( str(type(x)) + ' ' + repr(x) ) )     # numsLR :: [a] -> Either String [Num] def numsLR(xs): '''Either Right xs if all xs are float or int, or a Left explanatory message.''' def go(ns): ls, rs = partitionEithers(map(numLR, ns)) return Left(ls) if ls else Right(rs) return bindLR( Right(xs) if ( bool(xs) and isinstance(xs, list) ) else Left( 'Expected a non-empty list, saw: ' + ( str(type(xs)) + ' ' + repr(xs) ) ) )(go)     # partitionEithers :: [Either a b] -> ([a],[b]) def partitionEithers(lrs): '''A list of Either values partitioned into a tuple of two lists, with all Left elements extracted into the first list, and Right elements extracted into the second list. ''' def go(a, x): ls, rs = a r = x.get('Right') return (ls + [x.get('Left')], rs) if None is r else ( ls, rs + [r] ) return reduce(go, lrs, ([], []))     # showList :: [a] -> String def showList(xs): '''Compact string representation of a list''' return '[' + ','.join(str(x) for x in xs) + ']'     # showPrecision :: Int -> Float -> String def showPrecision(n): '''A string showing a floating point number at a given degree of precision.''' def go(x): return str(round(x, n)) return go     # unlines :: [String] -> String def unlines(xs): '''A single string derived by the intercalation of a list of strings with the newline character.''' return '\n'.join(xs)     # MAIN --- if __name__ == '__main__': main()
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
#ZX_Spectrum_Basic
ZX Spectrum Basic
1 REM fast 50 REM spheer with hidden lines and rotation 100 CLS 110 PRINT "sphere with lenght&wide-circles" 120 PRINT "_______________________________"'' 200 INPUT "rotate x-as:";a 210 INPUT "rotate y-as:";b 220 INPUT "rotate z-as:";c 225 INPUT "distance lines(10-45):";d 230 LET u=128: LET v=87: LET r=87: LET bm=PI/180: LET h=.5 240 LET s1=SIN (a*bm): LET s2=SIN (b*bm): LET s3=SIN (c*bm) 250 LET c1=COS (a*bm): LET c2=COS (b*bm): LET c3=COS (c*bm) 260 REM calc rotate matrix 270 LET ax=c2*c3: LET ay=-c2*s3: LET az=s2 280 LET bx=c1*s3+s1*s2*c3 290 LET by=c1*c3-s1*s2*s3: LET bz=-s1*c2 300 LET cx=s1*s3-c1*s2*c3 310 LET cy=s1*c3+c1*s2*s3: LET cz=c1*c2 400 REM draw outer 410 CLS : CIRCLE u,v,r 500 REM draw lenght-circle 510 FOR l=0 TO 180-d STEP d 515 LET f1=0 520 FOR p=0 TO 360 STEP 5 530 GO SUB 1000: REM xx,yy,zz calc 540 IF yy>0 THEN LET f2=0: LET f1=0: GO TO 580 550 LET xb=INT (u+xx+h): LET yb=INT (v+zz+h): LET f2=1 560 IF f1=0 THEN LET x1=xb: LET y1=yb: LET f1=1: GO TO 580 570 PLOT x1,y1: DRAW xb-x1,yb-y1: LET x1=xb: LET y1=yb: LET f1=f2 580 NEXT p 590 NEXT l 600 REM draw wide-circle 610 FOR p=-90+d TO 90-d STEP d 615 LET f1=0 620 FOR l=0 TO 360 STEP 5 630 GO SUB 1000: REM xx,yy,zz 640 IF yy>0 THEN LET f2=0: LET f1=0: GO TO 680 650 LET xb=INT (u+xx+h): LET yb=INT (v+zz+h): LET f2=1 660 IF f1=0 THEN LET x1=xb: LET y1=yb: LET f1=1: GO TO 680 670 PLOT x1,y1: DRAW xb-x1,yb-y1: LET x1=xb: LET y1=yb: LET f1=f2 680 NEXT l 690 NEXT p 700 PRINT #0;"...press any key...": PAUSE 0: RUN 999 REM sfere-coordinates>>>Cartesis Coordinate 1000 LET x=r*COS (p*bm)*COS (l*bm) 1010 LET y=r*COS (p*bm)*SIN (l*bm) 1020 LET z=r*SIN (p*bm) 1030 REM p(x,y,z) rotate to p(xx,yy,zz) 1040 LET xx=ax*x+ay*y+az*z 1050 LET yy=bx*x+by*y+bz*z 1060 LET zz=cx*x+cy*y+cz*z 1070 RETURN
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot product of two vectors directly:   each vector must be the same length   multiply corresponding terms from each vector   sum the products   (to produce the answer) Related task   Vector products
#ACL2
ACL2
(defun dotp (v u) (if (or (endp v) (endp u)) 0 (+ (* (first v) (first u)) (dotp (rest v) (rest u)))))
http://rosettacode.org/wiki/Doubly-linked_list/Definition
Doubly-linked list/Definition
Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#D
D
import std.stdio;   class LinkedList(T) { Node!(T) head, tail;   /** Iterate in the forward direction. */ int opApply (int delegate(uint, Node!(T)) dg) { uint i = 0; auto link = head; int result = 0; while (link) { result = dg (i, link); if (result) return result; i++; link = link.next; } return result; }   static LinkedList!(T) fromArray (T[] array) { Node!(T) link = null; auto head = link; auto self = new LinkedList!(T); foreach (elem; array) { link = new Node!(T)(null, link, elem, self); if (!head) head = link; } return self; } }   class Node(T) { Node!(T) next; Node!(T) previous; LinkedList!(T) parent; T value;   this (Node!(T) next, Node!(T) previous, T value, LinkedList!(T) parent) in { assert (parent !is null); } body { this.next = next; if (next) next.previous = this; if (previous) previous.next = this; this.previous = previous; this.value = value; this.parent = parent;   if (parent.head == next) parent.head = this; if (parent.tail == previous) parent.tail = this; }   /** Insert an element after this one. */ void insertAfter (T value) { new Node!(T)(next, this, value, parent); }   /** Insert an element before this one. */ void insertBefore (T value) { new Node!(T)(this, previous, value, parent); }   /** Remove the current node from the list. */ void remove () { if (next) next.previous = previous; if (previous) previous.next = next; if (parent.tail == this) parent.tail = previous; if (parent.head == this) parent.head = next; } }   void main () { string[] sample = ["was", "it", "a", "cat", "I", "saw"]; auto list = LinkedList!string.fromArray (sample); for (auto elem = list.head; elem; elem = elem.next) { writef ("%s ", elem.value); if (elem.value == "it") elem.insertAfter("really"); } writeln; for (auto elem = list.tail; elem; elem = elem.previous) { writef ("%s ", elem.value); } writeln; }
http://rosettacode.org/wiki/Disarium_numbers
Disarium numbers
A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number. E.G. 135 is a Disarium number: 11 + 32 + 53 == 1 + 9 + 125 == 135 There are a finite number of Disarium numbers. Task Find and display the first 18 Disarium numbers. Stretch Find and display all 20 Disarium numbers. See also Geeks for Geeks - Disarium numbers OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...) Related task: Narcissistic decimal number Related task: Own digits power sum Which seems to be the same task as Narcissistic decimal number...
#Haskell
Haskell
module Disarium where import Data.Char ( digitToInt)   isDisarium :: Int -> Bool isDisarium n = (sum $ map (\(c , i ) -> (digitToInt c ) ^ i ) $ zip ( show n ) [1 , 2 ..]) == n   solution :: [Int] solution = take 18 $ filter isDisarium [0, 1 ..]  
http://rosettacode.org/wiki/Disarium_numbers
Disarium numbers
A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number. E.G. 135 is a Disarium number: 11 + 32 + 53 == 1 + 9 + 125 == 135 There are a finite number of Disarium numbers. Task Find and display the first 18 Disarium numbers. Stretch Find and display all 20 Disarium numbers. See also Geeks for Geeks - Disarium numbers OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...) Related task: Narcissistic decimal number Related task: Own digits power sum Which seems to be the same task as Narcissistic decimal number...
#Julia
Julia
isdisarium(n) = sum(last(p)^first(p) for p in enumerate(reverse(digits(n)))) == n   function disariums(numberwanted) n, ret = 0, Int[] while length(ret) < numberwanted isdisarium(n) && push!(ret, n) n += 1 end return ret end   println(disariums(19)) @time disariums(19)  
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.
#PHP
PHP
<?php $ipv4_record = dns_get_record("www.kame.net",DNS_A); $ipv6_record = dns_get_record("www.kame.net",DNS_AAAA); print "ipv4: " . $ipv4_record[0]["ip"] . "\n"; print "ipv6: " . $ipv6_record[0]["ipv6"] . "\n"; ?>
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.
#PicoLisp
PicoLisp
(make (in '(host "www.kame.net") (while (from "address ") (link (till "^J" 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.
#Pike
Pike
  > array ips = Protocols.DNS.gethostbyname("www.kame.net")[1] || ({}); > write(ips*"\n");