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 cy... | #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 disp... |
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 ... | #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",... |
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 an... | #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(leve... |
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 t... | #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)
... |
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 t... | #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::... |
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 do... |
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 do... |
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 i... | #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
... |
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 rang... |
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 ... | #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. out... |
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 cy... | #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: ... |
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 ... | #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> s... |
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 ... | #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() {
... |
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"... |
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... |
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 an... | #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]); \
... |
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 t... | #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 } => [... |
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 t... | #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)... |
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 ... |
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 ... |
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 i... | #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()
.... |
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... |
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: Definitio... | #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 ... | #JavaScript | JavaScript | (() => {
"use strict";
// ----------- NESTED TABLES FROM OUTLINE ------------
// wikiTablesFromOutline :: [String] -> String -> String
const wikiTablesFromOutline = colorSwatch =>
outline => forestFromIndentedLines(
indentLevelsFromLines(lines(outline))
)
.map(wik... |
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 cy... | #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: ... |
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 ... | #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 ... | #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]. ... |
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 an... | #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
turnrig... |
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 t... | #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:
... |
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
... |
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... |
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 i... | #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 = me... |
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 i... | #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 }.
ec... |
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 = CG... |
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: Definitio... | #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 ... | #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 widt... |
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 ... | #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,
... |
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 cy... | #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 ... |
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 ... | #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 ... | #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 an... | #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 (sp... |
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 t... | #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 ... |
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 for... |
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... |
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 (th... |
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 i... | #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))
.aver... |
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 = CG... |
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: Definitio... | #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 ... | #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 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 ... | #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,... |
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 cy... | #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">
<ani... |
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 ... | #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 ... | #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 b... |
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 $ "I... |
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 an... | #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)
... |
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 t... | #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
... |
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: Stri... |
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 ... |
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 i... | #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) {
... |
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: Definitio... | #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 ... |
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 ... | #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 descendi... |
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 cy... | #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 -... |
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 ... | #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 ... | #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 w... |
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 an... | #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... |
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 t... | #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 constraine... |
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 i... | #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 averageS... |
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: Definitio... | #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 ... |
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 ... | #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",
... |
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 cy... | #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)
... |
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 ... | #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 mach... |
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 ... | #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 se... |
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.le... |
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 an... | #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) B... |
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 t... | #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) {
... |
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 i... | #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 i... | #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, ... |
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... |
Subsets and Splits
Rosetta Code COBOL Python Hard Tasks
Identifies and retrieves challenging tasks that exist in both COBOL and Python, revealing cross-language programming patterns and difficulty levels for comparative analysis.
Rosetta Code Task Comparisons
Identifies tasks common to both COBOL and Python languages that are described as having difficulty levels, revealing cross-language task similarities and providing useful comparative programming examples.
SQL Code Examples from Training Data
Retrieves raw SQL code examples for the SQL language, which is basic data retrieval without meaningful analysis or patterns.
SQL Code Examples from Training Data
Retrieves raw SQL code examples for the SQL language, which is basic filtering that shows what data looks like but doesn't provide meaningful analysis or patterns.
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.