task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Doubly-linked_list/Definition | Doubly-linked list/Definition | Define the data structure for a complete Doubly Linked List.
The structure should support adding elements to the head, tail and middle of the list.
The structure should not allow circular loops
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definitio... | #AutoHotkey | AutoHotkey | /* double linked list */
#include <stdio.h>
#include <stdlib.h>
struct List {
struct MNode *head;
struct MNode *tail;
struct MNode *tail_pred;
};
struct MNode {
struct MNode *succ;
struct MNode *pred;
};
typedef struct MNode *NODE;
typedef struct List *LIST;
/*
** LIST l = newList()
** create (al... |
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 ... | #Raku | Raku | my $outline = q:to/END/;
Display an outline as a nested table.
Parse the outline to a tree,
measuring the indent of each line,
translating the indentation to a nested structure,
and padding the tree to even depth.
count the leaves descending from each node,
... |
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... | #Yabasic | Yabasic | clear screen
open window 300,100
backcolor 0, 0, 0
window origin "cc"
// Display digital clock
sub digital_clock()
local t$(1), void
static as$
void = token(time$, t$(), "-")
if t$(3) <> as$ then
draw_clock(t$(1), t$(2), t$(3))
as$ = t$(3)
end if
end sub
sub draw_clock(hour$,... |
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 ... | #Phix | Phix | without js -- (zmq dll/so)
puts(1, "durapub:\n")
include zmq/zmq.e
atom context = zmq_init(1)
zmq_assert(context, "zmq_init")
--// subscriber tells us when it's ready here
atom sync = zmq_socket(context, ZMQ_PULL)
zmq_bind(sync, "tcp://*:5564")
--// send update via this socket
atom publisher = zmq_socket(context, ZM... |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #Julia | Julia |
julia> using Sockets
julia> getaddrinfo("www.kame.net")
ip"203.178.141.194"
julia> getaddrinfo("www.kame.net", IPv6)
ip"2001:200:dff:fff1:216:3eff:feb1:44d7"
|
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #Kotlin | Kotlin | // version 1.1.3
import java.net.InetAddress
import java.net.Inet4Address
import java.net.Inet6Address
fun showIPAddresses(host: String) {
try {
val ipas = InetAddress.getAllByName(host)
println("The IP address(es) for '$host' is/are:\n")
for (ipa in ipas) {
print(when (ipa) ... |
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... | #PostScript | PostScript | %!PS
%%BoundingBox: 0 0 550 400
/ifpendown false def
/rotation 0 def
/srootii 2 sqrt def
/turn {
rotation add /rotation exch def
} def
/forward {
dup rotation cos mul
exch rotation sin mul
ifpendown
{ rlineto }
{ rmoveto }
ifels... |
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... | #jq | jq | def linearCombo:
reduce to_entries[] as {key: $k,value: $v} ("";
if $v == 0 then .
else
(if $v < 0 and length==0 then "-"
elif $v < 0 then " - "
elif $v > 0 and length==0 then ""
else " + "
end) as $sign
| ($v|fabs... |
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... | #Julia | Julia | # v0.6
linearcombination(coef::Array) = join(collect("$c * e($i)" for (i, c) in enumerate(coef) if c != 0), " + ")
for c in [[1, 2, 3], [0, 1, 2, 3], [1, 0, 3, 4], [1, 2, 0], [0, 0, 0], [0], [1, 1, 1],
[-1, -1, -1], [-1, -2, 0, -3], [-1]]
@printf("%20s -> %s\n", c, linearcombination(c))
end |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Nim | Nim | ## Nim directly supports documentation using comments that start with two
## hashes (##). To create the documentation run ``nim doc file.nim``.
## ``nim doc2 file.nim`` is the same, but run after semantic checking, which
## allows it to process macros and output more information.
##
## These are the comments for the en... |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Objeck | Objeck | #~
Sets the named row value
@param name name
@param value value
@return true of value was set, false otherwise
~#
method : public : Set(name : String, value : String) ~ Bool {
return Set(@table->GetRowId(name), value);
}
|
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Objective-C | Objective-C | /*!
@function add
@abstract Adds two numbers
@discussion Use add to sum two numbers.
@param a an integer.
@param b another integer.
@return the sum of a and b
*/
int add(int a, int b) {
return a + b;
} |
http://rosettacode.org/wiki/Diversity_prediction_theorem | Diversity prediction theorem | The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the i... | #Kotlin | Kotlin | // version 1.1.4-3
fun square(d: Double) = d * d
fun averageSquareDiff(d: Double, predictions: DoubleArray) =
predictions.map { square(it - d) }.average()
fun diversityTheorem(truth: Double, predictions: DoubleArray): String {
val average = predictions.average()
val f = "%6.3f"
return "average-er... |
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... | #Lua | Lua | function square(x)
return x * x
end
function mean(a)
local s = 0
local c = 0
for i,v in pairs(a) do
s = s + v
c = c + 1
end
return s / c
end
function averageSquareDiff(a, predictions)
local results = {}
for i,x in pairs(predictions) do
table.insert(results, sq... |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #VBScript | VBScript | shades = Array(".", ":", "!", "*", "o", "e", "&", "#", "%", "@")
light = Array(30, 30, -50)
Sub Normalize(v)
length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2))
v(0) = v(0)/length : v(1) = v(1)/length : v(2) = v(2)/length
End Sub
Function Dot(x, y)
d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2)
If d < 0 Then Dot = -... |
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... | #C | C | /* double linked list */
#include <stdio.h>
#include <stdlib.h>
struct List {
struct MNode *head;
struct MNode *tail;
struct MNode *tail_pred;
};
struct MNode {
struct MNode *succ;
struct MNode *pred;
};
typedef struct MNode *NODE;
typedef struct List *LIST;
/*
** LIST l = newList()
** create (al... |
http://rosettacode.org/wiki/Disarium_numbers | Disarium numbers | A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.
E.G.
135 is a Disarium number:
11 + 32 + 53 == 1 + 9 + 125 == 135
There are a finite number of Disarium numbers.
Task
Find and display the first 18 Disarium numbers.
Stretch... | #ALGOL_68 | ALGOL 68 | BEGIN # find some Disarium numbers - numbers whose digit position-power sums #
# are equal to the number, e.g. 135 = 1^1 + 3^2 + 5^3 #
# compute the nth powers of 0-9 #
[ 1 : 9, 0 : 9 ]INT power;
FOR d FROM 0 TO 9 DO power[ 1, d ] := d OD;
... |
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 ... | #Wren | Wren | import "/dynamic" for Struct
import "/fmt" for Fmt
var NNode = Struct.create("NNode", ["name", "children"])
var INode = Struct.create("INode", ["level", "name"])
var toNest // recursive function
toNest = Fn.new { |iNodes, start, level, n|
if (level == 0) n.name = iNodes[0].name
var i = start + 1
while (... |
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... | #zkl | zkl | var
t=T("⡎⢉⢵","⠀⢺⠀","⠊⠉⡱","⠊⣉⡱","⢀⠔⡇","⣏⣉⡉","⣎⣉⡁","⠊⢉⠝","⢎⣉⡱","⡎⠉⢱","⠀⠶⠀"),
b=T("⢗⣁⡸","⢀⣸⣀","⣔⣉⣀","⢄⣀⡸","⠉⠉⡏","⢄⣀⡸","⢇⣀⡸","⢰⠁⠀","⢇⣀⡸","⢈⣉⡹","⠀⠶ ");
while(True){
x:=Time.Date.ctime()[11,8] // or Time.Date.to24HString() (no seconds)
.pump(List,fcn(n){ n.toAsc() - 0x30 }); //-->L(2,3,10,4,3,10,5,2)
print(... |
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 ... | #PicoLisp | PicoLisp | (task (port 12321) # Background server task
(let? Sock (accept @)
(unless (fork) # Handle request in child process
(in Sock
(while (rd) # Handle requests
(out Sock
(pr (eval @)) ) ) ) # Evaluate and send... |
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 ... | #Python | Python | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import SimpleXMLRPCServer
class MyHandlerInstance:
def echo(self, data):
'''Method for returning data got from client'''
return 'Server responded: %s' % data
def div(self, num1, num2):
'''Method for divide 2 numbers'''
return nu... |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #Lasso | Lasso | dns_lookup('www.kame.net', -type='A') |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #Lua | Lua | local socket = require('socket')
local ip_tbl = socket.dns.getaddrinfo('www.kame.net')
for _, v in ipairs(ip_tbl) do
io.write(string.format('%s: %s\n', v.family, v.addr))
end
|
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #Neko | Neko | /* dns in neko */
var host_resolve = $loader.loadprim("std@host_resolve", 1);
var host_to_string = $loader.loadprim("std@host_to_string", 1);
var host_reverse = $loader.loadprim("std@host_reverse", 1);
var ip = host_resolve("www.kame.net");
$print("www.kame.net: ", ip, ", ", host_to_string(ip), "\n");
$print(host_t... |
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... | #POV-Ray | POV-Ray | # handy constants with script-wide scope
[Single]$script:QUARTER_PI=0.7853982
[Single]$script:HALF_PI=1.570796
# leverage GDI (Forms and Drawing)
Add-Type -AssemblyName System.Drawing
Add-Type -AssemblyName System.Windows.Forms
$script:TurtlePen = New-Object Drawing.Pen darkGreen
$script:Form = New-Object Windows.For... |
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... | #Kotlin | Kotlin | // version 1.1.2
fun linearCombo(c: IntArray): String {
val sb = StringBuilder()
for ((i, n) in c.withIndex()) {
if (n == 0) continue
val op = when {
n < 0 && sb.isEmpty() -> "-"
n < 0 -> " - "
n > 0 && sb.isEmpty() -> ""
else ... |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #OCaml | OCaml |
; note: use this script to generate a markdown file
; sed -n 's/\s*;!\s*//gp'
(import (owl parse))
;! # Documentation
;! ## Functions
;! ### whitespace
;! Returns a #true if argument is a space, newline, return or tab character.
(define whitespace (byte-if (lambda (x) (has? '(#\tab #\newline #\space #\retu... |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Ol | Ol |
; note: use this script to generate a markdown file
; sed -n 's/\s*;!\s*//gp'
(import (owl parse))
;! # Documentation
;! ## Functions
;! ### whitespace
;! Returns a #true if argument is a space, newline, return or tab character.
(define whitespace (byte-if (lambda (x) (has? '(#\tab #\newline #\space #\retu... |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #PARI.2FGP | PARI/GP | addhelp(funcName, "funcName(v, n): This is a description of the function named funcName."); |
http://rosettacode.org/wiki/Diversity_prediction_theorem | Diversity prediction theorem | The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the i... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[DiversityPredictionTheorem]
DiversityPredictionTheorem[trueval_?NumericQ, estimates_List] :=
Module[{avg, avgerr, crowderr, diversity},
avg = Mean[estimates];
avgerr = Mean[(estimates - trueval)^2];
crowderr = (trueval - avg)^2;
diversity = Mean[(estimates - avg)^2];
<|
"TrueValue" -> trueval,
... |
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... | #Nim | Nim | import strutils, math, stats
func meanSquareDiff(refValue: float; estimates: seq[float]): float =
## Compute the mean of the squares of the differences
## between estimated values and a reference value.
for estimate in estimates:
result += (estimate - refValue)^2
result /= estimates.len.toFloat
const ... |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #Wren | Wren | var shades = ".:!*oe&#\%@"
var light = [30, 30, -50]
var normalize = Fn.new { |v|
var len = (v[0]*v[0] + v[1]*v[1] + v[2]*v[2]).sqrt
for (i in 0..2) v[i] = v[i] / len
}
var dot = Fn.new { |x, y|
var d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
return (d < 0) ? -d : 0
}
var drawSphere = Fn.new { |r, k, a... |
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... | #C.23 | C# | using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
LinkedList<string> list = new LinkedList<string>();
list.AddFirst(".AddFirst() adds at the head.");
list.AddLast(".AddLast() adds at the tail.");
LinkedListNode<string> head = list.Find(".AddFir... |
http://rosettacode.org/wiki/Disarium_numbers | Disarium numbers | A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.
E.G.
135 is a Disarium number:
11 + 32 + 53 == 1 + 9 + 125 == 135
There are a finite number of Disarium numbers.
Task
Find and display the first 18 Disarium numbers.
Stretch... | #ALGOL_W | ALGOL W | begin % find some Disarium numbers - numbers whose digit position-power sums %
% are equal to the number, e.g. 135 = 1^1 + 3^2 + 5^3 %
integer array power ( 1 :: 9, 0 :: 9 );
integer MAX_DISARIUM;
integer count, powerOfTen, length, n;
% compute the nth powers of 0-9 ... |
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 ... | #zkl | zkl | fcn parseOutline(outline){ //--> "tree" annotated with spans
var [const] indent=" "*100; // no tabs
parse:=fcn(ow,tree,parent,col,prevD,unit){
rows,span,spans,cell := 0, 0,List(), Void;
foreach line in (ow){
if(not line) continue;
d,text,d := line.prefix(indent), line[d,*], d/unit; // d==0 is... |
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... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 REM First we draw the clock face
20 FOR n=1 TO 12
30 PRINT AT 10-10*COS (n/6*PI),16+10*SIN (n/6*PI);n
40 NEXT n
50 DEF FN t()=INT (65536*PEEK 23674+256*PEEK 23673+PEEK 23672)/50: REM number of seconds since start
100 REM Now we start the clock
110 LET t1=FN t()
120 LET a=t1/30*PI: REM a is the angle of the second ha... |
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 ... | #Racket | Racket |
#lang racket/base
(require racket/place/distributed racket/place)
(define (fib n)
(if (<= n 1) n (+ (fib (- n 1)) (fib (- n 2)))))
(provide work)
(define (work)
(place ch
(place-channel-put ch (fib (place-channel-get ch)))))
(module+ main
(define places
(for/list ([host '("localhost" "localhost" "... |
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 ... | #Raku | Raku | ./server.raku --usage
Usage:
server.p6 [--server=<Any>] [--port=<Any>] |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #NetRexx | NetRexx |
/* NetRexx */
options replace format comments java crossref symbols nobinary
ir = InetAddress
addresses = InetAddress[] InetAddress.getAllByName('www.kame.net')
loop ir over addresses
if ir <= Inet4Address then do
say 'IPv4 :' ir.getHostAddress
end
if ir <= Inet6Address then do
say 'IPv6 :' ir.getHo... |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #NewLISP | NewLISP |
(define (dnsLookup site , ipv)
;; captures current IPv mode
(set 'ipv (net-ipv))
;; IPv mode agnostic lookup
(println "IPv4: " (begin (net-ipv 4) (net-lookup site)))
(println "IPv6: " (begin (net-ipv 6) (net-lookup site)))
;; returns newLISP to previous IPv mode
(net-ipv ipv)
)
(dnsLoo... |
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... | #PowerShell | PowerShell | # handy constants with script-wide scope
[Single]$script:QUARTER_PI=0.7853982
[Single]$script:HALF_PI=1.570796
# leverage GDI (Forms and Drawing)
Add-Type -AssemblyName System.Drawing
Add-Type -AssemblyName System.Windows.Forms
$script:TurtlePen = New-Object Drawing.Pen darkGreen
$script:Form = New-Object Windows.For... |
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... | #Lambdatalk | Lambdatalk |
{def linearcomb
{def linearcomb.r
{lambda {:a :n :i}
{if {= :i :n}
then
else {let { {:e e({+ :i 1})}
{:v {abs {A.get :i :a}}}
{:s {if {< {A.get :i :a} 0} then - else +}}
} {if {= :v 0} then else
{if {= :v 1} then :s :e else :s :v*:e}}}
... |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Perl | Perl | procedure StoreVar(integer N, integer NTyp)
--
-- Store a variable, applying any final operator as needed.
-- If N is zero, PopFactor (ie store in a new temporary variable of
-- the specified type). Otherwise N should be an index to symtab.
-- If storeConst is 1, NTyp is ignored/overridden, otherwise it
-- should usu... |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Phix | Phix | procedure StoreVar(integer N, integer NTyp)
--
-- Store a variable, applying any final operator as needed.
-- If N is zero, PopFactor (ie store in a new temporary variable of
-- the specified type). Otherwise N should be an index to symtab.
-- If storeConst is 1, NTyp is ignored/overridden, otherwise it
-- should usu... |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #PHP | PHP | : (doc 'car) # View documentation of a function
: (doc '+Entity) # View documentation of a class
: (doc '+ 'firefox) # Explicitly specify a browser |
http://rosettacode.org/wiki/Diversity_prediction_theorem | Diversity prediction theorem | The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the i... | #Perl | Perl | sub diversity {
my($truth, @pred) = @_;
my($ae,$ce,$cp,$pd,$stats);
$cp += $_/@pred for @pred; # collective prediction
$ae = avg_error($truth, @pred); # average individual error
$ce = ($cp - $truth)**2; # collective error
$pd = avg_error($cp, @pred); # prediction diversity
... |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
def R=100, R2=R*R; \radius, in pixels; radius squared
def X0=640/2, Y0=480/2; \coordinates of center of screen
int X, Y, Z, C, D2; \coords, color, distance from center squared
[SetVid($112); \set 640x480x24 ... |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot ... | #11l | 11l | print(dot((1, 3, -5), (4, -2, -1))) |
http://rosettacode.org/wiki/Doubly-linked_list/Definition | Doubly-linked list/Definition | Define the data structure for a complete Doubly Linked List.
The structure should support adding elements to the head, tail and middle of the list.
The structure should not allow circular loops
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definitio... | #C.2B.2B | C++ | #include <iostream>
#include <list>
int main ()
{
std::list<int> numbers {1, 5, 7, 0, 3, 2};
numbers.insert(numbers.begin(), 9); //Insert at the beginning
numbers.insert(numbers.end(), 4); //Insert at the end
auto it = std::next(numbers.begin(), numbers.size() / 2); //Iterator to the middle of the lis... |
http://rosettacode.org/wiki/Disarium_numbers | Disarium numbers | A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.
E.G.
135 is a Disarium number:
11 + 32 + 53 == 1 + 9 + 125 == 135
There are a finite number of Disarium numbers.
Task
Find and display the first 18 Disarium numbers.
Stretch... | #Arturo | Arturo | disarium?: function [x][
j: 0
psum: sum map digits x 'dig [
j: j + 1
dig ^ j
]
return psum = x
]
cnt: 0
i: 0
while [cnt < 18][
if disarium? i [
print i
cnt: cnt + 1
]
i: i + 1
] |
http://rosettacode.org/wiki/Disarium_numbers | Disarium numbers | A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.
E.G.
135 is a Disarium number:
11 + 32 + 53 == 1 + 9 + 125 == 135
There are a finite number of Disarium numbers.
Task
Find and display the first 18 Disarium numbers.
Stretch... | #AWK | AWK |
# syntax: GAWK -f DISARIUM_NUMBERS.AWK
BEGIN {
stop = 19
printf("The first %d Disarium numbers:\n",stop)
while (count < stop) {
if (is_disarium(n)) {
printf("%d ",n)
count++
}
n++
}
printf("\n")
exit(0)
}
function is_disarium(n, leng,sum,x) {
x = n
le... |
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 ... | #Ruby | Ruby | require 'drb/drb'
# The URI for the server to connect to
URI="druby://localhost:8787"
class TimeServer
def get_current_time
return Time.now
end
end
# The object that handles requests on the server
FRONT_OBJECT = TimeServer.new
$SAFE = 1 # disable eval() and friends
DRb.start_service(URI, FRONT_O... |
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 ... | #Tcl | Tcl | proc main {} {
global connections
set connections [dict create]
socket -server handleConnection 12345
vwait dummyVar ;# enter the event loop
}
proc handleConnection {channel clientaddr clientport} {
global connections
dict set connections $channel address "$clientaddr:$clientport"
fconfigu... |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #Nim | Nim | import nativesockets
iterator items(ai: ptr AddrInfo): ptr AddrInfo =
var current = ai
while current != nil:
yield current
current = current.aiNext
proc main() =
let addrInfos = getAddrInfo("www.kame.net", Port 80, AfUnspec)
defer: freeAddrInfo addrInfos
for i in addrInfos:
echo getAddrStrin... |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #Oberon-2 | Oberon-2 |
MODULE DNSQuery;
IMPORT
IO:Address,
Out := NPCT:Console;
PROCEDURE Do() RAISES Address.UnknownHostException;
VAR
ip: Address.Inet;
BEGIN
ip := Address.GetByName("www.kame.net");
Out.String(ip.ToString());Out.Ln
END Do;
BEGIN
Do;
END DNSQuery.
|
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #Objeck | Objeck | use System.IO.Net;
class Rosetta {
function : Main(args : String[]) ~ Nil {
resoloved := TCPSocket->Resolve("www.kame.net");
each(i : resoloved) {
resoloved[i]->PrintLine();
};
}
} |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an... | #Processing | Processing | float l = 3;
int ints = 13;
void setup() {
size(700, 600);
background(0, 0, 255);
translate(150, 100);
stroke(255);
turn_left(l, ints);
turn_right(l, ints);
}
void turn_right(float l, int ints) {
if (ints == 0) {
line(0, 0, 0, -l);
translate(0, -l);
} else {
turn_left(l, ints-1);
rot... |
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... | #Lua | Lua | function t2s(t)
local s = "["
for i,v in pairs(t) do
if i > 1 then
s = s .. ", " .. v
else
s = s .. v
end
end
return s .. "]"
end
function linearCombo(c)
local sb = ""
for i,n in pairs(c) do
local skip = false
if n < 0 then
... |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #PicoLisp | PicoLisp | : (doc 'car) # View documentation of a function
: (doc '+Entity) # View documentation of a class
: (doc '+ 'firefox) # Explicitly specify a browser |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #PL.2FI | PL/I |
help about_comment_based_help
|
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #PowerShell | PowerShell |
help about_comment_based_help
|
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #PureBasic | PureBasic | ; This is a small demo-code to demonstrate PureBasic’s internal
; documentation system.
;- All Includes
; By starting the line with ‘;-‘ marks that specific line as a special comment,
; and this will be included in the overview, while normal comments will not.
IncludeFile "MyLibs.pbi"
IncludeFile "Combustion_Dat... |
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... | #Phix | Phix | with javascript_semantics
function mean(sequence s)
return sum(s)/length(s)
end function
function variance(sequence s, atom d)
return mean(sq_power(sq_sub(s,d),2))
end function
function diversity_theorem(atom reference, sequence observations)
atom average_error = variance(observations,reference),
... |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #Yabasic | Yabasic | ancho = 640 : alto = 480
open window 640,480
backcolor 16,16,16
clear window
sphera()
sub sphera()
local n
for n = 1 to 100
color 2*n, 2*n, 2*n
fill circle ancho/2-2*n/3, alto/2-n/2, 150-n
next n
end sub |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot ... | #360_Assembly | 360 Assembly | * Dot product 03/05/2016
DOTPROD CSECT
USING DOTPROD,R15
SR R7,R7 p=0
LA R6,1 i=1
LOOPI CH R6,=AL2((B-A)/4) do i=1 to hbound(a)
BH ELOOPI
LR R1,R6 i
SLA R1,2 *4
... |
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... | #Clojure | Clojure | (ns double-list)
(defprotocol PDoubleList
(get-head [this])
(add-head [this x])
(get-tail [this])
(add-tail [this x])
(remove-node [this node])
(add-before [this node x])
(add-after [this node x])
(get-nth [this n]))
(defrecord Node [prev next data])
(defn make-node
"Create an internal or finali... |
http://rosettacode.org/wiki/Disarium_numbers | Disarium numbers | A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.
E.G.
135 is a Disarium number:
11 + 32 + 53 == 1 + 9 + 125 == 135
There are a finite number of Disarium numbers.
Task
Find and display the first 18 Disarium numbers.
Stretch... | #BASIC | BASIC | function isDisarium(n)
digitos = length(string(n))
suma = 0
x = n
while x <> 0
suma += (x % 10) ^ digitos
digitos -= 1
x = x \ 10
end while
if suma = n then return True else return False
end function
limite = 19
cont = 0 : n = 0
print "The first"; limite; " Disarium numbers are:"
while cont < limite
if i... |
http://rosettacode.org/wiki/Disarium_numbers | Disarium numbers | A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.
E.G.
135 is a Disarium number:
11 + 32 + 53 == 1 + 9 + 125 == 135
There are a finite number of Disarium numbers.
Task
Find and display the first 18 Disarium numbers.
Stretch... | #C.2B.2B | C++ | #include <vector>
#include <iostream>
#include <cmath>
#include <algorithm>
std::vector<int> decompose( int n ) {
std::vector<int> digits ;
while ( n != 0 ) {
digits.push_back( n % 10 ) ;
n /= 10 ;
}
std::reverse( digits.begin( ) , digits.end( ) ) ;
return digits ;
}
bool isDisarium( int ... |
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 ... | #UnixPipes | UnixPipes | : >/tmp/buffer
tail -f /tmp/buffer | nc -l 127.0.0.1 1234 | sh >/tmp/buffer 2>&1 |
http://rosettacode.org/wiki/Distributed_programming | Distributed programming | Write two programs (or one program with two modes) which run on networked computers, and send some messages between them.
The protocol used may be language-specific or not, and should be suitable for general distributed programming; that is, the protocol should be generic (not designed just for the particular example ... | #Wren | Wren | /* distributed_programming_server.wren */
class Rpc {
foreign static register()
foreign static handleHTTP()
}
foreign class Listener {
construct listen(network, address) {}
}
class HTTP {
foreign static serve(listener)
}
Rpc.register()
Rpc.handleHTTP()
var listener = Listener.listen("tcp", ":1... |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #OCaml | OCaml | let dns_query ~host ~ai_family =
let opts = [
Unix.AI_FAMILY ai_family;
Unix.AI_SOCKTYPE Unix.SOCK_DGRAM;
] in
let addr_infos = Unix.getaddrinfo host "" opts in
match addr_infos with
| [] -> failwith "dns_query"
| ai :: _ ->
match ai.Unix.ai_addr with
| Unix.ADDR_INET (addr, _) -> (Unix.stri... |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #Perl | Perl | use feature 'say';
use Socket qw(getaddrinfo getnameinfo);
my ($err, @res) = getaddrinfo('orange.kame.net', 0, { protocol=>Socket::IPPROTO_TCP } );
die "getaddrinfo error: $err" if $err;
say ((getnameinfo($_->{addr}, Socket::NI_NUMERICHOST))[1]) for @res |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an... | #Prolog | Prolog | dragonCurve(N) :-
dcg_dg(N, [left], DCL, []),
Side = 4,
Angle is -N * (pi/4),
dcg_computePath(Side, Angle, DCL, point(180,400), P, []),
new(D, window('Dragon Curve')),
send(D, size, size(800,600)),
new(Path, path(poly)),
send_list(Path, append, P),
send(D, display, Path),
send(D, open).
% compute the list... |
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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | tests = {{1, 2, 3}, {0, 1, 2, 3}, {1, 0, 3, 4}, {1, 2, 0}, {0, 0, 0}, {0}, {1, 1, 1}, {-1, -1, -1}, {-1, -2, 0, -3}, {-1}};
Column[TraditionalForm[Total[MapIndexed[#1 e[#2[[1]]] &, #]]] & /@ tests] |
http://rosettacode.org/wiki/Display_a_linear_combination | Display a linear combination | Task
Display a finite linear combination in an infinite vector basis
(
e
1
,
e
2
,
…
)
{\displaystyle (e_{1},e_{2},\ldots )}
.
Write a function that, when given a finite list of scalars
(
α
1
,
α
2
,
…
)
{\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )}
,
creates a string representing t... | #Modula-2 | Modula-2 | MODULE Linear;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
PROCEDURE WriteInt(n : INTEGER);
VAR buf : ARRAY[0..15] OF CHAR;
BEGIN
FormatString("%i", buf, n);
WriteString(buf)
END WriteInt;
PROCEDURE WriteLinear(c : ARRAY OF INTEGER);
VAR
buf : ARRAY[0..15] O... |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Python | Python | class Doc(object):
"""
This is a class docstring. Traditionally triple-quoted strings are used because
they can span multiple lines and you can include quotation marks without escaping.
"""
def method(self, num):
"""This is a method docstring."""
pass |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #R | R | example(package.skeleton) |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Racket | Racket |
#lang scribble/manual
(require (for-label "sandwiches.rkt"))
@defproc[(make-sandwich [ingredients (listof ingredient?)])
sandwich?]{
Returns a sandwich given the right ingredients.
}
|
http://rosettacode.org/wiki/Diversity_prediction_theorem | Diversity prediction theorem | The wisdom of the crowd is the collective opinion of a group of individuals rather than that of a single expert.
Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the i... | #PureBasic | PureBasic | Define.f ref=49.0, mea
NewList argV.f()
Macro put
Print(~"\n["+StrF(ref)+"]"+#TAB$)
ForEach argV() : Print(StrF(argV())+#TAB$) : Next
PrintN(~"\nAverage Error : "+StrF(vari(argV(),ref),5))
PrintN("Crowd Error : "+StrF((ref-mea)*(ref-mea),5))
PrintN("Diversity : "+StrF(vari(argV(),mea),5))
EndMacro
... |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #zkl | zkl | img:=PPM(640,480);
R:=100; R2:=R*R; //radius, in pixels; radius squared
X0:=640/2; Y0:=480/2; //coordinates of center of screen
foreach Y in ([-R..R]){ //for all the coordinates near the circle
foreach X in ([-R..R]){ // which is under the sphere
D2:=X*X + Y*Y;
C:=0; ... |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot ... | #8th | 8th | [1,3,-5] [4,-2,-1] ' n:* ' n:+ a:dot . cr |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot ... | #ABAP | ABAP | report zdot_product
data: lv_n type i,
lv_sum type i,
lt_a type standard table of i,
lt_b type standard table of i.
append: '1' to lt_a, '3' to lt_a, '-5' to lt_a.
append: '4' to lt_b, '-2' to lt_b, '-1' to lt_b.
describe table lt_a lines lv_n.
perform dot_product using lt_a lt_b lv_n changing lv_... |
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... | #Common_Lisp | Common Lisp | (defstruct dlist head tail)
(defstruct dlink content prev next)
(defun insert-between (dlist before after data)
"Insert a fresh link containing DATA after existing link BEFORE if not nil and before existing link AFTER if not nil"
(let ((new-link (make-dlink :content data :prev before :next after)))
(if (null ... |
http://rosettacode.org/wiki/Disarium_numbers | Disarium numbers | A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.
E.G.
135 is a Disarium number:
11 + 32 + 53 == 1 + 9 + 125 == 135
There are a finite number of Disarium numbers.
Task
Find and display the first 18 Disarium numbers.
Stretch... | #Factor | Factor | USING: io kernel lists lists.lazy math.ranges math.text.utils
math.vectors prettyprint sequences ;
: disarium? ( n -- ? )
dup 1 digit-groups dup length 1 [a,b] v^ sum = ;
: disarium ( -- list ) 0 lfrom [ disarium? ] lfilter ;
19 disarium ltake [ pprint bl ] leach nl |
http://rosettacode.org/wiki/Disarium_numbers | Disarium numbers | A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.
E.G.
135 is a Disarium number:
11 + 32 + 53 == 1 + 9 + 125 == 135
There are a finite number of Disarium numbers.
Task
Find and display the first 18 Disarium numbers.
Stretch... | #Go | Go | package main
import (
"fmt"
"strconv"
)
const DMAX = 20 // maximum digits
const LIMIT = 20 // maximum number of disariums to find
func main() {
// Pre-calculated exponential and power serials
EXP := make([][]uint64, 1+DMAX)
POW := make([][]uint64, 1+DMAX)
EXP[0] = make([]uint64, 11)
... |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #Phix | Phix | without js
include builtins\cffi.e
constant AF_UNSPEC = 0,
-- AF_INET = 2,
-- AF_INET6 = 23,
-- SOCK_STREAM = 1,
SOCK_DGRAM = 2,
-- IPPROTO_TCP = 6,
NI_MAXHOST = 1025,
NI_NUMERICHOST = iff(platform()=LINUX?1:2)
constant tWAD = """
typedef struct WSAData {
WORD ... |
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... | #PureBasic | PureBasic | #SqRt2 = 1.4142136
#SizeH = 800: #SizeV = 550
Global angle.d, px, py, imageNum
Procedure turn(degrees.d)
angle + degrees * #PI / 180
EndProcedure
Procedure forward(length.d)
Protected w = Cos(angle) * length
Protected h = Sin(angle) * length
LineXY(px, py, px + w, py + h, RGB(255,255,255))
px + w: py + h
... |
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... | #Nim | Nim | import strformat
proc linearCombo(c: openArray[int]): string =
for i, n in c:
if n == 0: continue
let op = if n < 0:
if result.len == 0: "-" else: " - "
else:
if n > 0 and result.len == 0: "" else: " + "
let av = abs(n)
let coeff = if av == 1: "" else: $a... |
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... | #Perl | Perl | use strict;
use warnings;
use feature 'say';
sub linear_combination {
my(@coef) = @$_;
my $e = '';
for my $c (1..+@coef) { $e .= "$coef[$c-1]*e($c) + " if $coef[$c-1] }
$e =~ s/ \+ $//;
$e =~ s/1\*//g;
$e =~ s/\+ -/- /g;
$e or 0;
}
say linear_combination($_) for
[1, 2, 3], [0, 1, 2, 3]... |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #Raku | Raku |
#= it's yellow
sub marine { ... }
say &marine.WHY; # "it's yellow"
#= a shaggy little thing
class Sheep {
#= not too scary
method roar { 'roar!' }
}
say Sheep.WHY; # "a shaggy little thing"
say Sheep.^find_method('roar').WHY; # "not too scary" |
http://rosettacode.org/wiki/Documentation | Documentation |
See also
Related task: Comments
Related task: Here_document
| #REBOL | REBOL | rebol [
Title: "Documentation"
URL: http://rosettacode.org/wiki/Documentation
Purpose: {To demonstrate documentation of REBOL pograms.}
]
; Notice the fields in the program header. The header is required for
; valid REBOL programs, although the fields don't have to be filled
; in. Standard fields are defined... |
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... | #Python | Python | '''Diversity prediction theorem'''
from itertools import chain
from functools import reduce
# diversityValues :: Num a => a -> [a] ->
# { mean-Error :: a, crowd-error :: a, diversity :: a }
def diversityValues(x):
'''The mean error, crowd error and
diversity, for a given observation x
and a no... |
http://rosettacode.org/wiki/Draw_a_sphere | Draw a sphere | Task
Draw a sphere.
The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.
Either static or rotational projection is acceptable for this task.
Related tasks
draw a cuboid
draw a rotating cube
write language name in 3D ASCII
draw a Deathstar
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 1 REM fast
50 REM spheer with hidden lines and rotation
100 CLS
110 PRINT "sphere with lenght&wide-circles"
120 PRINT "_______________________________"''
200 INPUT "rotate x-as:";a
210 INPUT "rotate y-as:";b
220 INPUT "rotate z-as:";c
225 INPUT "distance lines(10-45):";d
230 LET u=128: LET v=87: LET r=87: LET bm=PI/18... |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot ... | #ACL2 | ACL2 | (defun dotp (v u)
(if (or (endp v) (endp u))
0
(+ (* (first v) (first u))
(dotp (rest v) (rest u))))) |
http://rosettacode.org/wiki/Doubly-linked_list/Definition | Doubly-linked list/Definition | Define the data structure for a complete Doubly Linked List.
The structure should support adding elements to the head, tail and middle of the list.
The structure should not allow circular loops
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definitio... | #D | D | import std.stdio;
class LinkedList(T)
{
Node!(T) head, tail;
/** Iterate in the forward direction. */
int opApply (int delegate(uint, Node!(T)) dg)
{
uint i = 0;
auto link = head;
int result = 0;
while (link)
{
result = dg (i, link);
if (result) return result;
i++;
link = link.next;
}
... |
http://rosettacode.org/wiki/Disarium_numbers | Disarium numbers | A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.
E.G.
135 is a Disarium number:
11 + 32 + 53 == 1 + 9 + 125 == 135
There are a finite number of Disarium numbers.
Task
Find and display the first 18 Disarium numbers.
Stretch... | #Haskell | Haskell | module Disarium
where
import Data.Char ( digitToInt)
isDisarium :: Int -> Bool
isDisarium n = (sum $ map (\(c , i ) -> (digitToInt c ) ^ i )
$ zip ( show n ) [1 , 2 ..]) == n
solution :: [Int]
solution = take 18 $ filter isDisarium [0, 1 ..]
|
http://rosettacode.org/wiki/Disarium_numbers | Disarium numbers | A Disarium number is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.
E.G.
135 is a Disarium number:
11 + 32 + 53 == 1 + 9 + 125 == 135
There are a finite number of Disarium numbers.
Task
Find and display the first 18 Disarium numbers.
Stretch... | #Julia | Julia | isdisarium(n) = sum(last(p)^first(p) for p in enumerate(reverse(digits(n)))) == n
function disariums(numberwanted)
n, ret = 0, Int[]
while length(ret) < numberwanted
isdisarium(n) && push!(ret, n)
n += 1
end
return ret
end
println(disariums(19))
@time disariums(19)
|
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #PHP | PHP | <?php
$ipv4_record = dns_get_record("www.kame.net",DNS_A);
$ipv6_record = dns_get_record("www.kame.net",DNS_AAAA);
print "ipv4: " . $ipv4_record[0]["ip"] . "\n";
print "ipv6: " . $ipv6_record[0]["ipv6"] . "\n";
?> |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #PicoLisp | PicoLisp | (make
(in '(host "www.kame.net")
(while (from "address ")
(link (till "^J" T)) ) ) ) |
http://rosettacode.org/wiki/DNS_query | DNS query | DNS is an internet service that maps domain names, like rosettacode.org, to IP addresses, like 66.220.0.231.
Use DNS to resolve www.kame.net to both IPv4 and IPv6 addresses. Print these addresses.
| #Pike | Pike |
> array ips = Protocols.DNS.gethostbyname("www.kame.net")[1] || ({});
> write(ips*"\n");
|
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.