task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Draw_a_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
#Scheme
Scheme
  (import (scheme base) (scheme inexact) (scheme time) (pstk))   (define PI 3.1415927)   ;; Draws the hands on the canvas using the current time, and repeats each second (define (hands canvas) (canvas 'delete 'withtag "hands")   (let* ((time (current-second)) ; no time locality used, so displays time in GMT (hours (floor (/ time 3600))) (rem (- time (* hours 3600))) (mins (floor (/ rem 60))) (secs (- rem (* mins 60))) (second-angle (* secs (* 2 PI 1/60))) (minute-angle (* mins (* 2 PI 1/60))) (hour-angle (* hours (* 2 PI 1/12)))) (canvas 'create 'line ; second hand 100 100 (+ 100 (* 90 (sin second-angle))) (- 100 (* 90 (cos second-angle))) 'width: 1 'tags: "hands") (canvas 'create 'line ; minute hand 100 100 (+ 100 (* 85 (sin minute-angle))) (- 100 (* 85 (cos minute-angle))) 'width: 3 'capstyle: "projecting" 'tags: "hands") (canvas 'create 'line ; hour hand 100 100 (+ 100 (* 60 (sin hour-angle))) (- 100 (* 60 (cos hour-angle))) 'width: 7 'capstyle: "projecting" 'tags: "hands")) (tk/after 1000 (lambda () (hands canvas))))   ;; Create the initial frame, clock frame and hours (let ((tk (tk-start))) (tk/wm 'title tk "GMT Clock")   (let ((canvas (tk 'create-widget 'canvas))) (tk/pack canvas) (canvas 'configure 'height: 200 'width: 200) (canvas 'create 'oval 2 2 198 198 'fill: "white" 'outline: "black") (do ((h 1 (+ 1 h))) ((> h 12) ) (let ((angle (- (/ PI 2) (* h PI 1/6)))) (canvas 'create 'text (+ 100 (* 90 (cos angle))) (- 100 (* 90 (sin angle))) 'text: (number->string h) 'font: "{Helvetica -12}")))   (hands canvas)) (tk-event-loop tk))  
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.
#Erlang
Erlang
-module(srv). -export([start/0, wait/0]).   start() -> net_kernel:start([srv,shortnames]), erlang:set_cookie(node(), rosetta), Pid = spawn(srv,wait,[]), register(srv,Pid), io:fwrite("~p ready~n",[node(Pid)]), ok.   wait() -> receive {echo, Pid, Any} -> io:fwrite("-> ~p from ~p~n", [Any, node(Pid)]), Pid ! {hello, Any}, wait(); Any -> io:fwrite("Error ~p~n", [Any]) 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.
#CoffeeScript
CoffeeScript
  # runs under node.js dns = require 'dns'   dns.resolve4 'www.kame.net', (err, addresses) -> console.log 'IP4' console.log addresses   dns.resolve6 'www.kame.net', (err, addresses) -> console.log 'IP6' console.log addresses  
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.
#Common_Lisp
Common Lisp
(sb-bsd-sockets:host-ent-addresses (sb-bsd-sockets:get-host-by-name "www.rosettacode.org")) (#(71 19 147 227))
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.
#Crystal
Crystal
require "socket"   Socket::Addrinfo.resolve( "www.kame.net", 80, type: Socket::Type::STREAM ).each { |a| puts a.ip_address.address }
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.
#Openscad
Openscad
level = 8; linewidth = .1; // fraction of segment length sqrt2 = pow(2, .5);   // Draw a dragon curve "level" going from [0,0] to [1,0] module dragon(level) { if (level <= 0) { translate([.5,0]) cube([1+linewidth,linewidth,linewidth],center=true); } else { rotate(-45) scale(1/sqrt2) dragon(level-1); translate([1,0]) rotate(-135) scale(1/sqrt2) dragon(level-1); } }   scale(40) { // scale to nicely visible in the default GUI sphere(1.5*linewidth / pow(2,level/2)); // mark the start of the curve dragon(level); }  
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
#Elixir
Elixir
defmodule Linear_combination do def display(coeff) do Enum.with_index(coeff) |> Enum.map_join(fn {n,i} -> {m,s} = if n<0, do: {-n,"-"}, else: {n,"+"} case {m,i} do {0,_} -> "" {1,i} -> "#{s}e(#{i+1})" {n,i} -> "#{s}#{n}*e(#{i+1})" end end) |> String.trim_leading("+") |> case do "" -> IO.puts "0" str -> IO.puts str end end end   coeffs = [ [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] ] Enum.each(coeffs, &Linear_combination.display(&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
#F.23
F#
  // Display a linear combination. Nigel Galloway: March 28th., 2018 let fN g = let rec fG n g=match g with |0::g -> fG (n+1) g |1::g -> printf "+e(%d)" n; fG (n+1) g |(-1)::g -> printf "-e(%d)" n; fG (n+1) g |i::g -> printf "%+de(%d)" i n; fG (n+1) g |_ -> printfn "" let rec fN n g=match g with |0::g -> fN (n+1) g |1::g -> printf "e(%d)" n; fG (n+1) g |(-1)::g -> printf "-e(%d)" n; fG (n+1) g |i::g -> printf "%de(%d)" i n; fG (n+1) g |_ -> printfn "0" fN 1 g  
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Factor
Factor
def class Foo { """ This is a docstring. Every object in Fancy can have it's own docstring. Either defined in the source code, like this one, or by using the Object#docstring: method """ def a_method { """ Same for methods. They can have docstrings, too. """ } } Foo docstring println # prints docstring Foo class Foo instance_method: 'a_method . docstring println # prints method's docstring
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Fancy
Fancy
def class Foo { """ This is a docstring. Every object in Fancy can have it's own docstring. Either defined in the source code, like this one, or by using the Object#docstring: method """ def a_method { """ Same for methods. They can have docstrings, too. """ } } Foo docstring println # prints docstring Foo class Foo instance_method: 'a_method . docstring println # prints method's docstring
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Forth
Forth
\ this is a comment
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).
#Go
Go
package main   import "fmt"   func averageSquareDiff(f float64, preds []float64) (av float64) { for _, pred := range preds { av += (pred - f) * (pred - f) } av /= float64(len(preds)) return }   func diversityTheorem(truth float64, preds []float64) (float64, float64, float64) { av := 0.0 for _, pred := range preds { av += pred } av /= float64(len(preds)) avErr := averageSquareDiff(truth, preds) crowdErr := (truth - av) * (truth - av) div := averageSquareDiff(av, preds) return avErr, crowdErr, div }   func main() { predsArray := [2][]float64{{48, 47, 51}, {48, 47, 51, 42}} truth := 49.0 for _, preds := range predsArray { avErr, crowdErr, div := diversityTheorem(truth, preds) fmt.Printf("Average-error : %6.3f\n", avErr) fmt.Printf("Crowd-error  : %6.3f\n", crowdErr) fmt.Printf("Diversity  : %6.3f\n\n", div) } }
http://rosettacode.org/wiki/Draw_a_sphere
Draw a sphere
Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a Deathstar
#Sidef
Sidef
func normalize (vec) { vec »/» (vec »*« vec -> sum.sqrt) } func dot (x, y) { -(x »*« y -> sum) `max` 0 }   var x = var y = 255 x += 1 if x.is_even # must be odd   var light = normalize([ 3, 2, -5 ]) var depth = 255   func draw_sphere(rad, k, ambient) { var pixels = [] var r2 = (rad * rad) var range = (-rad .. rad) for x,y in (range ~X range) { if ((var x2 = x*x) + (var y2 = y*y) < r2) { var vector = normalize([x, y, (r2 - x2 - y2).sqrt]) var intensity = (dot(light, vector)**k + ambient) var pixel = (0 `max` (intensity*depth -> int) `min` depth) pixels << pixel } else { pixels << 0 } } return pixels }   var outfile = %f'sphere-sidef.pgm' var out = outfile.open('>:raw')   out.say("P5\n#{x} #{y}\n#{depth}") # .pgm header out.print(draw_sphere((x-1)/2, .9, .2).map{.chr}.join) out.close
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.
#J
J
depth=: (i.~ ~.)@(0 i."1~' '=];._2) tree=: (i: 0>.<:@{:)\ width=: {{NB. y is tree c=. *i.#y NB. children NB. sum of children, inductively y (+//. c&*)`(~.@[)`]}^:_ c }}   NB. avoid dark colors NB. avoid dark colors NB. avoid dark colors pastel=: {{256#.192+?y$,:3#64}}   task=: {{ depths=: depth y NB. outline structure t=: tree depths NB. outline as tree pad=: (i.#depths) -. t,I.(=>./)depths tr=: t,pad NB. outline as constant depth tree dr=: depths,1+pad{depths lines=:(#dr){.<@dlb;._2 y widths=. width tr NB. column widths top=. I.2>dr color=.<"1 hfd 8421504 (I.tr e.pad)} (top top} tr)&{^:_ (<:2^24),pastel<:#dr r=.'{| class="wikitable" style="text-align: center;"',LF for_d.~.dr do. NB. descend through the depths k=.I.d=dr NB. all lines at this depth p=. |:({:,~{&tr)^:d ,:k j=. k/:p NB. order padding to fit parents r=. r,'|-',LF r=. r,;'| style="background: #',L:0 (j{color),L:0'" colspan=',L:0(j{widths),&":each' | ',L:0 (j{lines),L:0 LF end. r=.r,'|}',LF }}
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
#Scratch
Scratch
$ include "seed7_05.s7i"; include "float.s7i"; include "math.s7i"; include "draw.s7i"; include "keybd.s7i"; include "time.s7i"; include "duration.s7i";   const integer: WINDOW_WIDTH is 200; const integer: WINDOW_HEIGHT is 200; const color: BACKGROUND is White; const color: FOREGROUND is Black; const color: CLOCKCOLOR is Aqua;   const proc: main is func local var char: command is ' '; var time: start_time is time.value; var float: alpha is 0.0; var integer: x is 0; begin screen(WINDOW_WIDTH, WINDOW_HEIGHT); clear(curr_win, BACKGROUND); KEYBOARD := GRAPH_KEYBOARD; command := busy_getc(KEYBOARD); while command <> 'q' do start_time := truncToSecond(time(NOW)); clear(curr_win, BACKGROUND); fcircle(100, 100, 95, CLOCKCOLOR); circle(100, 100, 95, FOREGROUND); for x range 0 to 60 do alpha := flt(x-15) * PI / 30.0; if x mod 5 = 0 then lineTo(100 + round(cos(alpha)*95.0), 100 + round(sin(alpha)*95.0), 100 + round(cos(alpha)*85.0), 100 + round(sin(alpha)*85.0), FOREGROUND); else lineTo(100 + round(cos(alpha)*95.0), 100 + round(sin(alpha)*95.0), 100 + round(cos(alpha)*92.0), 100 + round(sin(alpha)*92.0), FOREGROUND); end if; end for; alpha := flt(start_time.second-15) * PI / 30.0; lineTo(100, 100, 100 + round(cos(alpha)*85.0), 100 + round(sin(alpha)*85.0), FOREGROUND); alpha := flt(start_time.minute-15) * PI / 30.0; lineTo(100 + round(cos(alpha-PI/2.0)*5.0), 100 + round(sin(alpha-PI/2.0)*5.0), 100 + round(cos(alpha)*75.0), 100 + round(sin(alpha)*75.0), FOREGROUND); lineTo(100 + round(cos(alpha+PI/2.0)*5.0), 100 + round(sin(alpha+PI/2.0)*5.0), 100 + round(cos(alpha)*75.0), 100 + round(sin(alpha)*75.0), FOREGROUND); alpha := (flt(start_time.hour)+flt(start_time.minute)/60.0-3.0) * PI / 6.0; lineTo(100 + round(cos(alpha-PI/2.0)*7.0), 100 + round(sin(alpha-PI/2.0)*7.0), 100 + round(cos(alpha)*50.0), 100 + round(sin(alpha)*50.0), FOREGROUND); lineTo(100 + round(cos(alpha+PI/2.0)*7.0), 100 + round(sin(alpha+PI/2.0)*7.0), 100 + round(cos(alpha)*50.0), 100 + round(sin(alpha)*50.0), FOREGROUND); fcircle(100, 100, 7, CLOCKCOLOR); circle(100, 100, 7, FOREGROUND); DRAW_FLUSH; await(start_time + 1 . SECONDS); command := busy_getc(KEYBOARD); end while; end func;
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.
#Factor
Factor
USING: concurrency.distributed concurrency.messaging threads io.sockets io.servers ; QUALIFIED: concurrency.messaging : prettyprint-message ( -- ) concurrency.messaging:receive . flush prettyprint-message ; [ prettyprint-message ] "logger" spawn dup name>> register-remote-thread "127.0.0.1" 9000 <inet4> <node-server> start-server
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.
#Go
Go
package main   import ( "errors" "log" "net" "net/http" "net/rpc" )   type TaxComputer float64   func (taxRate TaxComputer) Tax(x float64, r *float64) error { if x < 0 { return errors.New("Negative values not allowed") } *r = x * float64(taxRate) return nil }   func main() { c := TaxComputer(.05) rpc.Register(c) rpc.HandleHTTP() listener, err := net.Listen("tcp", ":1234") if err != nil { log.Fatal(err) } http.Serve(listener, nil) }
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.
#D
D
import std.stdio, std.socket;   void main() { auto domain = "www.kame.net", port = "80";   auto a = getAddressInfo(domain, port, AddressFamily.INET); writefln("IPv4 address for %s: %s", domain, a[0].address);   a = getAddressInfo(domain, port, AddressFamily.INET6); writefln("IPv6 address for %s: %s", domain, a[0].address); }
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.
#Delphi
Delphi
program DNSQuerying;   {$APPTYPE CONSOLE}   uses IdGlobal, IdStackWindows;   const DOMAIN_NAME = 'www.kame.net'; var lStack: TIdStackWindows; begin lStack := TIdStackWindows.Create; try Writeln(DOMAIN_NAME); Writeln('IPv4: ' + lStack.ResolveHost(DOMAIN_NAME)); Writeln('IPv6: ' + lStack.ResolveHost(DOMAIN_NAME, Id_IPv6)); finally lStack.Free; end; end.
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.
#PARI.2FGP
PARI/GP
level = 13 p = [0, 1]; \\ complex number points, initially 0 to 1   \\ "unfold" at the current endpoint p[#p]. \\ p[^-1] so as not to duplicate that endpoint. \\ \\ * end \\ --> | \\ / | \\ v \\ *------->* \\ 0,0 p[#p] \\ for(i=1,level, my(end = (1+I)*p[#p]); \ p = concat(p, apply(z->(end - I*z), Vecrev(p[^-1]))))   plothraw(apply(real,p),apply(imag,p), 1); \\ flag=1 join points
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
#Factor
Factor
USING: formatting kernel match math pair-rocket regexp sequences ;   MATCH-VARS: ?a ?b ;   : choose-term ( coeff i -- str ) 1 + { } 2sequence { { 0 _ } => [ "" ] { 1 ?a } => [ ?a "e(%d)" sprintf ] { -1 ?a } => [ ?a "-e(%d)" sprintf ] { ?a ?b } => [ ?a ?b "%d*e(%d)" sprintf ] } match-cond ;   : linear-combo ( seq -- str ) [ choose-term ] map-index harvest " + " join R/ \+ -/ "- " re-replace [ "0" ] when-empty ;   { { 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 } } [ dup linear-combo "%-14u ->  %s\n" printf ] each
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
#FreeBASIC
FreeBASIC
Dim scalars(1 To 10, 1 To 4) As Integer => {{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 n As Integer = 1 To Ubound(scalars) Dim As String cadena = "" Dim As Integer scalar For m As Integer = 1 To Ubound(scalars,2) scalar = scalars(n, m) If scalar <> 0 Then If scalar = 1 Then cadena &= "+e" & m Elseif scalar = -1 Then cadena &= "-e" & m Else If scalar > 0 Then cadena &= Chr(43) & scalar & "*e" & m Else cadena &= scalar & "*e" & m End If End If End If Next m If cadena = "" Then cadena = "0" If Left(cadena, 1) = "+" Then cadena = Right(cadena, Len(cadena)-1) Print cadena Next n Sleep
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Fortran
Fortran
SUBROUTINE SHOW(A,N) !Prints details to I/O unit LINPR. REAL*8 A !Distance to the next node. INTEGER N !Number of the current node.
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#FreeBASIC
FreeBASIC
// Example serves as an example but does nothing useful. // // A package comment preceeds the package clause and explains the purpose // of the package. package example   // Exported variables. var ( // lookie X, Y, Z int // popular names )   /* XP does nothing.   Here's a block comment. */ func XP() { // here we go! // comments inside }   // Non-exported. func nonXP() {}   // Doc not extracted.   var MEMEME int
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Go
Go
// Example serves as an example but does nothing useful. // // A package comment preceeds the package clause and explains the purpose // of the package. package example   // Exported variables. var ( // lookie X, Y, Z int // popular names )   /* XP does nothing.   Here's a block comment. */ func XP() { // here we go! // comments inside }   // Non-exported. func nonXP() {}   // Doc not extracted.   var MEMEME int
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).
#Groovy
Groovy
class DiversityPredictionTheorem { private static double square(double d) { return d * d }   private static double averageSquareDiff(double d, double[] predictions) { return Arrays.stream(predictions) .map({ it -> square(it - d) }) .average() .orElseThrow() }   private static String diversityTheorem(double truth, double[] predictions) { double average = Arrays.stream(predictions) .average() .orElseThrow() return String.format("average-error : %6.3f%n", averageSquareDiff(truth, predictions)) + String.format("crowd-error  : %6.3f%n", square(truth - average)) + String.format("diversity  : %6.3f%n", averageSquareDiff(average, predictions)) }   static void main(String[] args) { println(diversityTheorem(49.0, [48.0, 47.0, 51.0] as double[])) println(diversityTheorem(49.0, [48.0, 47.0, 51.0, 42.0] as double[])) } }
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
#Smalltalk
Smalltalk
  Point3D := Point subclass:#Point3D instanceVariableNames:'z' classVariableNames:'' poolDictionaries:'' category:'' inEnvironment:nil.   Point3D compile:'z ^ z'. Point3D compile:'z:v z := v'.   normalize := [:v | |invLen| invLen := 1 / (dot value:v value:v) sqrt. v x: v x * invLen. v y: v y * invLen. v z: v z * invLen. ].   dot := [:a :b | (a x * b x) + (a y * b y) + (a z * b z) ].   drawSphere := [:r :k :amb :dir | |w h imh vec img|   w := r*4. h := r*3. img := Image width:w height:h depth:8. img photometric:#blackIs0; createPixelStore. vec := Point3D new. 0-r to:r do:[:x | 0-r to:r do:[:y | |z s lum| (z := (r*r) - (x*x) - (y*y)) >= 0 ifTrue:[ vec x: x. vec y: y. vec z: z sqrt. normalize value:vec. s := dot value:dir value:vec. s < 0 ifTrue:[ s := 0 ]. lum := 255 * ((s raisedTo: k) + amb) / (1 + amb). lum < 0 ifTrue:[ lum := 0 ] ifFalse:[ lum > 255 ifTrue:[ lum := 255 ]]. img atX:(x+(w//2)) y:(y+(h//2)) put:(Color greyByte:lum). ] ] ]. img ].   main := [ |dir img|   dir := Point3D new x:-30; y:-30; z:50; yourself. normalize value:dir. img := drawSphere value: 100 value: 1.5 value: 0.2 value: dir. img displayOn:(View new extent:400@400; openAndWait). img saveOn:'sphere.png'. ].   main value.  
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
#Action.21
Action!
SET EndProg=*
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.
#JavaScript
JavaScript
(() => { "use strict";   // ----------- NESTED TABLES FROM OUTLINE ------------   // wikiTablesFromOutline :: [String] -> String -> String const wikiTablesFromOutline = colorSwatch => outline => forestFromIndentedLines( indentLevelsFromLines(lines(outline)) ) .map(wikiTableFromTree(colorSwatch)) .join("\n\n");     // wikiTableFromTree :: [String] -> Tree String -> String const wikiTableFromTree = colorSwatch => compose( wikiTableFromRows, levels, paintedTree(colorSwatch), widthLabelledTree, ap(paddedTree(""))(treeDepth) );   // ---------------------- TEST ----------------------- // main :: IO () const main = () => { const outline = `Display an outline as a nested table. Parse the outline to a tree, measuring the indent of each line, translating the indentation to a nested structure, and padding the tree to even depth. count the leaves descending from each node, defining the width of a leaf as 1, and the width of a parent node as a sum. (The sum of the widths of its children) and write out a table with 'colspan' values either as a wiki table, or as HTML.`;   return wikiTablesFromOutline([ "#ffffe6", "#ffebd2", "#f0fff0", "#e6ffff", "#ffeeff" ])(outline); };   // --------- TREE STRUCTURE FROM NESTED TEXT ---------   // forestFromIndentedLines :: [(Int, String)] -> // [Tree String] const forestFromIndentedLines = tuples => { const go = xs => 0 < xs.length ? (() => { // First line and its sub-tree, const [indented, body] = Array.from( xs[0] ), [tree, rest] = Array.from( span(compose(lt(indented), fst))( tail(xs) ) );   // followed by the rest. return [ Node(body)(go(tree)) ].concat(go(rest)); })() : [];   return go(tuples); };     // indentLevelsFromLines :: [String] -> [(Int, String)] const indentLevelsFromLines = xs => { const pairs = xs.map( x => bimap(length)(cs => cs.join(""))( span(isSpace)(list(x)) ) ), indentUnit = pairs.reduce( (a, tpl) => { const i = tpl[0];   return 0 < i ? ( i < a ? i : a ) : a; }, Infinity );   return [Infinity, 0].includes(indentUnit) ? ( pairs ) : pairs.map(first(n => n / indentUnit)); };   // ------------ TREE PADDED TO EVEN DEPTH ------------   // paddedTree :: a -> Tree a -> Int -> Tree a const paddedTree = padValue => // All descendants expanded to same depth // with empty nodes where needed. node => depth => { const go = n => tree => 1 < n ? (() => { const children = nest(tree);   return Node(root(tree))( ( 0 < children.length ? ( children ) : [Node(padValue)([])] ).map(go(n - 1)) ); })() : tree;   return go(depth)(node); };   // treeDepth :: Tree a -> Int const treeDepth = tree => foldTree( () => xs => 0 < xs.length ? ( 1 + maximum(xs) ) : 1 )(tree);   // ------------- SUBTREE WIDTHS MEASURED -------------   // widthLabelledTree :: Tree a -> Tree (a, Int) const widthLabelledTree = tree => // A tree in which each node is labelled with // the width of its own subtree. foldTree(x => xs => 0 < xs.length ? ( Node(Tuple(x)( xs.reduce( (a, node) => a + snd(root(node)), 0 ) ))(xs) ) : Node(Tuple(x)(1))([]) )(tree);   // -------------- COLOR SWATCH APPLIED ---------------   // paintedTree :: [String] -> Tree a -> Tree (String, a) const paintedTree = colorSwatch => tree => 0 < colorSwatch.length ? ( Node( Tuple(colorSwatch[0])(root(tree)) )( zipWith(compose(fmapTree, Tuple))( cycle(colorSwatch.slice(1)) )( nest(tree) ) ) ) : fmapTree(Tuple(""))(tree);   // --------------- WIKITABLE RENDERED ----------------   // wikiTableFromRows :: // [[(String, (String, Int))]] -> String const wikiTableFromRows = rows => { const cw = color => width => { const go = w => 1 < w ? ( `colspan=${w} ` ) : "";   return `style="background:${color}; "` + ( ` ${go(width)}` ); }, cellText = ctw => { const [color, tw] = Array.from(ctw); const [txt, width] = Array.from(tw);   return 0 < txt.length ? ( `| ${cw(color)(width)}| ${txt}` ) : "| |"; }, classText = "class=\"wikitable\"", styleText = "style=\"text-align:center;\"", header = `{| ${classText} ${styleText}\n|-`, tableBody = rows.map( cells => cells.map(cellText).join("\n") ).join("\n|-\n");   return `${header}\n${tableBody}\n|}`; };   // ------------------ GENERIC TREES ------------------   // Node :: a -> [Tree a] -> Tree a const Node = v => // Constructor for a Tree node which connects a // value of some kind to a list of zero or // more child trees. xs => ({ type: "Node", root: v, nest: xs || [] });     // fmapTree :: (a -> b) -> Tree a -> Tree b const fmapTree = f => { // A new tree. The result of a // structure-preserving application of f // to each root in the existing tree. const go = t => Node( f(t.root) )( t.nest.map(go) );   return go; };     // foldTree :: (a -> [b] -> b) -> Tree a -> b const foldTree = f => { // The catamorphism on trees. A summary // value obtained by a depth-first fold. const go = tree => f( root(tree) )( nest(tree).map(go) );   return go; };     // levels :: Tree a -> [[a]] const levels = tree => { // A list of lists, grouping the root // values of each level of the tree. const go = (a, node) => { const [h, ...t] = 0 < a.length ? ( a ) : [ [], [] ];   return [ [node.root, ...h], ...node.nest.slice(0) .reverse() .reduce(go, t) ]; };   return go([], tree); };     // nest :: Tree a -> [a] const nest = tree => { // Allowing for lazy (on-demand) evaluation. // If the nest turns out to be a function – // rather than a list – that function is applied // here to the root, and returns a list. const xs = tree.nest;   return "function" !== typeof xs ? ( xs ) : xs(root(tree)); };     // root :: Tree a -> a const root = tree => // The value attached to a tree node. tree.root;   // --------------------- GENERIC ---------------------   // Just :: a -> Maybe a const Just = x => ({ type: "Maybe", Nothing: false, Just: x });     // Nothing :: Maybe a const Nothing = () => ({ type: "Maybe", Nothing: true });     // Tuple (,) :: a -> b -> (a, b) const Tuple = a => b => ({ type: "Tuple", "0": a, "1": b, length: 2 });     // apFn :: (a -> b -> c) -> (a -> b) -> (a -> c) const ap = f => // Applicative instance for functions. // f(x) applied to g(x). g => x => f(x)( g(x) );     // bimap :: (a -> b) -> (c -> d) -> (a, c) -> (b, d) const bimap = f => // Tuple instance of bimap. // A tuple of the application of f and g to the // first and second values respectively. g => tpl => Tuple(f(tpl[0]))( g(tpl[1]) );     // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c const compose = (...fs) => // A function defined by the right-to-left // composition of all the functions in fs. fs.reduce( (f, g) => x => f(g(x)), x => x );     // cycle :: [a] -> Generator [a] const cycle = function* (xs) { // An infinite repetition of xs, // from which an arbitrary prefix // may be taken. const lng = xs.length; let i = 0;   while (true) { yield xs[i]; i = (1 + i) % lng; } };     // first :: (a -> b) -> ((a, c) -> (b, c)) const first = f => // A simple function lifted to one which applies // to a tuple, transforming only its first item. xy => { const tpl = Tuple(f(xy[0]))(xy[1]);   return Array.isArray(xy) ? ( Array.from(tpl) ) : tpl; };     // fst :: (a, b) -> a const fst = tpl => // First member of a pair. tpl[0];     // isSpace :: Char -> Bool const isSpace = c => // True if c is a white space character. (/\s/u).test(c);     // length :: [a] -> Int const length = xs => // Returns Infinity over objects without finite // length. This enables zip and zipWith to choose // the shorter argument when one is non-finite, // like cycle, repeat etc "GeneratorFunction" !== xs.constructor .constructor.name ? ( xs.length ) : Infinity;     // lines :: String -> [String] const lines = s => // A list of strings derived from a single // string delimited by newline and or CR. 0 < s.length ? ( s.split(/[\r\n]+/u) ) : [];     // list :: StringOrArrayLike b => b -> [a] const list = xs => // xs itself, if it is an Array, // or an Array derived from xs. Array.isArray(xs) ? ( xs ) : Array.from(xs || []);     // lt (<) :: Ord a => a -> a -> Bool const lt = a => b => a < b;     // maximum :: Ord a => [a] -> a const maximum = xs => ( // The largest value in a non-empty list. ys => 0 < ys.length ? ( ys.slice(1).reduce( (a, y) => y > a ? ( y ) : a, ys[0] ) ) : undefined )(list(xs));     // snd :: (a, b) -> b const snd = tpl => // Second member of a pair. tpl[1];     // span :: (a -> Bool) -> [a] -> ([a], [a]) const span = p => // Longest prefix of xs consisting of elements which // all satisfy p, tupled with the remainder of xs. xs => { const i = xs.findIndex(x => !p(x));   return -1 !== i ? ( Tuple(xs.slice(0, i))( xs.slice(i) ) ) : Tuple(xs)([]); };     // tail :: [a] -> [a] const tail = xs => // A new list consisting of all // items of xs except the first. "GeneratorFunction" !== xs.constructor .constructor.name ? ( (ys => 0 < ys.length ? ys.slice(1) : [])( xs ) ) : (take(1)(xs), xs);     // take :: Int -> [a] -> [a] // take :: Int -> String -> String const take = n => // The first n elements of a list, // string of characters, or stream. xs => "GeneratorFunction" !== xs .constructor.constructor.name ? ( xs.slice(0, n) ) : [].concat(...Array.from({ length: n }, () => { const x = xs.next();   return x.done ? [] : [x.value]; }));     // uncons :: [a] -> Maybe (a, [a]) const uncons = xs => { // Just a tuple of the head of xs and its tail, // Or Nothing if xs is an empty list. const lng = length(xs);   return (0 < lng) ? ( Infinity > lng ? ( // Finite list Just(Tuple(xs[0])(xs.slice(1))) ) : (() => { // Lazy generator const nxt = take(1)(xs);   return 0 < nxt.length ? ( Just(Tuple(nxt[0])(xs)) ) : Nothing(); })() ) : Nothing(); };     // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] const zipWith = f => // A list with the length of the shorter of // xs and ys, defined by zipping with a // custom function, rather than with the // default tuple constructor. xs => ys => { const n = Math.min(length(xs), length(ys));   return Infinity > n ? ( (([as, bs]) => Array.from({ length: n }, (_, i) => f(as[i])( bs[i] )))([xs, ys].map( take(n) )) ) : zipWithGen(f)(xs)(ys); };     // zipWithGen :: (a -> b -> c) -> // Gen [a] -> Gen [b] -> Gen [c] const zipWithGen = f => ga => gb => { const go = function* (ma, mb) { let a = ma, b = mb;   while (!a.Nothing && !b.Nothing) { const ta = a.Just, tb = b.Just;   yield f(fst(ta))(fst(tb)); a = uncons(snd(ta)); b = uncons(snd(tb)); } };   return go(uncons(ga), uncons(gb)); };   // MAIN --- return main(); })();
http://rosettacode.org/wiki/Draw_a_clock
Draw a clock
Task Draw a clock. More specific: Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be drawn; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK. The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock. A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task. A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language. Key points animate simple object timed event polling system resources code clarity
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i"; include "math.s7i"; include "draw.s7i"; include "keybd.s7i"; include "time.s7i"; include "duration.s7i";   const integer: WINDOW_WIDTH is 200; const integer: WINDOW_HEIGHT is 200; const color: BACKGROUND is White; const color: FOREGROUND is Black; const color: CLOCKCOLOR is Aqua;   const proc: main is func local var char: command is ' '; var time: start_time is time.value; var float: alpha is 0.0; var integer: x is 0; begin screen(WINDOW_WIDTH, WINDOW_HEIGHT); clear(curr_win, BACKGROUND); KEYBOARD := GRAPH_KEYBOARD; command := busy_getc(KEYBOARD); while command <> 'q' do start_time := truncToSecond(time(NOW)); clear(curr_win, BACKGROUND); fcircle(100, 100, 95, CLOCKCOLOR); circle(100, 100, 95, FOREGROUND); for x range 0 to 60 do alpha := flt(x-15) * PI / 30.0; if x mod 5 = 0 then lineTo(100 + round(cos(alpha)*95.0), 100 + round(sin(alpha)*95.0), 100 + round(cos(alpha)*85.0), 100 + round(sin(alpha)*85.0), FOREGROUND); else lineTo(100 + round(cos(alpha)*95.0), 100 + round(sin(alpha)*95.0), 100 + round(cos(alpha)*92.0), 100 + round(sin(alpha)*92.0), FOREGROUND); end if; end for; alpha := flt(start_time.second-15) * PI / 30.0; lineTo(100, 100, 100 + round(cos(alpha)*85.0), 100 + round(sin(alpha)*85.0), FOREGROUND); alpha := flt(start_time.minute-15) * PI / 30.0; lineTo(100 + round(cos(alpha-PI/2.0)*5.0), 100 + round(sin(alpha-PI/2.0)*5.0), 100 + round(cos(alpha)*75.0), 100 + round(sin(alpha)*75.0), FOREGROUND); lineTo(100 + round(cos(alpha+PI/2.0)*5.0), 100 + round(sin(alpha+PI/2.0)*5.0), 100 + round(cos(alpha)*75.0), 100 + round(sin(alpha)*75.0), FOREGROUND); alpha := (flt(start_time.hour)+flt(start_time.minute)/60.0-3.0) * PI / 6.0; lineTo(100 + round(cos(alpha-PI/2.0)*7.0), 100 + round(sin(alpha-PI/2.0)*7.0), 100 + round(cos(alpha)*50.0), 100 + round(sin(alpha)*50.0), FOREGROUND); lineTo(100 + round(cos(alpha+PI/2.0)*7.0), 100 + round(sin(alpha+PI/2.0)*7.0), 100 + round(cos(alpha)*50.0), 100 + round(sin(alpha)*50.0), FOREGROUND); fcircle(100, 100, 7, CLOCKCOLOR); circle(100, 100, 7, FOREGROUND); DRAW_FLUSH; await(start_time + 1 . SECONDS); command := busy_getc(KEYBOARD); end while; end func;
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.
#Haskell
Haskell
var net = require('net')   var server = net.createServer(function (c){ c.write('hello\r\n') c.pipe(c) // echo messages back })   server.listen(3000, 'localhost')  
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.
#JavaScript
JavaScript
var net = require('net')   var server = net.createServer(function (c){ c.write('hello\r\n') c.pipe(c) // echo messages back })   server.listen(3000, 'localhost')  
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.
#Erlang
Erlang
  33> {ok, {hostent, Host, Aliases, AddrType, Bytes, AddrList}} = inet:gethostbyname("www.kame.net", inet). {ok,{hostent,"orange.kame.net", ["www.kame.net"], inet,4, [{203,178,141,194}]}} 34> [inet_parse:ntoa(Addr) || Addr <- AddrList]. ["203.178.141.194"] 35> f(). ok 36> {ok, {hostent, Host, Aliases, AddrType, Bytes, AddrList}} = inet:gethostbyname("www.kame.net", inet6). {ok,{hostent,"orange.kame.net",[],inet6,16, [{8193,512,3583,65521,534,16127,65201,17623}]}} 37> [inet_parse:ntoa(Addr) || Addr <- AddrList]. ["2001:200:DFF:FFF1:216:3EFF:FEB1:44D7"]  
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.
#Pascal
Pascal
procedure dcr(step,dir:integer;length:real); begin; step:=step -1; length:= length/sqrt(2); if dir > 0 then begin if step > 0 then begin turnright(45); dcr(step,1,length); turnleft(90); dcr(step,0,length); turnright(45); end else begin turnright(45); forward(length); turnleft(90); forward(length); turnright(45); end; end else begin if step > 0 then begin turnleft(45); dcr(step,1,length); turnright(90); dcr(step,0,length); turnleft(45); end else begin turnleft(45); forward(length); turnright(90); forward(length); turnleft(45); end; end; 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
#Go
Go
package main   import ( "fmt" "strings" )   func linearCombo(c []int) string { var sb strings.Builder for i, n := range c { if n == 0 { continue } var op string switch { case n < 0 && sb.Len() == 0: op = "-" case n < 0: op = " - " case n > 0 && sb.Len() == 0: op = "" default: op = " + " } av := n if av < 0 { av = -av } coeff := fmt.Sprintf("%d*", av) if av == 1 { coeff = "" } sb.WriteString(fmt.Sprintf("%s%se(%d)", op, coeff, i+1)) } if sb.Len() == 0 { return "0" } else { return sb.String() } }   func main() { combos := [][]int{ {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 := range combos { t := strings.Replace(fmt.Sprint(c), " ", ", ", -1) fmt.Printf("%-15s ->  %s\n", t, linearCombo(c)) } }
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Gri
Gri
`My Hello Message' Print a greeting to the user. This is only a short greeting. { show "hello" }
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Haskell
Haskell
-- |This is a documentation comment for the following function square1 :: Int -> Int square1 x = x * x   -- |It can even -- span multiple lines square2 :: Int -> Int square2 x = x * x   square3 :: Int -> Int -- ^You can put the comment underneath if you like, like this square3 x = x * x   {-| Haskell block comments are also supported -} square4 :: Int -> Int square4 x = x * x   -- |This is a documentation comment for the following datatype data Tree a = Leaf a | Node [Tree a]   -- |This is a documentation comment for the following type class class Foo a where bar :: a
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Icon_and_Unicon
Icon and Unicon
############################################################################ # # File: filename.icn # # Subject: Short Description # # Author: Author's name # # Date: Date # ############################################################################ # # This file is in the public domain. (or other license) # ############################################################################ # # Long form docmentation # ############################################################################ # # Links: # ############################################################################   procedure x1() #: short description of procedure  
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).
#Haskell
Haskell
mean :: (Fractional a, Foldable t) => t a -> a mean lst = sum lst / fromIntegral (length lst)   meanSq :: Fractional c => c -> [c] -> c meanSq x = mean . map (\y -> (x-y)^^2)   diversityPrediction x estimates = do putStrLn $ "TrueValue:\t" ++ show x putStrLn $ "CrowdEstimates:\t" ++ show estimates let avg = mean estimates let avgerr = meanSq x estimates putStrLn $ "AverageError:\t" ++ show avgerr let crowderr = (x - avg)^^2 putStrLn $ "CrowdError:\t" ++ show crowderr let diversity = meanSq avg estimates putStrLn $ "Diversity:\t" ++ show diversity
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).
#J
J
  echo 'Use: ' , (;:inv 2 {. ARGV) , ' <reference value> <observations>'   data=: ([: ". [: ;:inv 2&}.) ::([: exit 1:) ARGV   ([: exit (1: echo@('insufficient data'"_)))^:(2 > #) data   mean=: +/ % # variance=: [: mean [: *: -   averageError=: ({. variance }.)@:] crowdError=: variance {. diversity=: variance }.   echo (<;._2'average error;crowd error;diversity;') ,: ;/ (averageError`crowdError`diversity`:0~ mean@:}.) data   exit 0  
http://rosettacode.org/wiki/Draw_a_sphere
Draw a sphere
Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a Deathstar
#SVG
SVG
  class Sphere: UIView{   override func drawRect(rect: CGRect) { let context = UIGraphicsGetCurrentContext() let locations: [CGFloat] = [0.0, 1.0]   let colors = [UIColor.whiteColor().CGColor, UIColor.blueColor().CGColor]   let colorspace = CGColorSpaceCreateDeviceRGB()   let gradient = CGGradientCreateWithColors(colorspace, colors, locations)   var startPoint = CGPoint() var endPoint = CGPoint() startPoint.x = self.center.x - (self.frame.width * 0.1) startPoint.y = self.center.y - (self.frame.width * 0.15) endPoint.x = self.center.x endPoint.y = self.center.y let startRadius: CGFloat = 0 let endRadius: CGFloat = self.frame.width * 0.38   CGContextDrawRadialGradient (context, gradient, startPoint, startRadius, endPoint, endRadius, 0) } }   var s = Sphere(frame: CGRectMake(0, 0, 200, 200))  
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
#Ada
Ada
# -*- coding: utf-8 -*- # COMMENT REQUIRES: MODE VALUE = ~; # For example: # MODE VALUE = UNION(INT, REAL, COMPL) END COMMENT   MODE LINKNEW = STRUCT ( LINK next, prev, VALUE value );   MODE LINK = REF LINKNEW;   SKIP
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.
#Julia
Julia
using DataFrames   text = """ Display an outline as a nested table. Parse the outline to a tree, measuring the indent of each line, translating the indentation to a nested structure, and padding the tree to even depth. count the leaves descending from each node, defining the width of a leaf as 1, and the width of a parent node as a sum. (The sum of the widths of its children) and write out a table with 'colspan' values either as a wiki table, or as HTML. """   const bcolor = ["background: #ffffaa;", "background: #ffdddd;", "background: #ddffdd;", "background: #ddddff;"] colorstring(n) = bcolor[n == 1 ? 1  : mod1(n - 1, length(bcolor) - 1) + 1]   function processtable(txt) df = DataFrame() indents = Int[] linetext = String[] for line in split(txt, "\n") if length(line) > 0 n = findfirst(!isspace, line) push!(linetext, String(line[n:end])) push!(indents, n - 1) end end len = length(indents) divisor = gcd(indents) indents .= div.(indents, divisor) parent(i) = (n = findlast(x -> indents[x] < indents[i], 1:i-1)) == nothing ? 0 : n children(i) = findall(x -> parent(x) == i, 1:len) treesize(i) = (s = children(i); isempty(s) ? 1 : sum(treesize, s)) prioronlevel(i) = (j = indents[i]; filter(x -> indents[x] == j, 1:i-1)) treesizeprior(i) = (s = prioronlevel(i); isempty(s) ? 0 : sum(treesize, s)) startpos(i) = (n = parent(i)) == 0 ? 0 : treesizeprior(n) - treesizeprior(i) function leveloneparent(i) p = parent(i) return p < 1 ? 1 : p ==1 ? sum(x -> indents[x] <= 1, 1:i) : leveloneparent(p) end df.TEXT = linetext df.INDENT = indents df.COLSPAN = [treesize(i) for i in 1:len] df.PRESPAN = [max(0, startpos(i)) for i in 1:len] df.LEVELONEPARENT = [leveloneparent(i) for i in 1:len] return df end   function htmlfromdataframe(df) println("<h4>A Rosetta Code Nested Table</h4><table style=\"width:100%\" class=\"wikitable\" >") for ind in minimum(df.INDENT):maximum(df.INDENT) println("<tr>") for row in eachrow(df) if row[:INDENT] == ind if row[:PRESPAN] > 0 println("<td colspan=\"$(row[:PRESPAN])\"> </td>") end print("<td ") if row[:COLSPAN] > 0 println("colspan=\"$(row[:COLSPAN])\"") end println(" style = \"$(colorstring(row[:LEVELONEPARENT]))\" >$(row[:TEXT])</td>") end end println("</tr>") end println("</table>") end   htmlfromdataframe(processtable(text)) textplus = text * " Optionally add color to the nodes." htmlfromdataframe(processtable(textplus))  
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.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
s = "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."; s = StringSplit[s, "\n"]; indentation = LengthWhile[Characters[#], EqualTo[" "]] & /@ s; s = MapThread[StringDrop, {s, indentation}]; indentation = indentation /. Thread[Union[indentation] -> Range[Length[Union[indentation]]]]; ii = Transpose[{Range[Length[indentation]], indentation}]; (*ii//Grid*)   sel = Table[ {i, Last@Select[ii, #[[2]] < i[[2]] \[And] #[[1]] < i[[1]] &]} , {i, Rest@ii} ]; g = Graph[Rule @@@ sel[[All, All, 1]], VertexLabels -> "Name"];   vl = VertexList[g]; head = FirstPosition[vl, 1][[1]]; dm = GraphDistanceMatrix[g]; depth = ReverseSortBy[Transpose[{vl, dm[[All, head]]}], Last]; colspandb = <||>; data = Table[ vert = d[[1]]; vd = VertexInDegree[g, vert]; vics = VertexInComponent[g, vert, {1}]; vocs = Rest@VertexOutComponent[g, vert]; cspan = 0; Do[ If[KeyExistsQ[colspandb, vic], cspan += colspandb[vic] ] , {vic, vics} ]; If[cspan == 0, cspan = 1]; AssociateTo[colspandb, d[[1]] -> cspan]; {Sequence @@ d, vd, vics, vocs, cspan} , {d, depth} ];   emptybefore = Table[ {d[[1]], Length@ Select[ data, #[[1]] < d[[1]] \[And] Length[#[[4]]] == 0 \[And] #[[2]] < d[[2]] &][[All, {1, 2, 3}]]} , {d, data} ]; emptybefore = Association[Rule @@@ emptybefore];   depthcopy = depth; depthcopy[[All, 2]] += 1; graphelements = SortBy[Sort /@ GatherBy[depthcopy, Last], First /* Last][[All, All, 1]];   str = {"<table style='text-align: center;'>"}; colorsdb = <|1 -> "#ffffe6", 2 -> "#ffebd2", 6 -> "#f0fff0", 10 -> "#e6ffff"|>; Do[ AppendTo[str, "<tr>"]; totalspan = 0; Do[ If[KeyExistsQ[colorsdb, g], color = colorsdb[g] , (*Print["sel",SelectFirst[data,First/*EqualTo[g]][[5]]];*)   color = colorsdb[ Max[ Intersection[SelectFirst[data, First /* EqualTo[g]][[5]], Keys[colorsdb]]]] ]; span = SelectFirst[data, First /* EqualTo[g]][[6]]; totalspan += span;   empty = emptybefore[g]; str = str~Join~ ConstantArray["<td style=\"background-color: #F9F9F9;\"></td>", empty]; If[span == 1, AppendTo[str, "<td style=\"background-color: " <> color <> ";\">" <> s[[g]] <> "</td>"]; , AppendTo[str, "<tdcolspan=\"" <> ToString[span] <> "\" style=\"background-color: " <> color <> ";\">" <> s[[g]] <> "</td>"]; ]; , {g, ge} ]; extra = SelectFirst[data, First /* EqualTo[1]][[6]] - totalspan - empty; str = str~Join~ ConstantArray["<td style=\"background-color: #F9F9F9;\"></td>", extra]; AppendTo[str, "</tr>"]; , {ge, graphelements} ] AppendTo[str, "</table>"]; StringRiffle[str, "\n"]
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
#Sidef
Sidef
STDOUT.autoflush(true)   var (rows, cols) = `stty size`.nums...   var x = (rows/2 - 1 -> int) var y = (cols/2 - 16 -> int)   var chars = [ "┌─┐ ╷╶─┐╶─┐╷ ╷┌─╴┌─╴╶─┐┌─┐┌─┐ ", "│ │ │┌─┘╶─┤└─┤└─┐├─┐ │├─┤└─┤ : ", "└─┘ ╵└─╴╶─┘ ╵╶─┘└─┘ ╵└─┘╶─┘ " ].map {|s| s.split(3) }   func position(i,j) { "\e[%d;%dH" % (i, j) }   func indices { var t = Time.local "%02d:%02d:%02d" % (t.hour, t.min, t.sec) -> split(1).map{|c| c.ord - '0'.ord } }   loop { print "\e[H\e[J" for i in ^chars { print position(x + i, y) print [chars[i][indices()]].join(' ') } print position(1, 1) Sys.sleep(0.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.
#Julia
Julia
# From Julia 1.0's online docs. File countheads.jl available to all machines:   function count_heads(n) c::Int = 0 for i = 1:n c += rand(Bool) end c end
http://rosettacode.org/wiki/Distributed_programming
Distributed programming
Write two programs (or one program with two modes) which run on networked computers, and send some messages between them. The protocol used may be language-specific or not, and should be suitable for general distributed programming; that is, the protocol should be generic (not designed just for the particular example application), readily capable of handling the independent communications of many different components of a single application, and the transferring of arbitrary data structures natural for the language. This task is intended to demonstrate high-level communication facilities beyond just creating sockets.
#LFE
LFE
  $ ./bin/lfe Erlang/OTP 17 [erts-6.2] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false]   LFE Shell V6.2 (abort with ^G) >  
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.
#Factor
Factor
USING: dns io kernel sequences ;   "www.kame.net" [ dns-A-query ] [ dns-AAAA-query ] bi [ message>names second print ] bi@
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.
#Frink
Frink
for a = callJava["java.net.InetAddress", "getAllByName", "www.kame.net"] println[a.getHostAddress[]]
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.
#Go
Go
package main   import ( "fmt" "net" )   func main() { if addrs, err := net.LookupHost("www.kame.net"); err == nil { fmt.Println(addrs) } else { fmt.Println(err) } }
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.
#Perl
Perl
use SVG; use List::Util qw(max min);   use constant pi => 2 * atan2(1, 0);   # Compute the curve with a Lindemayer-system my %rules = ( X => 'X+YF+', Y => '-FX-Y' ); my $dragon = 'FX'; $dragon =~ s/([XY])/$rules{$1}/eg for 1..10;   # Draw the curve in SVG ($x, $y) = (0, 0); $theta = 0; $r = 6;   for (split //, $dragon) { if (/F/) { push @X, sprintf "%.0f", $x; push @Y, sprintf "%.0f", $y; $x += $r * cos($theta); $y += $r * sin($theta); } elsif (/\+/) { $theta += pi/2; } elsif (/\-/) { $theta -= pi/2; } }   $xrng = max(@X) - min(@X); $yrng = max(@Y) - min(@Y); $xt = -min(@X)+10; $yt = -min(@Y)+10; $svg = SVG->new(width=>$xrng+20, height=>$yrng+20); $points = $svg->get_path(x=>\@X, y=>\@Y, -type=>'polyline'); $svg->rect(width=>"100%", height=>"100%", style=>{'fill'=>'black'}); $svg->polyline(%$points, style=>{'stroke'=>'orange', 'stroke-width'=>1}, transform=>"translate($xt,$yt)");   open $fh, '>', 'dragon_curve.svg'; print $fh $svg->xmlify(-namespace=>'svg'); close $fh;
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
#Groovy
Groovy
class LinearCombination { private static String linearCombo(int[] c) { StringBuilder sb = new StringBuilder() for (int i = 0; i < c.length; ++i) { if (c[i] == 0) continue String op if (c[i] < 0 && sb.length() == 0) { op = "-" } else if (c[i] < 0) { op = " - " } else if (c[i] > 0 && sb.length() == 0) { op = "" } else { op = " + " } int av = Math.abs(c[i]) String coeff = av == 1 ? "" : "" + av + "*" sb.append(op).append(coeff).append("e(").append(i + 1).append(')') } if (sb.length() == 0) { return "0" } return sb.toString() }   static void main(String[] args) { int[][] combos = [ [1, 2, 3], [0, 1, 2, 3], [1, 0, 3, 4], [1, 2, 0], [0, 0, 0], [0], [1, 1, 1], [-1, -1, -1], [-1, -2, 0, -3], [-1] ]   for (int[] c : combos) { printf("%-15s ->  %s\n", Arrays.toString(c), linearCombo(c)) } } }
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Isabelle
Isabelle
theory Text imports Main begin   chapter ‹Presenting Theories›   text ‹This text will appear in the proof document.›   section ‹Some Examples.›   ― ‹A marginal comment. The expression \<^term>‹True› holds.›   lemma True_is_True: "True" ..   text ‹ The overall content of an Isabelle/Isar theory may alternate between formal and informal text. ›   text_raw ‹Can also contain raw latex.›   text ‹This text will only compile if the fact @{thm True_is_True} holds.›   text ‹This text will only compile if the constant \<^const>‹True› is defined.›   end
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#J
J
NB. ========================================================= NB.*apply v apply verb x to y apply=: 128!:2   NB. ========================================================= NB.*def c : (explicit definition) def=: :   NB.*define a : 0 (explicit definition script form) define=: : 0   NB.*do v name for ". do=: ".   NB.*drop v name for }. drop=: }.   Note 1 Note accepts multi-line descriptions. Definitions display the source. )   usleep 3 : '''libc.so.6 usleep > i i''&(15!:0) >.y'  
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Java
Java
/** * This is a class documentation comment. This text shows at the top of the page for this class * @author Joe Schmoe */ public class Doc{ /** * This is a field comment for a variable */ private String field;   /** * This is a method comment. It has parameter tags (param), an exception tag (throws), * and a return value tag (return). * * @param num a number with the variable name "num" * @throws BadException when something bad happens * @return another number */ public int method(long num) throws BadException{ //...code here } }
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).
#Java
Java
import java.util.Arrays;   public class DiversityPredictionTheorem { private static double square(double d) { return d * d; }   private static double averageSquareDiff(double d, double[] predictions) { return Arrays.stream(predictions) .map(it -> square(it - d)) .average() .orElseThrow(); }   private static String diversityTheorem(double truth, double[] predictions) { double average = Arrays.stream(predictions) .average() .orElseThrow(); return String.format("average-error : %6.3f%n", averageSquareDiff(truth, predictions)) + String.format("crowd-error  : %6.3f%n", square(truth - average)) + String.format("diversity  : %6.3f%n", averageSquareDiff(average, predictions)); }   public static void main(String[] args) { System.out.println(diversityTheorem(49.0, new double[]{48.0, 47.0, 51.0})); System.out.println(diversityTheorem(49.0, new double[]{48.0, 47.0, 51.0, 42.0})); } }
http://rosettacode.org/wiki/Draw_a_sphere
Draw a sphere
Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a Deathstar
#Swift
Swift
  class Sphere: UIView{   override func drawRect(rect: CGRect) { let context = UIGraphicsGetCurrentContext() let locations: [CGFloat] = [0.0, 1.0]   let colors = [UIColor.whiteColor().CGColor, UIColor.blueColor().CGColor]   let colorspace = CGColorSpaceCreateDeviceRGB()   let gradient = CGGradientCreateWithColors(colorspace, colors, locations)   var startPoint = CGPoint() var endPoint = CGPoint() startPoint.x = self.center.x - (self.frame.width * 0.1) startPoint.y = self.center.y - (self.frame.width * 0.15) endPoint.x = self.center.x endPoint.y = self.center.y let startRadius: CGFloat = 0 let endRadius: CGFloat = self.frame.width * 0.38   CGContextDrawRadialGradient (context, gradient, startPoint, startRadius, endPoint, endRadius, 0) } }   var s = Sphere(frame: CGRectMake(0, 0, 200, 200))  
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
#ALGOL_68
ALGOL 68
# -*- coding: utf-8 -*- # COMMENT REQUIRES: MODE VALUE = ~; # For example: # MODE VALUE = UNION(INT, REAL, COMPL) END COMMENT   MODE LINKNEW = STRUCT ( LINK next, prev, VALUE value );   MODE LINK = REF LINKNEW;   SKIP
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.
#Nim
Nim
import strutils   const Outline = """Display an outline as a nested table. Parse the outline to a tree, measuring the indent of each line, translating the indentation to a nested structure, and padding the tree to even depth. count the leaves descending from each node, defining the width of a leaf as 1, and the width of a parent node as a sum. (The sum of the widths of its children) and write out a table with 'colspan' values either as a wiki table, or as HTML."""   type Color {.pure.} = enum NoColor Yellow = "#ffffe6;" Orange = "#ffebd2;" Green = "#f0fff0;" Blue = "#e6ffff;"   const Line1Color = Yellow const Line2Colors = [Orange, Green, Blue]   type Node = ref object value: string level: Natural width: Natural color: Color parent: Node children: seq[Node]   #---------------------------------------------------------------------------------------------------   proc leadingSpaces(line: string): int = ## return the number of leading spaces. while line[result] == ' ': inc result   #---------------------------------------------------------------------------------------------------   proc buildTree(outline: string): tuple[root: Node, depth: Natural] = ## Build the tree for the given outline.   result.root = Node() var level: int var startPos = @[-1] var nodes: seq[Node] = @[result.root] var linecount = 0   for line in Outline.splitLines: inc linecount if line.len == 0: continue let start = line.leadingSpaces() level = startPos.find(start)   if level < 0: # Level not yet encountered. if start < startPos[^1]: raise newException(ValueError, "wrong indentation at line " & $linecount) startPos.add(start) nodes.add(nil) level = startPos.high   # Create the node. let node = Node(value: line.strip(), level: level) let parent = nodes[level - 1] parent.children.add(node) node.parent = parent nodes[level] = node # Set the node as current node for this level.   result.depth = nodes.high   #---------------------------------------------------------------------------------------------------   proc padTree(node: Node; depth: Natural) = ## pad the tree with empty nodes to get an even depth. if node.level == depth: return if node.children.len == 0: # Add an empty node. node.children.add(Node(level: node.level + 1, parent: node)) for child in node.children: child.padTree(depth)   #---------------------------------------------------------------------------------------------------   proc computeWidths(node: Node) = ## Compute the widths. var width = 0 if node.children.len == 0: width = 1 else: for child in node.children: child.computeWidths() inc width, child.width node.width = width   #---------------------------------------------------------------------------------------------------   proc build(nodelists: var seq[seq[Node]]; node: Node) = ## Build the list of nodes per level. nodelists[node.level].add(node) for child in node.children: nodelists.build(child)   #---------------------------------------------------------------------------------------------------   proc setColors(nodelists: seq[seq[Node]]) = ## Set the colors of the nodes. for node in nodelists[1]: node.color = Line1Color for i, node in nodelists[2]: node.color = Line2Colors[i mod Line2Colors.len] for level in 3..nodelists.high: for node in nodelists[level]: node.color = if node.value.len != 0: node.parent.color else: NoColor   #---------------------------------------------------------------------------------------------------   proc writeWikiTable(nodelists: seq[seq[Node]]) = ## Output the wikitable. echo "{| class='wikitable' style='text-align: center;'" for level in 1..nodelists.high: echo "|-" for node in nodelists[level]: if node.width > 1: # Node with children. echo "| style='background: $1 ' colspan=$2 | $3".format(node.color, node.width, node.value) elif node.value.len > 0: # Leaf with contents. echo "| style='background: $1 ' | $2".format(node.color, node.value) else: # Empty cell. echo "| | " echo "|}"   #---------------------------------------------------------------------------------------------------   proc writeHtml(nodelists: seq[seq[Node]]) = ## Output the HTML. echo "<table class='wikitable' style='text-align: center;'>" for level in 1..nodelists.high: echo " <tr>" for node in nodelists[level]: if node.width > 1: # Node with children. echo " <td colspan='$1' style='background-color: $2'>$3</td>".format(node.width, node.color, node.value) elif node.value.len > 0: # Leaf with contents. echo " <td style='background-color: $1'>$2</td>".format(node.color, node.value) else: # Empty cell. echo " <td></td>" echo " </tr>" echo "</table>"   #———————————————————————————————————————————————————————————————————————————————————————————————————   let (root, depth) = Outline.buildTree() root.padTree(depth) root.computeWidths() var nodelists = newSeq[seq[Node]](depth + 1) nodelists.build(root) nodelists.setColors() echo "WikiTable:" nodelists.writeWikiTable() echo "HTML:" nodelists.writeHtml()
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.
#Perl
Perl
#!/usr/bin/perl   use strict; use warnings;   my @rows; my $row = -1; my $width = 0; my $color = 0; our $bg = 'e0ffe0';   parseoutline( do { local $/; <DATA> =~ s/\t/ /gr } );   print "<table border=1 cellspacing=0>\n"; for ( @rows ) { my $start = 0; print " <tr>\n"; for ( @$_ ) # columns { my ($data, $col, $span, $bg) = @$_; print " <td></td>\n" x ( $col - $start ), " <td colspan=$span align=center bgcolor=#$bg> $data </td>\n"; $start = $col + $span; } print " <td></td>\n" x ( $width - $start ), " </tr>\n"; } print "</table>\n";   sub parseoutline { ++$row; while( $_[0] =~ /^( *)(.*)\n((?:\1 .*\n)*)/gm ) { my ($head, $body, $col) = ($2, $3, $width); $row == 1 and local $bg = qw( ffffe0 ffe0e0 )[ $color ^= 1]; if( length $body ) { parseoutline( $body ) } else { ++$width } push @{ $rows[$row] }, [ $head, $col, $width - $col, $bg ]; } --$row; }   __DATA__ 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.
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
#SVG
SVG
<svg viewBox="0 0 100 100" width="480px" height="480px" xmlns="http://www.w3.org/2000/svg"> <circle cx="50" cy="50" r="48" style="fill:peru; stroke:black; stroke-width:2" /> <g transform="translate(50,50) rotate(0)" style="fill:none; stroke-linecap:round"> <line y2="-36" style="stroke:black; stroke-width:5"> <animateTransform attributeName="transform" type="rotate" by="30" dur="3600s" accumulate="sum" repeatCount="indefinite"/> </line> <line y2="-42" style="stroke:white; stroke-width:2"> <animateTransform attributeName="transform" type="rotate" by="6" dur="60s" accumulate="sum" repeatCount="indefinite"/> </line> <line y2="-46" style="stroke:red; stroke-width:1"> <animateTransform attributeName="transform" type="rotate" calcMode="discrete" by="6" dur="1s" accumulate="sum" repeatCount="indefinite"/> </line> </g> <circle cx="50" cy="50" r="4" style="fill:gold; stroke:black; stroke-width:1" /> </svg>  
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.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
LaunchKernels[2]; ParallelEvaluate[RandomReal[]]  
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.
#Nim
Nim
import os, nanomsg   proc sendMsg(s: cint, msg: string) = echo "SENDING \"",msg,"\"" let bytes = s.send(msg.cstring, msg.len + 1, 0) assert bytes == msg.len + 1   proc recvMsg(s: cint) = var buf: cstring let bytes = s.recv(addr buf, MSG, 0) if bytes > 0: echo "RECEIVED \"",buf,"\"" discard freemsg buf   proc sendRecv(s: cint, msg: string) = var to: cint = 100 discard s.setSockOpt(SOL_SOCKET, RCVTIMEO, addr to, sizeof to) while true: s.recvMsg sleep 1000 s.sendMsg msg   proc node0(url: string) = var s = socket(AF_SP, nanomsg.PAIR) assert s >= 0 let res = s.bindd url assert res >= 0 s.sendRecv "node0" discard s.shutdown 0   proc node1(url: string) = var s = socket(AF_SP, nanomsg.PAIR) assert s >= 0 let res = s.connect url assert res >= 0 s.sendRecv "node1" discard s.shutdown 0   if paramStr(1) == "node0": node0 paramStr(2) elif paramStr(1) == "node1": node1 paramStr(2)
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.
#Groovy
Groovy
def addresses = InetAddress.getAllByName('www.kame.net') println "IPv4: ${addresses.find { it instanceof Inet4Address }?.hostAddress}" println "IPv6: ${addresses.find { it instanceof Inet6Address }?.hostAddress}"
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.
#Haskell
Haskell
module Main where   import Network.Socket   getWebAddresses :: HostName -> IO [SockAddr] getWebAddresses host = do results <- getAddrInfo (Just defaultHints) (Just host) (Just "http") return [ addrAddress a | a <- results, addrSocketType a == Stream ]   showIPs :: HostName -> IO () showIPs host = do putStrLn $ "IP addresses for " ++ host ++ ":" addresses <- getWebAddresses host mapM_ (putStrLn . (" "++) . show) addresses   main = showIPs "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.
#Phix
Phix
-- -- demo\rosetta\DragonCurve.exw -- ============================ -- with javascript_semantics include pGUI.e Ihandle dlg, canvas cdCanvas cddbuffer, cdcanvas integer colour = 0 procedure Dragon(integer depth, atom x1, y1, x2, y2) depth -= 1 if depth<=0 then cdCanvasSetForeground(cddbuffer, colour) cdCanvasLine(cddbuffer, x1, y1, x2, y2) -- (some interesting colour patterns emerge) colour += 2 -- colour += 2000 -- colour += #100 else atom dx = x2-x1, dy = y2-y1, nx = x1+(dx-dy)/2, ny = y1+(dx+dy)/2 Dragon(depth,x1,y1,nx,ny) Dragon(depth,x2,y2,nx,ny) end if end procedure function redraw_cb(Ihandle /*ih*/, integer /*posx*/, /*posy*/) cdCanvasActivate(cddbuffer) cdCanvasClear(cddbuffer) -- (note: depths over 21 take a long time to draw, -- depths <= 16 look a little washed out) Dragon(17,100,100,100+256,100) cdCanvasFlush(cddbuffer) return IUP_DEFAULT end function function map_cb(Ihandle ih) cdcanvas = cdCreateCanvas(CD_IUP, ih) cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas) cdCanvasSetBackground(cddbuffer, CD_PARCHMENT) return IUP_DEFAULT end function procedure main() IupOpen() canvas = IupCanvas(NULL) IupSetAttribute(canvas, "RASTERSIZE", "420x290") IupSetCallback(canvas, "MAP_CB", Icallback("map_cb")) IupSetCallback(canvas, "ACTION", Icallback("redraw_cb")) dlg = IupDialog(canvas,"RESIZE=NO") IupSetAttribute(dlg, "TITLE", "Dragon Curve") IupShow(dlg) if platform()!=JS then IupMainLoop() IupClose() end if end procedure main()
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
#Haskell
Haskell
import Text.Printf (printf)   linearForm :: [Int] -> String linearForm = strip . concat . zipWith term [1..] where term :: Int -> Int -> String term i c = case c of 0 -> mempty 1 -> printf "+e(%d)" i -1 -> printf "-e(%d)" i c -> printf "%+d*e(%d)" c i   strip str = case str of '+':s -> s "" -> "0" s -> s
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Julia
Julia
  "Tell whether there are too foo items in the array." foo(xs::Array) = ...  
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Kotlin
Kotlin
/** * A group of *members*. * @author A Programmer. * @since version 1.1.51. * * This class has no useful logic; it's just a documentation example. * * @param T the type of a member in this group. * @property name the name of this group. * @constructor Creates an empty group. */ class Group<T>(val name: String) { /** * Adds a [member] to this group. * @throws AddException if the member can't be added. * @return the new size of the group. */ fun add(member: T): Int { ... } }
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Lambdatalk
Lambdatalk
  '{def add // define the name {lambda {:a :b} // for a function with two arguments {+ :a :b} // whose body calls the + primitive on them } // end function } // end define -> add   '{add 3 4} // call the function on two values -> 7 // the result  
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).
#JavaScript
JavaScript
'use strict';   function sum(array) { return array.reduce(function (a, b) { return a + b; }); }   function square(x) { return x * x; }   function mean(array) { return sum(array) / array.length; }   function averageSquareDiff(a, predictions) { return mean(predictions.map(function (x) { return square(x - a); })); }   function diversityTheorem(truth, predictions) { var average = mean(predictions); return { 'average-error': averageSquareDiff(truth, predictions), 'crowd-error': square(truth - average), 'diversity': averageSquareDiff(average, predictions) }; }   console.log(diversityTheorem(49, [48,47,51])) console.log(diversityTheorem(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
#Tcl
Tcl
proc grey {n} {format "#%2.2x%2.2x%2.2x" $n $n $n}   pack [canvas .c -height 400 -width 640 -background white]   for {set i 0} {$i < 255} {incr i} { set h [grey $i] .c create arc [expr {100+$i/5}] [expr {50+$i/5}] [expr {400-$i/1.5}] [expr {350-$i/1.5}] \ -start 0 -extent 359 -fill $h -outline $h }
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
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program defDblList.s */   /* Constantes */ .equ STDOUT, 1 @ Linux output console .equ EXIT, 1 @ Linux syscall .equ READ, 3 .equ WRITE, 4     /*******************************************/ /* Structures */ /********************************************/ /* structure Doublylinkedlist*/ .struct 0 dllist_head: @ head node .struct dllist_head + 4 dllist_tail: @ tail node .struct dllist_tail + 4 dllist_fin: /* structure Node Doublylinked List*/ .struct 0 NDlist_next: @ next element .struct NDlist_next + 4 NDlist_prev: @ previous element .struct NDlist_prev + 4 NDlist_value: @ element value or key .struct NDlist_value + 4 NDlist_fin: /* Initialized data */ .data szMessInitListe: .asciz "List initialized.\n" szCarriageReturn: .asciz "\n" szMessErreur: .asciz "Error detected.\n"   /* UnInitialized data */ .bss dllist1: .skip dllist_fin @ list memory place   /* code section */ .text .global main main: ldr r0,iAdrdllist1 bl newDList @ create new list ldr r0,iAdrszMessInitListe bl affichageMess ldr r0,iAdrdllist1 @ list address mov r1,#10 @ value bl insertHead @ insertion at head cmp r0,#-1 beq 99f ldr r0,iAdrdllist1 mov r1,#20 bl insertTail @ insertion at tail cmp r0,#-1 beq 99f ldr r0,iAdrdllist1 @ list address mov r1,#10 @ value to after insered mov r2,#15 @ new value bl insertAfter cmp r0,#-1 beq 99f   b 100f 99: ldr r0,iAdrszMessErreur bl affichageMess 100: @ standard end of the program mov r7, #EXIT @ request to exit program svc 0 @ perform system call iAdrszMessInitListe: .int szMessInitListe iAdrszMessErreur: .int szMessErreur iAdrszCarriageReturn: .int szCarriageReturn iAdrdllist1: .int dllist1 /******************************************************************/ /* create new list */ /******************************************************************/ /* r0 contains the address of the list structure */ newDList: push {r1,lr} @ save registers mov r1,#0 str r1,[r0,#dllist_tail] str r1,[r0,#dllist_head] pop {r1,lr} @ restaur registers bx lr @ return /******************************************************************/ /* list is empty ? */ /******************************************************************/ /* r0 contains the address of the list structure */ /* r0 return 0 if empty else return 1 */ isEmpty: //push {r1,lr} @ save registers ldr r0,[r0,#dllist_head] cmp r0,#0 movne r0,#1 //pop {r1,lr} @ restaur registers bx lr @ return /******************************************************************/ /* insert value at list head */ /******************************************************************/ /* r0 contains the address of the list structure */ /* r1 contains value */ insertHead: push {r1-r4,lr} @ save registers mov r4,r0 @ save address mov r0,r1 @ value bl createNode cmp r0,#-1 @ allocation error ? beq 100f ldr r2,[r4,#dllist_head] @ load address first node str r2,[r0,#NDlist_next] @ store in next pointer on new node mov r1,#0 str r1,[r0,#NDlist_prev] @ store zero in previous pointer on new node str r0,[r4,#dllist_head] @ store address new node in address head list cmp r2,#0 @ address first node is null ? strne r0,[r2,#NDlist_prev] @ no store adresse new node in previous pointer streq r0,[r4,#dllist_tail] @ else store new node in tail address 100: pop {r1-r4,lr} @ restaur registers bx lr @ return /******************************************************************/ /* insert value at list tail */ /******************************************************************/ /* r0 contains the address of the list structure */ /* r1 contains value */ insertTail: push {r1-r4,lr} @ save registers mov r4,r0 @ save list address mov r0,r1 @ value bl createNode @ create new node cmp r0,#-1 beq 100f @ allocation error ldr r2,[r4,#dllist_tail] @ load address last node str r2,[r0,#NDlist_prev] @ store in previous pointer on new node mov r1,#0 @ store null un next pointer str r1,[r0,#NDlist_next] str r0,[r4,#dllist_tail] @ store address new node on list tail cmp r2,#0 @ address last node is null ? strne r0,[r2,#NDlist_next] @ no store address new node in next pointer streq r0,[r4,#dllist_head] @ else store in head list 100: pop {r1-r4,lr} @ restaur registers bx lr @ return /******************************************************************/ /* insert value after other element */ /******************************************************************/ /* r0 contains the address of the list structure */ /* r1 contains value to search*/ /* r2 contains value to insert */ insertAfter: push {r1-r5,lr} @ save registers mov r4,r0 @ save list address bl searchValue @ search this value in r1 cmp r0,#-1 beq 100f @ not found -> error mov r5,r0 @ save address of node find mov r0,r2 @ new value bl createNode @ create new node cmp r0,#-1 beq 100f @ allocation error ldr r2,[r5,#NDlist_next] @ load pointer next of find node str r0,[r5,#NDlist_next] @ store new node in pointer next str r5,[r0,#NDlist_prev] @ store address find node in previous pointer on new node str r2,[r0,#NDlist_next] @ store pointer next of find node on pointer next on new node cmp r2,#0 @ next pointer is null ? strne r0,[r2,#NDlist_prev] @ no store address new node in previous pointer streq r0,[r4,#dllist_tail] @ else store in list tail 100: pop {r1-r5,lr} @ restaur registers bx lr @ return /******************************************************************/ /* search value */ /******************************************************************/ /* r0 contains the address of the list structure */ /* r1 contains the value to search */ /* r0 return address of node or -1 if not found */ searchValue: push {r2,lr} @ save registers ldr r0,[r0,#dllist_head] @ load first node 1: cmp r0,#0 @ null -> end search not found moveq r0,#-1 beq 100f ldr r2,[r0,#NDlist_value] @ load node value cmp r2,r1 @ equal ? beq 100f ldr r0,[r0,#NDlist_next] @ load addresse next node b 1b @ and loop 100: pop {r2,lr} @ restaur registers bx lr @ return /******************************************************************/ /* Create new node */ /******************************************************************/ /* r0 contains the value */ /* r0 return node address or -1 if allocation error*/ createNode: push {r1-r7,lr} @ save registers mov r4,r0 @ save value @ allocation place on the heap mov r0,#0 @ allocation place heap mov r7,#0x2D @ call system 'brk' svc #0 mov r5,r0 @ save address heap for output string add r0,#NDlist_fin @ reservation place one element mov r7,#0x2D @ call system 'brk' svc #0 cmp r0,#-1 @ allocation error beq 100f mov r0,r5 str r4,[r0,#NDlist_value] @ store value mov r2,#0 str r2,[r0,#NDlist_next] @ store zero to pointer next str r2,[r0,#NDlist_prev] @ store zero to pointer previous 100: pop {r1-r7,lr} @ restaur registers bx lr @ return /******************************************************************/ /* display text with size calculation */ /******************************************************************/ /* r0 contains the address of the message */ affichageMess: push {r0,r1,r2,r7,lr} @ save registers mov r2,#0 @ counter length */ 1: @ loop length calculation ldrb r1,[r0,r2] @ read octet start position + index cmp r1,#0 @ if 0 its over addne r2,r2,#1 @ else add 1 in the length bne 1b @ and loop @ so here r2 contains the length of the message mov r1,r0 @ address message in r1 mov r0,#STDOUT @ code to write to the standard output Linux mov r7, #WRITE @ code call system "write" svc #0 @ call system pop {r0,r1,r2,r7,lr} @ restaur registers bx lr @ return    
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.
#Phix
Phix
with javascript_semantics constant html = false, outlines = {""" 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.""", """ 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."""} constant yellow = "#ffffe6;", orange = "#ffebd2;", green = "#f0fff0;", blue = "#e6ffff;", pink = "#ffeeff;", colours = {{yellow, orange, green, blue, pink}, {blue, yellow, orange, green, pink}} function calc_spans(sequence lines, integer ldx) sequence children = lines[ldx][$] if length(children)!=0 then integer span = 0 for i=1 to length(children) do integer child = children[i] lines = calc_spans(lines,child) span += lines[child][4] end for lines[ldx][4] = span -- else -- (span already 1) end if return lines end function procedure markup(string outline, sequence colours) sequence lines = split(outline,"\n",no_empty:=true), pi = {}, -- indents (to locate parents) pdx = {}, -- indexes for "" children = {} string text integer maxdepth = 0, parent, depth, span for i=1 to length(lines) do string line = trim_tail(lines[i]) text = trim_head(line) integer indent = length(line)-length(text) -- remove any completed parents while length(pi) and indent<=pi[$] do pi = pi[1..$-1] pdx = pdx[1..$-1] end while parent = 0 if length(pi) then parent = pdx[$] lines[parent][$] = deep_copy(lines[parent][$]) & i -- (update children) end if pi &= indent pdx &= i depth = length(pi) span = 1 -- (default/assume no children[=={}]) lines[i] = {i,depth,indent,span,parent,text,children} maxdepth = max(maxdepth,depth) end for lines = calc_spans(lines,1) string res = iff(html?"<table class=\"wikitable\" style=\"text-align: center;\">\n" :"{| class=\"wikitable\" style=\"text-align: center;\"\n") for d=1 to maxdepth do res &= iff(html?"<tr>\n" :"|-\n") integer cdx = 1, lii, lident for i=1 to length(lines) do {lii,depth,lident,span,parent,text,children} = lines[i] if depth=2 then cdx += 1 end if string style = sprintf(`style="background: %s"`,{colours[cdx]}) if depth=d then if span!=1 then style &= sprintf(` colspan="%d"`,span) end if res &= sprintf(iff(html?"<td %s>%s</td>\n" :"| %s | %s\n"),{style,text}) elsif depth<d and children={} then -- res &= iff(html?"<td></td>\n" --  :"| |\n") res &= sprintf(iff(html?"<td %s></td>\n" :"| %s |\n"),{style}) end if end for if html then res &= "</tr>\n" end if end for res &= iff(html?"</table>\n" :"|}\n") puts(1,res) end procedure for i=1 to length(outlines) do markup(outlines[i],colours[i]) end for
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
#Tcl
Tcl
package require Tcl 8.5 package require Tk   # GUI code pack [canvas .c -width 200 -height 200] .c create oval 20 20 180 180 -width 10 -fill {} -outline grey70 .c create line 0 0 1 1 -tags hour -width 6 -cap round -fill black .c create line 0 0 1 1 -tags minute -width 4 -cap round -fill black .c create line 0 0 1 1 -tags second -width 2 -cap round -fill grey30 proc updateClock t { scan [clock format $t -format "%H %M %S"] "%d%d%d" h m s # On an analog clock, the hour and minute hands move gradually set m [expr {$m + $s/60.0}] set h [expr {($h % 12 + $m/60.0) * 5}] foreach tag {hour minute second} value [list $h $m $s] len {50 80 80} { .c coords $tag 100 100 \ [expr {100 + $len*sin($value/30.0*3.14159)}] \ [expr {100 - $len*cos($value/30.0*3.14159)}] } }   # Timer code, accurate to within a quarter second set time 0 proc ticker {} { global time set t [clock seconds] after 250 ticker if {$t != $time} { set time $t updateClock $t } } ticker
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.
#Objective-C
Objective-C
#import <Foundation/Foundation.h> // our protocol allows "sending" "strings", but we can implement // everything we could for a "local" object @protocol ActionObjectProtocol - (NSString *)sendMessage: (NSString *)msg; @end
http://rosettacode.org/wiki/Distributed_programming
Distributed programming
Write two programs (or one program with two modes) which run on networked computers, and send some messages between them. The protocol used may be language-specific or not, and should be suitable for general distributed programming; that is, the protocol should be generic (not designed just for the particular example application), readily capable of handling the independent communications of many different components of a single application, and the transferring of arbitrary data structures natural for the language. This task is intended to demonstrate high-level communication facilities beyond just creating sockets.
#OCaml
OCaml
open Printf   let create_logger () = def log(text) & logs(l) = printf "Logged: %s\n%!" text; logs((text, Unix.gettimeofday ())::l) & reply to log   or search(text) & logs(l) = logs(l) & reply List.filter (fun (line, _) -> line = text) l to search in spawn logs([]); (log, search)   def wait() & finished() = reply to wait   let register name service = Join.Ns.register Join.Ns.here name service   let () = let log, search = create_logger () in register "log" log; register "search" search; Join.Site.listen (Unix.ADDR_INET (Join.Site.get_local_addr(), 12345)); wait ()
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.
#Icon_and_Unicon
Icon and Unicon
  procedure main(A) host := gethost( A[1] | "www.kame.net") | stop("can't translate") write(host.name, ": ", host.addresses) 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.
#J
J
2!:0'dig -4 +short www.kame.net' orange.kame.net. 203.178.141.194   2!:0'dig -6 +short www.kame.net' |interface error | 2!:0'dig -6 +short 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.
#PicoLisp
PicoLisp
# Need some turtle graphics (load "@lib/math.l")   (setq *TurtleX 100 # X position *TurtleY 75 # Y position *TurtleA 0.0 ) # Angle   (de fd (Img Len) # Forward (let (R (*/ *TurtleA pi 180.0) DX (*/ (cos R) Len 1.0) DY (*/ (sin R) Len 1.0)) (brez Img *TurtleX *TurtleY DX DY) (inc '*TurtleX DX) (inc '*TurtleY DY) ) )   (de rt (A) # Right turn (inc '*TurtleA A) )   (de lt (A) # Left turn (dec '*TurtleA A) )     # Dragon curve stuff (de *DragonStep . 4)   (de dragon (Img Depth Dir) (if (=0 Depth) (fd Img *DragonStep) (rt Dir) (dragon Img (dec Depth) 45.0) (lt (* 2 Dir)) (dragon Img (dec Depth) -45.0) (rt Dir) ) )   # Run it (let Img (make (do 200 (link (need 300 0)))) # Create image 300 x 200 (dragon Img 10 45.0) # Build dragon curve (out "img.pbm" # Write to bitmap file (prinl "P1") (prinl 300 " " 200) (mapc prinl Img) ) )
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
#J
J
fourbanger=:3 :0 e=. ('e(',')',~])@":&.> 1+i.#y firstpos=. 0< {.y-.0 if. */0=y do. '0' else. firstpos}.;y gluedto e end. )   gluedto=:4 :0 each pfx=. '+-' {~ x<0 select. |x case. 0 do. '' case. 1 do. pfx,y case. do. pfx,(":|x),'*',y end. )
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Logtalk
Logtalk
  :- object(set(_Type), extends(set)).   % the info/1 directive is the main directive for documenting an entity % its value is a list of Key-Value pairs; the set of keys is user-extendable :- info([ version is 1.2, author is 'A. Coder', date is 2013/10/13, comment is 'Set predicates with elements constrained to a single type.', parnames is ['Type'] ]).   % the info/2 directive is the main directive for documenting predicates % its second value is a list of Key-Value pairs; the set of keys is user-extendable :- public(intersection/3). :- mode(intersection(+set, +set, ?set), zero_or_one). :- info(intersection/3, [ comment is 'Returns the intersection of Set1 and Set2.', argnames is ['Set1', 'Set2', 'Intersection'] ]).   ...   :- end_object.  
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Lua
Lua
--- Converts degrees to radians (summary). -- Given an angle measure in degrees, return an equivalent angle measure in radians (long description). -- @param deg the angle measure in degrees -- @return the angle measure in radians -- @see rad2deg function deg2rad(deg) return deg*math.pi/180 end
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).
#Jsish
Jsish
/* Diverisity Prediction Theorem, in Jsish */ "use strict";   function sum(arr:array):number { return arr.reduce(function(acc, cur, idx, arr) { return acc + cur; }); }   function square(x:number):number { return x * x; }   function mean(arr:array):number { return sum(arr) / arr.length; }   function averageSquareDiff(a:number, predictions:array):number { return mean(predictions.map(function(x:number):number { return square(x - a); })); }   function diversityTheorem(truth:number, predictions:array):object { var average = mean(predictions); return { "average-error": averageSquareDiff(truth, predictions), "crowd-error": square(truth - average), "diversity": averageSquareDiff(average, predictions) }; }   ;diversityTheorem(49, [48,47,51]); ;diversityTheorem(49, [48,47,51,42]);   /* =!EXPECTSTART!= diversityTheorem(49, [48,47,51]) ==> { "average-error":3, "crowd-error":0.1111111111111127, diversity:2.888888888888889 } diversityTheorem(49, [48,47,51,42]) ==> { "average-error":14.5, "crowd-error":4, diversity:10.5 } =!EXPECTEND!= */
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
#LaTeX
LaTeX
\documentclass{minimal} \usepackage{tikz} \usetikzlibrary{shadings} \begin{document} \begin{tikzpicture} \shade[ball color=black] (0,0) circle (4); \end{tikzpicture} \end{document}
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
#ATS
ATS
(********************************************************************) (* The public interface *)   abstype dllist_t (t : t@ype+, is_root : bool) (* An abstract type. *) typedef dllist_t (t : t@ype+) = [b : bool] dllist_t (t, b)   (* Make a new dllist_t, consisting of a root node. *) fun {t : t@ype} dllist_t_make () : dllist_t (t, true)   (* Is this the root node, with no element stored? *) fun {t : t@ype} dllist_t_is_root {is_root : bool} (dl : dllist_t (t, is_root)) : [b : bool | b == is_root] bool b   (* Is this a non-root node, with an element stored? *) fun {t : t@ype} dllist_t_isnot_root {is_root : bool} (dl : dllist_t (t, is_root)) : [b : bool | b == ~is_root] bool b   (* Return the root node of the list. *) fun {t : t@ype} dllist_t_root (dl : dllist_t t) : dllist_t (t, true)   (* Return the previous node. *) fun {t : t@ype} dllist_t_previous (dl : dllist_t t) : dllist_t t   (* Return the next node. *) fun {t : t@ype} dllist_t_next (dl : dllist_t t) : dllist_t t   (* Insert an element before the given node. *) fun {t : t@ype} dllist_t_insert_before (dl : dllist_t t, elem : t) : void   (* Insert an element after the given node. *) fun {t : t@ype} dllist_t_insert_after (dl : dllist_t t, elem : t) : void   (* Remove the given node. It is an error to call this on the root node. *) fun {t : t@ype} dllist_t_remove (dl : dllist_t t) : void   (* Return a copy of the stored element. It is an error to call this on the root node. *) fun {t : t@ype} dllist_t_element (dl: dllist_t t) : t   fun {t : t@ype} dllist_t_make_generator (dl: dllist_t t, direction : int) : () -<cloref1> Option t   fun {t : t@ype} dllist_t_to_list (dl : dllist_t t) : [n : nat] list (t, n)   fun {t : t@ype} list_to_dllist_t {n : int} (dl : list (t, n)) : dllist_t t   (********************************************************************)
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.
#Python
Python
"""Display an outline as a nested table. Requires Python >=3.6."""   import itertools import re import sys   from collections import deque from typing import NamedTuple     RE_OUTLINE = re.compile(r"^((?: |\t)*)(.+)$", re.M)   COLORS = itertools.cycle( [ "#ffffe6", "#ffebd2", "#f0fff0", "#e6ffff", "#ffeeff", ] )     class Node: def __init__(self, indent, value, parent, children=None): self.indent = indent self.value = value self.parent = parent self.children = children or []   self.color = None   def depth(self): if self.parent: return self.parent.depth() + 1 return -1   def height(self): """Height of the subtree rooted at this node.""" if not self.children: return 0 return max(child.height() for child in self.children) + 1   def colspan(self): if self.leaf: return 1 return sum(child.colspan() for child in self.children)   @property def leaf(self): return not bool(self.children)   def __iter__(self): # Level order tree traversal. q = deque() q.append(self) while q: node = q.popleft() yield node q.extend(node.children)     class Token(NamedTuple): indent: int value: str     def tokenize(outline): """Generate ``Token``s from the given outline.""" for match in RE_OUTLINE.finditer(outline): indent, value = match.groups() yield Token(len(indent), value)     def parse(outline): """Return the given outline as a tree of ``Node``s.""" # Split the outline into lines and count the level of indentation. tokens = list(tokenize(outline))   # Parse the tokens into a tree of nodes. temp_root = Node(-1, "", None) _parse(tokens, 0, temp_root)   # Pad the tree so that all branches have the same depth. root = temp_root.children[0] pad_tree(root, root.height())   return root     def _parse(tokens, index, node): """Recursively build a tree of nodes.   Args: tokens (list): A collection of ``Token``s. index (int): Index of the current token. node (Node): Potential parent or sibling node. """ # Base case. No more lines. if index >= len(tokens): return   token = tokens[index]   if token.indent == node.indent: # A sibling of node current = Node(token.indent, token.value, node.parent) node.parent.children.append(current) _parse(tokens, index + 1, current)   elif token.indent > node.indent: # A child of node current = Node(token.indent, token.value, node) node.children.append(current) _parse(tokens, index + 1, current)   elif token.indent < node.indent: # Try the node's parent until we find a sibling. _parse(tokens, index, node.parent)     def pad_tree(node, height): """Pad the tree with blank nodes so all branches have the same depth.""" if node.leaf and node.depth() < height: pad_node = Node(node.indent + 1, "", node) node.children.append(pad_node)   for child in node.children: pad_tree(child, height)     def color_tree(node): """Walk the tree and color each node as we go.""" if not node.value: node.color = "#F9F9F9" elif node.depth() <= 1: node.color = next(COLORS) else: node.color = node.parent.color   for child in node.children: color_tree(child)     def table_data(node): """Return an HTML table data element for the given node.""" indent = " "   if node.colspan() > 1: colspan = f'colspan="{node.colspan()}"' else: colspan = ""   if node.color: style = f'style="background-color: {node.color};"' else: style = ""   attrs = " ".join([colspan, style]) return f"{indent}<td{attrs}>{node.value}</td>"     def html_table(tree): """Return the tree as an HTML table.""" # Number of columns in the table. table_cols = tree.colspan()   # Running count of columns in the current row. row_cols = 0   # HTML buffer buf = ["<table style='text-align: center;'>"]   # Breadth first iteration. for node in tree: if row_cols == 0: buf.append(" <tr>")   buf.append(table_data(node)) row_cols += node.colspan()   if row_cols == table_cols: buf.append(" </tr>") row_cols = 0   buf.append("</table>") return "\n".join(buf)     def wiki_table_data(node): """Return an wiki table data string for the given node.""" if not node.value: return "| |"   if node.colspan() > 1: colspan = f"colspan={node.colspan()}" else: colspan = ""   if node.color: style = f'style="background: {node.color};"' else: style = ""   attrs = " ".join([colspan, style]) return f"| {attrs} | {node.value}"     def wiki_table(tree): """Return the tree as a wiki table.""" # Number of columns in the table. table_cols = tree.colspan()   # Running count of columns in the current row. row_cols = 0   # HTML buffer buf = ['{| class="wikitable" style="text-align: center;"']   for node in tree: if row_cols == 0: buf.append("|-")   buf.append(wiki_table_data(node)) row_cols += node.colspan()   if row_cols == table_cols: row_cols = 0   buf.append("|}") return "\n".join(buf)     def example(table_format="wiki"): """Write an example table to stdout in either HTML or Wiki format."""   outline = ( "Display an outline as a nested table.\n" " Parse the outline to a tree,\n" " measuring the indent of each line,\n" " translating the indentation to a nested structure,\n" " and padding the tree to even depth.\n" " count the leaves descending from each node,\n" " defining the width of a leaf as 1,\n" " and the width of a parent node as a sum.\n" " (The sum of the widths of its children)\n" " and write out a table with 'colspan' values\n" " either as a wiki table,\n" " or as HTML." )   tree = parse(outline) color_tree(tree)   if table_format == "wiki": print(wiki_table(tree)) else: print(html_table(tree))     if __name__ == "__main__": args = sys.argv[1:]   if len(args) == 1: table_format = args[0] else: table_format = "wiki"   example(table_format)
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
#Wren
Wren
import "graphics" for Canvas, Color import "dome" for Window import "math" for Math   var Degrees06 = Num.pi / 30 var Degrees30 = Degrees06 * 5 var Degrees90 = Degrees30 * 3   class Clock { construct new(hour, minute, second) { Window.title = "Clock" _size = 590 Window.resize(_size, _size) Canvas.resize(_size, _size) _spacing = 40 _diameter = _size - 2 * _spacing _cx = (_diameter / 2).floor + _spacing _cy = _cx _hour = hour _minute = minute _second = second }   drawFace() { var radius = (_diameter / 2).floor Canvas.circlefill(_cx, _cy, radius, Color.yellow) Canvas.circle(_cx, _cy, radius, Color.black) }   drawHand(angle, radius, color) { var x = _cx + (radius * Math.cos(angle)).truncate var y = _cy - (radius * Math.sin(angle)).truncate Canvas.line(_cx, _cy, x, y, color, 2) }   drawClock() { Canvas.cls(Color.white) drawFace() var angle = Degrees90 - Degrees06 * _second drawHand(angle, (_diameter/2).floor - 30, Color.red) var minsecs = _minute + _second/60 angle = Degrees90 - Degrees06 * minsecs drawHand(angle, (_diameter / 3).floor + 10, Color.black) var hourmins = _hour + minsecs / 60 angle = Degrees90 - Degrees30 * hourmins drawHand(angle, (_diameter / 4).floor + 10, Color.black) }   init() { _frame = 0 drawClock() }   update() { _frame = _frame + 1 if (_frame == 60) { _frame = 0 _second = _second + 1 if (_second == 60) { _minute = _minute + 1 _second = 0 if (_minute == 60) { _hour = _hour + 1 _minute = 0 if (_hour == 24) _hour = 0 } } } }   draw(alpha) { drawClock() } }   var Game = Clock.new(0, 0, 0) // start at midnight
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.
#Oz
Oz
declare functor ServerCode export port:Prt define Stream Prt = {NewPort ?Stream} thread for Request#Reply in Stream do case Request of echo(Data) then Reply = Data [] compute(Function) then Reply = {Function} end end end end   %% create the server on some machine %% (just change "localhost" to some machine %% that you can use with a passwordless rsh login %% and that has the same Mozart version installed) RM = {New Remote.manager init(host:localhost)}   %% execute the code encapsulated in the ServerCode functor Server = {RM apply(ServerCode $)}   %% Shortcut: send a message to Server and receive a reply fun {Send X} {Port.sendRecv Server.port X} end in %% echo {System.showInfo "Echo reply: "#{Send echo(hello)}}   %% compute {System.showInfo "Result of computation: "# {Send compute(fun {$} 8 div 4 end)}}   %% shut down server {RM close}
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.
#Perl
Perl
use Data::Dumper; use IO::Socket::INET; use Safe;   sub get_data { my $sock = new IO::Socket::INET LocalHost => "localhost", LocalPort => "10000", Proto => "tcp", Listen => 1, Reuse => 1; unless ($sock) { die "Socket creation failure" } my $cli = $sock->accept();   # of course someone may be tempted to send you 'system("rm -rf /")', # to be safe(r), use Safe:: my $safe = new Safe; my $x = $safe->reval(join("", <$cli>)); close $cli; close $sock; return $x; }   sub send_data { my $host = shift; my $data = shift; my $sock = new IO::Socket::INET PeerAddr => "$host:10000", Proto => "tcp", Reuse => 1;   unless ($sock) { die "Socket creation failure" }   print $sock Data::Dumper->Dump([$data]); close $sock; }   if (@ARGV) { my $x = get_data(); print "Got data\n", Data::Dumper->Dump([$x]); } else { send_data('some_host', { a=>100, b=>[1 .. 10] }); }
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.
#Java
Java
import java.net.InetAddress; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.UnknownHostException;   class DnsQuery { public static void main(String[] args) { try { InetAddress[] ipAddr = InetAddress.getAllByName("www.kame.net"); for(int i=0; i < ipAddr.length ; i++) { if (ipAddr[i] instanceof Inet4Address) { System.out.println("IPv4 : " + ipAddr[i].getHostAddress()); } else if (ipAddr[i] instanceof Inet6Address) { System.out.println("IPv6 : " + ipAddr[i].getHostAddress()); } } } catch (UnknownHostException uhe) { System.err.println("unknown host"); } } }  
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.
#JavaScript
JavaScript
const dns = require("dns");   dns.lookup("www.kame.net", { all: true }, (err, addresses) => { if(err) return console.error(err); console.log(addresses); })  
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.
#PL.2FI
PL/I
  * PROCESS GONUMBER, MARGINS(1,72), NOINTERRUPT, MACRO; TEST:PROCEDURE OPTIONS(MAIN); DECLARE SYSIN FILE STREAM INPUT, DRAGON FILE STREAM OUTPUT PRINT, SYSPRINT FILE STREAM OUTPUT PRINT; DECLARE (MIN,MAX,MOD,INDEX,LENGTH,SUBSTR,VERIFY,TRANSLATE) BUILTIN; DECLARE (COMPLEX,SQRT,REAL,IMAG,ATAN,SIN,EXP,COS,ABS) BUILTIN;  %INCLUDE PLILIB(GOODIES);  %INCLUDE PLILIB(SCAN);  %INCLUDE PLILIB(GRAMMAR);  %INCLUDE PLILIB(CARDINAL);  %INCLUDE PLILIB(ORDINAL);  %INCLUDE PLILIB(ANSWAROD);  %INCLUDE PLILIB(RUNFILE);  %INCLUDE PLILIB(PSTUFF);   DECLARE (TWOPI,TORAD) REAL; DECLARE RANGE(4) REAL; DECLARE TRACERANGE BOOLEAN INITIAL(FALSE); DECLARE FRESHRANGE BOOLEAN INITIAL(TRUE);   BOUND:PROCEDURE(Z); DECLARE Z COMPLEX; DECLARE (ZX,ZY) REAL; ZX = REAL(Z); ZY = IMAG(Z); IF FRESHRANGE THEN DO; RANGE(1),RANGE(2) = ZX; RANGE(3),RANGE(4) = ZY; END; ELSE DO; RANGE(1) = MIN(RANGE(1),ZX); RANGE(2) = MAX(RANGE(2),ZX); RANGE(3) = MIN(RANGE(3),ZY); RANGE(4) = MAX(RANGE(4),ZY); END; FRESHRANGE = FALSE; END BOUND;   PLOTZ:PROCEDURE(Z,PEN); DECLARE Z COMPLEX; DECLARE PEN INTEGER; IF TRACERANGE THEN CALL BOUND(Z); CALL PLOT(REAL(Z),IMAG(Z),PEN); END PLOTZ;    %PAGE; DRAGONCURVE:PROCEDURE(ORDER,HOP); /*Folding paper in two...*/ /*Some statistics on runs with x = 56.25", y = 32.6" &(the calcomp plotter).*/ /*The actual size of the picture determines the number of steps &to each quarter-turn.*/ /* n turns x y secs dx dy &*/ /* 20 1,048,575 -2389:681 -682:1364 180+ 3070 2046 &*/ /* 19 524,287 -1365:681 -340:1364 119 2046 1704 &*/ /* 18 262,143 -341:681 -340:1194 71 1022 1554 &*/ /* 17 131,071 -171:681 -340:682 35 852 1022 &*/ DECLARE ORDER BIGINT; /*So how many folds.*/ DECLARE HOP BOOLEAN; DECLARE FOLD(0:31,0:32767) BOOLEAN; /*Oh for (0:1000000) or so..*/ DECLARE (TURN,N,IT,I,I1,I2,J1,J2,L,LL) BIGINT; DECLARE (XMIN,XMAX,YMIN,YMAX,XMID,YMID) REAL; DECLARE (IXMIN,IXMAX,IYMIN,IYMAX) BIGINT; DECLARE (S,H,TORAD) REAL; DECLARE (ZMID,Z,Z2,DZ,ZL) COMPLEX; DECLARE (FULLTURN,ABOUTTURN,QUARTERTURN) INTEGER; DECLARE (WAY,DIRECTION,ND,LD,LD1,LD2) INTEGER; DECLARE LEAF(0:3,0:360) COMPLEX; /*Corner turning.*/ DECLARE SWAPXY BOOLEAN; /*Try to align rectangles.*/ DECLARE (T1,T2) CHARACTER(200) VARYING; IF ¬PLOTCHOICE('') THEN RETURN; /*Ascertain the plot device.*/ N = 0; FOR TURN = 1 TO ORDER; IT = N + 1; I1 = IT/32768; I2 = MOD(IT,32768); FOLD(I1,I2) = TRUE; FOR I = 1 TO N; I1 = (IT + I)/32768; I2 = MOD(IT + I,32768); J1 = (IT - I)/32768; J2 = MOD(IT - I,32768); FOLD(I1,I2) = ¬FOLD(J1,J2); END; N = N*2 + 1; IF HOP & TURN < ORDER THEN GO TO XX; XMIN,XMAX,YMIN,YMAX = 0; Z = 0; /*Start at the origin.*/ DZ = 1; /*Step out unilaterally.*/ FOR I = 1 TO N; Z = Z + DZ; /*Take the step before the kink.*/ I1 = I/32768; I2 = MOD(I,32768); IF FOLD(I1,I2) THEN DZ = DZ*(0 + 1I); ELSE DZ = DZ*(0 - 1I); Z = Z + DZ; /*The step after the kink.*/ XMIN = MIN(XMIN,REAL(Z)); XMAX = MAX(XMAX,REAL(Z)); YMIN = MIN(YMIN,IMAG(Z)); YMAX = MAX(YMAX,IMAG(Z)); END; SWAPXY = ((XMAX - XMIN) >= (YMAX - YMIN)) /*Contemplate */ ¬= (PLOTSTUFF.XSIZE >= PLOTSTUFF.YSIZE); /* rectangularities.*/ IF SWAPXY THEN DO; H = XMIN; XMIN = YMIN; YMIN = -XMAX; XMAX = YMAX; YMAX = -H; END; IXMAX = XMAX; IYMAX = YMAX; IXMIN = XMIN; IYMIN = YMIN; XMID = (XMAX + XMIN)/2; YMID = (YMAX + YMIN)/2; ZMID = COMPLEX(XMID,YMID); XMAX = XMAX - XMID; YMAX = YMAX - YMID; XMIN = XMIN - XMID; YMIN = YMIN - YMID; T1 = 'Order ' || IFMT(TURN) || ' Dragoncurve, ' || SAYNUM(0,N,'turn') || '.'; IF SWAPXY THEN T2 = 'y range ' || IFMT(IYMIN) || ':' || IFMT(IYMAX) || ', x range ' || IFMT(IXMIN) || ':' || IFMT(IXMAX); ELSE T2 = 'x range ' || IFMT(IXMIN) || ':' || IFMT(IXMAX) || ', y range ' || IFMT(IYMIN) || ':' || IFMT(IYMAX); S = MIN(PLOTSTUFF.XSIZE/(XMAX - XMIN), /*Rectangularity */ (PLOTSTUFF.YSIZE - 4*H)/(YMAX - YMIN)); /* matching?*/ H = MIN(PLOTSTUFF.XSIZE,S*(XMAX - XMIN)); /*X-width for text.*/ H = MIN(PLOTCHAR,H/(MAX(LENGTH(T1),LENGTH(T2)) + 6)); IF ¬NEWRANGE(XMIN*S,XMAX*S,YMIN*S-2*H,YMAX*S+2*H) THEN STOP('Urp!'); CALL PLOTTEXT(-LENGTH(T1)*H/2,YMAX*S + 2*PLOTTICK,H,T1,0); CALL PLOTTEXT(-LENGTH(T2)*H/2,YMIN*S - 2*H + 2*PLOTTICK,H,T2,0); QUARTERTURN = MIN(MAX(3,12*SQRT(S)),90); /*Angle refinement.*/ ABOUTTURN = QUARTERTURN*2; FULLTURN = QUARTERTURN*4; /*Ensures divisibility.*/ TORAD = TWOPI/FULLTURN; /*Imagine if FULLTURN was 360.*/ ZL = 1; /*Start with 0 degrees.*/ FOR L = 0 TO 3; /*The four directions.*/ FOR I = 0 TO FULLTURN; /*Fill out the petals in the corner.*/ LEAF(L,I) = ZL + EXP((0 + 1I)*I*TORAD); /*Poke!*/ END; /*Fill out the full circle for each for simplicity.*/ ZL = ZL*(0 + 1I); /*Rotate to the next axis.*/ END; /*Four circles, centred one unit along each axial direction.*/ Z = -ZMID; /*The start point. Was 0, before shift by ZMID.*/ CALL PLOTZ(S*Z,3); /*Position the pen.*/ DIRECTION = 0; /*The way ahead is along the x-axis.*/ DZ = 1; /*The step before the kink.*/ IF SWAPXY THEN DIRECTION = -QUARTERTURN; /*Or maybe y.*/ IF SWAPXY THEN DZ = (0 - 1I); /*An x-y swap.*/ FRESHRANGE = TRUE; /*A sniffing.*/ FOR I = 1 TO N; /*The deviationism begins.*/ I1 = I/32768; I2 = MOD(I,32768); IF FOLD(I1,I2) THEN WAY = +1; ELSE WAY = -1; ND = DIRECTION + QUARTERTURN*WAY; IF ND >= FULLTURN THEN ND = ND - FULLTURN; IF ND < 0 THEN ND = ND + FULLTURN; LD = ND/QUARTERTURN; /*Select a leaf.*/ LD1 = MOD(ND + ABOUTTURN,FULLTURN); LD2 = LD1 + WAY*QUARTERTURN; /*No mod, see the FOR loop below.*/ FOR L = LD1 TO LD2 BY WAY; /*Round the kink.*/ LL = L; /*A copy to wrap into range.*/ IF LL < 0 THEN LL = LL + FULLTURN; IF LL >= FULLTURN THEN LL = LL - FULLTURN; ZL = Z + LEAF(LD,LL); /*Work along the curve.*/ CALL PLOTZ(S*ZL,2); /*Move a bit.*/ END; /*On to the next step.*/ DIRECTION = ND; /*The new direction.*/ Z = Z + DZ; /*The first half of the step that has been rounded.*/ DZ = DZ*(0 + 1I)*WAY; /*A right-angle, one way or the other.*/ Z = Z + DZ; /*Avoid the roundoff of hordes of fractional moves.*/ END; /*On to the next fold.*/ CALL PLOT(0,0,998); IF TRACERANGE THEN PUT SKIP(3) FILE(DRAGON) LIST('Dragoncurve: '); IF TRACERANGE THEN PUT FILE(DRAGON) DATA(RANGE,ORDER,S,ZMID); XX:END; END DRAGONCURVE;  %PAGE;  %PAGE;  %PAGE; RANDOM:PROCEDURE(SEED) RETURNS(REAL); DECLARE SEED INTEGER; SEED = SEED*497 + 4032; IF SEED <= 0 THEN SEED = SEED + 32767; IF SEED > 32767 THEN SEED = MOD(SEED,32767); RETURN(SEED/32767.0); END RANDOM;    %PAGE; TRACE:PROCEDURE(O,R,A,N,G); DECLARE (I,N,G) INTEGER; DECLARE (O,R,A(*),X0,X1,X2) COMPLEX; X1 = O + R*A(1); X0 = X1; CALL PLOT(REAL(X1),IMAG(X1),3); FOR I = 2 TO N; X2 = O + R*A(I); CALL PLOT(REAL(X2),IMAG(X2),2); X1 = X2; END; CALL PLOT(REAL(X0),IMAG(X0),2); END TRACE;   CENTREZ:PROCEDURE(A,N); DECLARE (A(*),T) COMPLEX; DECLARE (I,N) INTEGER; T = 0; FOR I = 1 TO N; T = T + A(I); END; T = T/N; FOR I = 1 TO N; A(I) = A(I) - T; END; END CENTREZ;  %PAGE;  %PAGE; DECLARE (BELCH,ORDER,CHASE,TWIRL) INTEGER; DECLARE HOP BOOLEAN;   TWOPI = 8*ATAN(1); TORAD = TWOPI/360; BELCH = REPLYN('How many dragoncurves (max 20)'); IF BELCH < 12 THEN HOP = FALSE; ELSE HOP = YEA('Go directly to order ' || IFMT(BELCH)); /*ORDER = REPLYN('The depth of recursion (eg 4)'); CHASE = REPLYN('How many pursuits'); TWIRL = REPLYN('How many twirls'); TRACERANGE = YEA('Trace the ranges');*/ CALL DRAGONCURVE(BELCH,HOP); /*CALL TRIANGLEPLEX(ORDER); CALL SQUAREBASH(ORDER,+1); CALL SQUAREBASH(ORDER,-1); CALL SNOWFLAKE(ORDER); CALL SNOWFLAKE3(ORDER); CALL PURSUE(CHASE); CALL LISSAJOU(TWIRL); CALL CARDIOD; CALL HEART;*/ CALL PLOT(0,0,-3); CALL PLOT(0,0,999); END TEST;  
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
#Java
Java
import java.util.Arrays;   public class LinearCombination { private static String linearCombo(int[] c) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < c.length; ++i) { if (c[i] == 0) continue; String op; if (c[i] < 0 && sb.length() == 0) { op = "-"; } else if (c[i] < 0) { op = " - "; } else if (c[i] > 0 && sb.length() == 0) { op = ""; } else { op = " + "; } int av = Math.abs(c[i]); String coeff = av == 1 ? "" : "" + av + "*"; sb.append(op).append(coeff).append("e(").append(i + 1).append(')'); } if (sb.length() == 0) { return "0"; } return sb.toString(); }   public static void main(String[] args) { int[][] combos = new int[][]{ new int[]{1, 2, 3}, new int[]{0, 1, 2, 3}, new int[]{1, 0, 3, 4}, new int[]{1, 2, 0}, new int[]{0, 0, 0}, new int[]{0}, new int[]{1, 1, 1}, new int[]{-1, -1, -1}, new int[]{-1, -2, 0, -3}, new int[]{-1}, }; for (int[] c : combos) { System.out.printf("%-15s ->  %s\n", Arrays.toString(c), linearCombo(c)); } } }
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
f[x_,y_] := x + y (* Function comment : adds two numbers *) f::usage = "f[x,y] gives the sum of x and y"   ?f -> f[x,y] gives the sum of x and y
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#MATLAB_.2F_Octave
MATLAB / Octave
function Gnash(GnashFile); %Convert to a "function". Data is placed in the "global" area. % My first MatLab attempt, to swallow data as produced by Gnash's DUMP %command in a comma-separated format. Such files start with a line
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Neko
Neko
/** ... **/
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).
#jq
jq
def diversitytheorem($actual; $predicted): def mean: add/length;   ($predicted | mean) as $mean | { avgerr: ($predicted | map(. - $actual) | map(pow(.; 2)) | mean), crderr: pow($mean - $actual; 2), divers: ($predicted | map(. - $mean) | map(pow(.;2)) | mean) } ;
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).
#Julia
Julia
import Statistics: mean   function diversitytheorem(truth::T, pred::Vector{T}) where T<:Number μ = mean(pred) avgerr = mean((pred .- truth) .^ 2) crderr = (μ - truth) ^ 2 divers = mean((pred .- μ) .^ 2) avgerr, crderr, divers end   for (t, s) in [(49, [48, 47, 51]), (49, [48, 47, 51, 42])] avgerr, crderr, divers = diversitytheorem(t, s) println(""" average-error : $avgerr crowd-error  : $crderr diversity  : $divers """) end
http://rosettacode.org/wiki/Draw_a_sphere
Draw a sphere
Task Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. Related tasks draw a cuboid draw a rotating cube write language name in 3D ASCII draw a Deathstar
#Turing
Turing
% Draw a sphere in ASCII art in Turing   % Light intensity to character map const shades := '.:!*oe&#%@' const maxShades := length (shades)   % Absolute dot product of x and y function dot (x, y : array 1 .. 3 of real) : real result abs (x(1) * y(1) + x(2) * y(2) + x(3) * y(3)) end dot   % Vector normalization procedure normalize (var v : array 1 .. 3 of real) const norm := sqrt (v(1)**2 + v(2)**2 + v(3)**2) for i : 1 .. 3 v(i) := v(i) / norm end for end normalize   % Draws a sphere using ASCII art procedure drawSphere (radius : real, k : int, lightsource : array 1 .. 3 of real, brightness : real) const diameter := 2.0 * radius for i : floor (-radius) .. ceil (radius) var x := i + 0.5 for j : floor (-diameter) .. ceil (diameter) var y  := j / 2 + 0.5   if x**2 + y**2 <= radius**2 then var vec : array 1 .. 3 of real vec(1) := x; vec(2) := y; vec(3) := sqrt (radius**2 - x**2 - y**2) normalize (vec)   const b := dot (lightsource, vec) ** k + brightness var intensity := round ((1 - b) * maxShades)   if intensity < 1 then intensity := 1 elsif intensity > maxShades then intensity := maxShades end if   put shades (intensity) .. else put ' ' .. end if end for put "" end for end drawSphere   % Light source var lightsource : array 1 .. 3 of real := init (30, 30, -59) normalize (lightsource) const brightness := 0.1   % Draw some spheres drawSphere (20, 4, lightsource, brightness) drawSphere (15, 10, lightsource, brightness)