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/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...
#Python
Python
from turtle import *   def dragon(step, length): dcr(step, length)   def dcr(step, length): step -= 1 length /= 1.41421 if step > 0: right(45) dcr(step, length) left(90) dcl(step, length) right(45) else: right(45) forward(length) left(9...
http://rosettacode.org/wiki/Display_a_linear_combination
Display a linear combination
Task Display a finite linear combination in an infinite vector basis ( e 1 , e 2 , … ) {\displaystyle (e_{1},e_{2},\ldots )} . Write a function that, when given a finite list of scalars ( α 1 , α 2 , … ) {\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )} , creates a string representing t...
#Phix
Phix
with javascript_semantics function linear_combination(sequence f) string res = "" for e=1 to length(f) do integer fe = f[e] if fe!=0 then if fe=1 then if length(res) then res &= "+" end if elsif fe=-1 then res &= "-" elsif fe>0 ...
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Retro
Retro
  # Determine The Average Word Name Length   To determine the average length of a word name two values are needed. First, the total length of all names in the Dictionary:   ~~~ #0 [ d:name s:length + ] d:for-each ~~~   And then the number of words in the Dictionary:   ~~~ #0 [ dr...
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#REXX
REXX
/*REXX program illustrates how to display embedded documentation (help) within REXX code*/ parse arg doc /*obtain (all) the arguments from C.L. */ if doc='?' then call help /*show documentation if arg=a single ? */ /*■■■■■■■■■regular■■■■■■■■■■■■■■■■■■■■■■■■■*/ /...
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Ring
Ring
  /* Multiply two numbers n1: an integer. n2: an integer. returns product of n1 and n2 */ see mult(3, 5) + nl func mult n1, n2 return n1*n2  
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...
#R
R
diversityStats <- function(trueValue, estimates) { collectivePrediction <- mean(estimates) data.frame("True Value" = trueValue, as.list(setNames(estimates, paste("Guess", seq_along(estimates)))), #Guesses, each with a title and column. "Average Error" = mean((trueValue - estimates)^2), ...
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...
#Racket
Racket
#lang racket   (define (mean l) (/ (apply + l) (length l)))   (define (diversity-theorem truth predictions) (define μ (mean predictions)) (define (avg-sq-diff a) (mean (map (λ (p) (sqr (- p a))) predictions))) (hash 'average-error (avg-sq-diff truth) 'crowd-error (sqr (- truth μ)) 'diversity...
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 ...
#Action.21
Action!
INT FUNC DotProduct(INT ARRAY v1,v2 BYTE len) BYTE i,res   res=0 FOR i=0 TO len-1 DO res==+v1(i)*v2(i) OD RETURN (res)   PROC PrintVector(INT ARRAY a BYTE size) BYTE i   Put('[) FOR i=0 TO size-1 DO PrintI(a(i)) IF i<size-1 THEN Put(',) FI OD Put(']) RETURN   PROC Test(INT AR...
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...
#Delphi
Delphi
  program Doubly_linked;   {$APPTYPE CONSOLE}   uses System.SysUtils, boost.LinkedList;   var List: TLinkedList<string>; Head, Tail,Current: TLinkedListNode<string>; Value:string;   begin List := TLinkedList<string>.Create;   List.AddFirst('.AddFirst() adds at the head.'); List.AddLast('.AddLast() adds ...
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[DisariumQ] DisariumQ[n_Integer] := Module[{digs}, digs = IntegerDigits[n]; digs = digs^Range[Length[digs]]; Total[digs] == n ] i = 0; Reap[Do[ If[DisariumQ[n], i++; Sow[n] ]; If[i == 19, Break[]] , {n, 0, \[Infinity]} ]][[2, 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...
#Perl
Perl
use strict; use warnings;   my ($n,@D) = (0, 0); while (++$n) { my($m,$sum); map { $sum += $_ ** ++$m } split '', $n; push @D, $n if $n == $sum; last if 19 == @D; } print "@D\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.
#PowerShell
PowerShell
$DNS = Resolve-DnsName -Name www.kame.net Write-Host "IPv4:" $DNS.IP4Address "`nIPv6:" $DNS.IP6Address
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.
#Python
Python
>>> import socket >>> ips = set(i[4][0] for i in socket.getaddrinfo('www.kame.net', 80)) >>> for ip in ips: print ip ... 2001:200:dff:fff1:216:3eff:feb1:44d7 203.178.141.194
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.
#R
R
  #include <Rcpp.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h>   using namespace Rcpp ;   // [[Rcpp::export]] CharacterVector getNameInfo(std::string fqdn) {   struct addrinfo hints, *res, *res0; int error; char...
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...
#Quackery
Quackery
[ $ "turtleduck.qky" loadfile ] now!   [ 2 * 2dup turn 4 1 walk turn ] is corner ( n/d --> )   forward is right ( n --> )   forward is left ( n --> )   [ dup 0 = iff [ drop 8 1 walk ] done 1 - dup left 1 4 corn...
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...
#PureBasic
PureBasic
; Process and output values. Procedure WriteLinear(Array c.i(1)) Define buf$, i.i, j.i, b,i   b = #True j = 0   For i = 0 To ArraySize(c(), 1) If c(i) = 0 : Continue : EndIf   If c(i) < 0 If b : Print("-") : Else : Print(" - ") : EndIf ElseIf c(i) > 0 If Not b : Print(" + ") : ...
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Ruby
Ruby
=begin rdoc RDoc is documented here[http://www.ruby-doc.org/core/classes/RDoc.html].   This is a class documentation comment. This text shows at the top of the page for the class.   Comments can be written inside "=begin rdoc"/"end" blocks or in normal '#' comment blocks.   There are no '@parameters' like javadoc, bu...
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Rust
Rust
//! Documentation for the module //! //! **Lorem ipsum** dolor sit amet, consectetur adipiscing elit. Aenean a //! sagittis sapien, eu pellentesque ex. Nulla facilisi. Praesent eget sapien //! sollicitudin, laoreet ipsum at, fringilla augue. In hac habitasse platea //! dictumst. Nunc in neque sed magna suscipit mattis ...
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Scala
Scala
/** * This is a class documentation comment. This text shows at the top of the page for this class * * @author Joe Schmoe */ class Doc { /** * This is a field comment for a variable */ private val field = 0   /** * This is a method comment. It has parameter tags (param) and a return value tag ...
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...
#Raku
Raku
sub diversity-calc($truth, @pred) { my $ae = avg-error($truth, @pred); # average individual error my $cp = ([+] @pred)/+@pred; # collective prediction my $ce = ($cp - $truth)**2; # collective error my $pd = avg-error($cp, @pred); # prediction diversity return $ae, $ce, $pd; }   sub a...
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 ...
#ActionScript
ActionScript
function dotProduct(v1:Vector.<Number>, v2:Vector.<Number>):Number { if(v1.length != v2.length) return NaN; var sum:Number = 0; for(var i:uint = 0; i < v1.length; i++) sum += v1[i]*v2[i]; return sum; } trace(dotProduct(Vector.<Number>([1,3,-5]),Vector.<Number>([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...
#E
E
def makeDLList() { def firstINode def lastINode   def makeNode(var value, var prevI, var nextI) { # To meet the requirement that the client cannot create a loop, the # inter-node refs are protected: clients only get the external facet # with invariant-preserving operations. ...
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...
#Phix
Phix
with javascript_semantics constant limit = 19 integer count = 0, n = 0 printf(1,"The first 19 Disarium numbers are:\n") while count<limit do atom dsum = 0 string digits = sprintf("%d",n) for i=1 to length(digits) do dsum += power(digits[i]-'0',i) end for if dsum=n then printf(1," %d...
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...
#Picat
Picat
main => Limit = 19, D = [], N = 0, printf("The first %d Disarium numbers are:\n",Limit), while (D.len < Limit) if disarium_number(N) then D := D ++ [N] end, N := N + 1, if N mod 10_000_000 == 0 then println(test=N) end end, println(D).   disarium_number(N) => Sum...
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.
#Racket
Racket
  #lang racket   (require net/dns) (dns-get-address "8.8.8.8" "www.kame.net")  
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.
#Raku
Raku
use Net::DNS;   my $resolver = Net::DNS.new('8.8.8.8');   my $ip4 = $resolver.lookup('A', 'orange.kame.net'); my $ip6 = $resolver.lookup('AAAA', 'orange.kame.net');   say $ip4[0].octets.join: '.'; say $ip6[0].octets.».fmt("%.2X").join.comb(4).join: ':';
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...
#R
R
  Dragon<-function(Iters){ Rotation<-matrix(c(0,-1,1,0),ncol=2,byrow=T) ########Rotation multiplication matrix Iteration<-list() ###################################Set up list for segment matrices for 1st Iteration[[1]] <- matrix(rep(0,16), ncol = 4) Iteration[[1]][1,]<-c(0,0,1,0) Iteration[[1]][2,]<-c(1,0,1,...
http://rosettacode.org/wiki/Display_a_linear_combination
Display a linear combination
Task Display a finite linear combination in an infinite vector basis ( e 1 , e 2 , … ) {\displaystyle (e_{1},e_{2},\ldots )} . Write a function that, when given a finite list of scalars ( α 1 , α 2 , … ) {\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )} , creates a string representing t...
#Python
Python
  def linear(x): return ' + '.join(['{}e({})'.format('-' if v == -1 else '' if v == 1 else str(v) + '*', i + 1) for i, v in enumerate(x) if v] or ['0']).replace(' + -', ' - ')   list(map(lambda x: print(linear(x)), [[1, 2, 3], [0, 1, 2, 3], [1, 0, 3, 4], [1, 2, 0], [0, 0, 0], [0], [1, 1, 1], [-1, -1...
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Smalltalk
Smalltalk
FooClass comment: 'This is a comment ....'.
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#SQL_PL
SQL PL
  CREATE TABLESPACE myTs;   COMMENT ON TABLESPACE myTs IS 'Description of the tablespace.';   CREATE SCHEMA mySch;   COMMENT ON SCHEMA mySch IS 'Description of the schema.';   CREATE TYPE myType AS (col1 INT) MODE DB2SQL;   COMMENT ON TYPE mytype IS 'Description of the type.';   CREATE TABLE myTab ( myCol1 INT NOT NU...
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...
#REXX
REXX
/* REXX */ Numeric Digits 20 Call diversityTheorem 49,'48 47 51' Say '--------------------------------------' Call diversityTheorem 49,'48 47 51 42' Exit   diversityTheorem: Parse Arg truth,list average=average(list) Say 'average-error='averageSquareDiff(truth,list) Say 'crowd-error='||(truth-average)**2 Say ...
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...
#Ruby
Ruby
def mean(a) = a.sum(0.0) / a.size def mean_square_diff(a, predictions) = mean(predictions.map { |x| square(x - a)**2 })   def diversity_theorem(truth, predictions) average = mean(predictions) puts "truth: #{truth}, predictions #{predictions}", "average-error: #{mean_square_diff(truth, predictions)}", ...
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 ...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; procedure dot_product is type vect is array(Positive range <>) of Integer; v1 : vect := (1,3,-5); v2 : vect := (4,-2,-1);   function dotprod(a: vect; b: vect) return Integer is sum : Integer := 0; begin if not (a'Length=b'Length) then raise Constraint_Error; end if; for p ...
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...
#Erlang
Erlang
  -module( doubly_linked_list ).   -export( [append/2, foreach_next/2, foreach_previous/2, free/1, insert/3, new/1, task/0] ).   append( New, Start ) -> Start ! {append, New}.   foreach_next( Fun, Start ) -> Start ! {foreach_next, Fun}.   foreach_previous( Fun, Start ) -> Start ! {foreach_previous, Fun}.   free( Elemen...
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...
#Python
Python
#!/usr/bin/python   def isDisarium(n): digitos = len(str(n)) suma = 0 x = n while x != 0: suma += (x % 10) ** digitos digitos -= 1 x //= 10 if suma == n: return True else: return False   if __name__ == '__main__': limite = 19 cont = 0 n = 0 ...
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...
#PL.2FM
PL/M
100H: /* FIND SOME DISARIUM NUMBERS - NUMBERS WHOSE DIGIT POSITION-POWER */ /* SUMS ARE EQUAL TO THE NUMBER, E.G. 135 = 1^1 + 3^2 + 5^3 */   /* CP/M BDOS SYSTEM CALL, IGNORE THE RETURN VALUE */ BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END; P...
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.
#REXX
REXX
/*REXX program displays IPV4 and IPV6 addresses for a supplied domain name.*/ parse arg tar . /*obtain optional domain name from C.L.*/ if tar=='' then tar= 'www.kame.net' /*Not specified? Then use the default.*/ tFID = '\TEMP\DNSQUERY.$$$' /*define temp file to store IPV4 outpu...
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.
#Ruby
Ruby
irb(main):001:0> require 'socket' => true irb(main):002:0> Addrinfo.getaddrinfo("www.kame.net", nil, nil, :DGRAM) \ irb(main):003:0* .map! { |ai| ai.ip_address } => ["203.178.141.194", "2001:200:dff:fff1:216:3eff:feb1:44d7"]
http://rosettacode.org/wiki/Dragon_curve
Dragon curve
Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an...
#Racket
Racket
#lang racket   (require plot)   (define (dragon-turn n) (if (> (bitwise-and (arithmetic-shift (bitwise-and n (- n)) 1) n) 0) 'L 'R))   (define (rotate heading dir) (cond [(eq? dir 'R) (cond [(eq? heading 'N) 'E] [(eq? heading 'E) 'S] [(eq? heading 'S) ...
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...
#Racket
Racket
#lang racket/base (require racket/match racket/string)   (define (linear-combination->string es) (let inr ((es es) (i 1) (rv "")) (match* (es rv) [((list) "") "0"] [((list) rv) rv] [((list (? zero?) t ...) rv) (inr t (add1 i) rv)] [((list n t ...) rv) (define ±n (mat...
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...
#Raku
Raku
sub linear-combination(@coeff) { (@coeff Z=> map { "e($_)" }, 1 .. *) .grep(+*.key) .map({ .key ~ '*' ~ .value }) .join(' + ') .subst('+ -', '- ', :g) .subst(/<|w>1\*/, '', :g) || '0' }   say linear-combination($_) for [1, 2, 3], [0, 1, 2, 3], [1, 0, 3, 4], [1, 2, 0], [0, 0, 0], [0], [1...
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Stata
Stata
prog def hello di "Hello, World!" end
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Swift
Swift
/** Adds two numbers  :param: a an integer.  :param: b another integer.  :returns: the sum of a and b */ func add(a: Int, b: Int) -> Int { return a + b }
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Tcl
Tcl
#****f* RosettaCode/TclDocDemo # FUNCTION # TclDocDemo is a simple illustration of how to do documentation # of Tcl code using Robodoc. # SYNOPSYS # TclDocDemo foo bar # INPUTS # foo -- the first part of the message to print # bar -- the last part of the message to print # RESULT # No result # NOTES #...
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...
#Scala
Scala
object DiversityPredictionTheorem { def square(d: Double): Double = d * d   def average(a: Array[Double]): Double = a.sum / a.length   def averageSquareDiff(d: Double, predictions: Array[Double]): Double = average(predictions.map(it => square(it - d)))   def diversityTheorem(truth: Double, predictions: Ar...
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 ...
#Aime
Aime
real dp(list a, list b) { real p, v; integer i;   p = 0; for (i, v in a) { p += v * b[i]; }   p; }   integer main(void) { o_(dp(list(1r, 3r, -5r), list(4r, -2r, -1r)), "\n");   0; }
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...
#F.23
F#
type DListAux<'T> = {mutable prev: DListAux<'T> option; data: 'T; mutable next: DListAux<'T> option} type DList<'T> = {mutable front: DListAux<'T> option; mutable back: DListAux<'T> option} //'   let empty() = {front=None; back=None}   let addFront dlist elt = match dlist.front with | None -> let e = Some {pr...
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...
#Raku
Raku
my $disarium = (^∞).hyper.map: { $_ if $_ == sum .polymod(10 xx *).reverse Z** 1..* };   put $disarium[^18]; put $disarium[18];
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...
#Sidef
Sidef
func is_disarium(n) { n.digits.flip.sum_kv{|k,d| d**(k+1) } == n }   say 18.by(is_disarium)
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.
#Rust
Rust
use std::net::ToSocketAddrs;   fn main() { let host = "www.kame.net"; // Ideally, we would want to use std::net::lookup_host to resolve the host ips, // but at time of writing this, it is still unstable. Fortunately, we can // still resolve using the ToSocketAddrs trait, but we need to add a port, /...
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.
#Scala
Scala
import java.net._   InetAddress.getAllByName("www.kame.net").foreach(x => println(x.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.
#Scheme
Scheme
; Query DNS (define n (car (hostent:addr-list (gethost "www.kame.net"))))   ; Display address as IPv4 and IPv6 (display (inet-ntoa n))(newline) (display (inet-ntop AF_INET n))(newline) (display (inet-ntop AF_INET6 n))(newline)
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...
#Raku
Raku
use SVG;   role Lindenmayer { has %.rules; method succ { self.comb.map( { %!rules{$^c} // $c } ).join but Lindenmayer(%!rules) } }   my $dragon = "FX" but Lindenmayer( { X => 'X+YF+', Y => '-FX-Y' } );   $dragon++ xx ^15;   my @points = 215, 350;   for $dragon.comb { state ($x, $y) = @points[0,1];...
http://rosettacode.org/wiki/Display_a_linear_combination
Display a linear combination
Task Display a finite linear combination in an infinite vector basis ( e 1 , e 2 , … ) {\displaystyle (e_{1},e_{2},\ldots )} . Write a function that, when given a finite list of scalars ( α 1 , α 2 , … ) {\displaystyle (\alpha ^{1},\alpha ^{2},\ldots )} , creates a string representing t...
#REXX
REXX
/*REXX program displays a finite liner combination in an infinite vector basis. */ @.= .; @.1 = ' 1, 2, 3 ' /*define a specific test case for build*/ @.2 = ' 0, 1, 2, 3 ' /* " " " " " " " */ @.3 = ' 1, 0, 3, 4 ' ...
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#Wren
Wren
// The meaning of life! var mol = 42   // A function to add two numbers var add = Fn.new { |x, y| x + y }   /* A class with some string utilites */ class StrUtil { // reverses an ASCII string static reverse(s) { s[-1..0] }   // capitalizes the first letter of an ASCII string static capitalize(s) { ...
http://rosettacode.org/wiki/Documentation
Documentation
See also Related task: Comments Related task: Here_document
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 LET a=10: REM a is the number of apples 1000 DEF FN s(q)=q*q: REM s is a function that takes a single numeric parameter and returns its square
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...
#Sidef
Sidef
func avg_error(m, v) { v.map { (_ - m)**2 }.sum / v.len }   func diversity_calc(truth, pred) { var ae = avg_error(truth, pred) var cp = pred.sum/pred.len var ce = (cp - truth)**2 var pd = avg_error(cp, pred) return [ae, ce, pd] }   func diversity_format(stats) { gather { for t,v in (...
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...
#TypeScript
TypeScript
  function sum(array: Array<number>): number { return array.reduce((a, b) => a + b) }   function square(x : number) :number { return x * x }   function mean(array: Array<number>): number { return sum(array) / array.length }   function averageSquareDiff(a: number, predictions: Array<number>): number { re...
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 ...
#ALGOL_68
ALGOL 68
MODE DOTFIELD = REAL; MODE DOTVEC = [1:0]DOTFIELD;   # The "Spread Sheet" way of doing a dot product: o Assume bounds are equal, and start at 1 o Ignore round off error # PRIO SSDOT = 7; OP SSDOT = (DOTVEC a,b)DOTFIELD: ( DOTFIELD sum := 0; FOR i TO UPB a DO sum +:= a[i]*b[i] OD; sum );   # An improved dot-p...
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...
#Fortran
Fortran
  module dlist implicit none type node type(node), pointer :: next => null() type(node), pointer :: prev => null() integer :: data end type node   type dll type(node), pointer :: head => null() type(node), pointer :: tail => null() integer :: num_nodes = 0 end type dll   public...
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...
#VTL-2
VTL-2
1000 N=1 1010 D=0 1020 :N*10+D)=D 1030 D=D+1 1040 #=D<10*1020 1050 N=2 1060 :N*10)=0 1070 D=1 1080 :N*10+D)=:N-1*10+D)*D 1090 D=D+1 1100 #=D<10*1080 1120 N=N+1 1130 #=N<5*1060 2000 C=0 2010 T=10 2020 L=1 2030 N=0 2040 #=N=T=0*2070 2050 T=T*10 2060 L=L+1 2070 V=N 2080 P=L 2090 S=0 2100 V=V/10 2110 S=S+:P*10+% 2120 P=P-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...
#Vlang
Vlang
import strconv   const dmax = 20 // maximum digits const limit = 20 // maximum number of disariums to find   fn main() { // Pre-calculated exponential and power serials mut exp1 := [][]u64{len: 1+dmax, init: []u64{len: 11}} mut pow1 := [][]u64{len: 1+dmax, init: []u64{len: 11}}   for i := u64(1); 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...
#Wren
Wren
import "./math" for Int   var limit = 19 var count = 0 var disarium = [] var n = 0 while (count < limit) { var sum = 0 var digits = Int.digits(n) for (i in 0...digits.count) sum = sum + digits[i].pow(i+1) if (sum == n) { disarium.add(n) count = count + 1 } n = n + 1 } System.prin...
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.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "socket.s7i";   const proc: main is func begin writeln(numericAddress(inetSocketAddress("www.kame.net", 1024))); end func;
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.
#Sidef
Sidef
var (err, *res) = Socket.getaddrinfo( 'www.kame.net', 0, Hash.new(protocol => Socket.IPPROTO_TCP) ); err && die err; res.each { |z| say [Socket.getnameinfo(z{:addr}, Socket.NI_NUMERICHOST)][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.
#Standard_ML
Standard ML
- Option.map (NetHostDB.toString o NetHostDB.addr) (NetHostDB.getByName "www.kame.net"); val it = SOME "203.178.141.194": string option
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...
#RapidQ
RapidQ
DIM angle AS Double DIM x AS Double, y AS Double DECLARE SUB PaintCanvas   CREATE form AS QForm Width = 800 Height = 600 CREATE canvas AS QCanvas Height = form.ClientHeight Width = form.ClientWidth OnPaint = PaintCanvas END CREATE END CREATE   SUB turn (degrees AS Double) ...
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...
#Ring
Ring
  # Project : Display a linear combination   scalars = [[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=1 to len(scalars) str = "" for m=1 to len(scalars[n]) scalar = scalars[n] [m] if scalar != "0" ...
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...
#Ruby
Ruby
def linearCombo(c) sb = "" c.each_with_index { |n, i| if n == 0 then next end if n < 0 then if sb.length == 0 then op = "-" else op = " - " end elsif n > 0 then if sb.length > 0 then ...
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...
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Function Square(x As Double) As Double Return x * x End Function   Function AverageSquareDiff(a As Double, predictions As IEnumerable(Of Double)) As Double Return predictions.Select(Function(x) Square(x - a)).Average() End Function   Sub DiversityTheorem(truth As Dou...
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...
#Wren
Wren
import "/fmt" for Fmt   var averageSquareDiff = Fn.new { |f, preds| var av = 0 for (pred in preds) av = av + (pred-f)*(pred-f) return av/preds.count }   var diversityTheorem = Fn.new { |truth, preds| var av = (preds.reduce { |sum, pred| sum + pred }) / preds.count var avErr = averageSquareDiff.call(...
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 ...
#ALGOL_W
ALGOL W
begin  % computes the dot product of two equal length integer vectors  %  % (single dimension arrays ) the length of the vectors must be specified  %  % in length.  % integer procedure integerDotProduct( integer array 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...
#Go
Go
type dlNode struct { int next, prev *dlNode }   // Field 'members' allows loops to be prevented. All nodes // inserted should be added to members. Code that operates // on the list can check any pointer against members to // find out if the pointer is already in the list. type dlList struct { members map[...
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...
#XPL0
XPL0
func Disarium(N); \Return 'true' if N is a Disarium number int N, N0, D(10), A(10), I, J, Sum; [N0:= N; for J:= 0 to 10-1 do A(J):= 1; I:= 0; repeat N:= N/10; D(I):= rem(0); I:= I+1; for J:= 0 to I-1 do A(J):= A(J) * D(J); until N = 0; Sum:= 0; for J:= 0 to I-1 do Sum:=...
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root
Digital root/Multiplicative digital root
The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i {\displaystyle i} to 0 ...
#11l
11l
F mdroot(n) V count = 0 V mdr = n L mdr > 9 V m = mdr V digits_mul = 1 L m != 0 digits_mul *= m % 10 m = m I/ 10 mdr = digits_mul count++ R (count, mdr)   print(‘Number: (MP, MDR)’) print(‘====== =========’) L(n) (123321, 7739, 893, 899998) print(‘#6: ’.fo...
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.
#Tcl
Tcl
package require udp; # Query by UDP more widely supported, but requires external package package require dns   set host "www.kame.net" set v4 [dns::resolve $host -type A]; # Specifically get IPv4 address set v6 [dns::resolve $host -type AAAA]; # Specifically get IPv6 address while {[dns::status $v4] eq "connect" ||...
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.
#VBScript
VBScript
  Function dns_query(url,ver) Set r = New RegExp r.Pattern = "Pinging.+?\[(.+?)\].+" Set objshell = CreateObject("WScript.Shell") Set objexec = objshell.Exec("%comspec% /c " & "ping -" & ver & " " & url) WScript.StdOut.WriteLine "URL: " & url Do Until objexec.StdOut.AtEndOfStream line = objexec.StdOut.ReadLine ...
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...
#REXX
REXX
/*REXX program creates & draws an ASCII Dragon Curve (or Harter-Heighway dragon curve).*/ d.= 1; d.L= -d.; @.= ' '; x= 0; x2= x; y= 0; y2= y; z= d.; @.x.y= "∙" plot_pts = '123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZΘ' /*plot chars*/ loX= 0; hiX= 0; loY= 0; hiY= 0 ...
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...
#Rust
Rust
  use std::fmt::{Display, Formatter, Result}; use std::process::exit;   struct Coefficient(usize, f64);   impl Display for Coefficient { fn fmt(&self, f: &mut Formatter<'_>) -> Result { let i = self.0; let c = self.1;   if c == 0. { return Ok(()); }   write!( ...
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...
#Scala
Scala
object LinearCombination extends App { val combos = Seq(Seq(1, 2, 3), Seq(0, 1, 2, 3), Seq(1, 0, 3, 4), Seq(1, 2, 0), Seq(0, 0, 0), Seq(0), Seq(1, 1, 1), Seq(-1, -1, -1), Seq(-1, -2, 0, -3), Seq(-1))   private def linearCombo(c: Seq[Int]): String = { val sb = new StringBuilder for {i <- c.indi...
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...
#zkl
zkl
fcn avgError(m,v){ v.apply('wrap(n){ (n - m).pow(2) }).sum(0.0)/v.len() }   fcn diversityCalc(truth,pred){ //(Float,List of Float) ae,cp := avgError(truth,pred), pred.sum(0.0)/pred.len(); ce,pd := (cp - truth).pow(2), avgError(cp, pred); return(ae,ce,pd) }   fcn diversityFormat(stats){ // ( (averageError,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 ...
#APL
APL
1 3 ¯5 +.× 4 ¯2 ¯1
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 ...
#AppleScript
AppleScript
----------------------- DOT PRODUCT -----------------------   -- dotProduct :: [Number] -> [Number] -> Number on dotProduct(xs, ys) if length of xs = length of ys then sum(zipWith(my mul, xs, ys)) else missing value -- arrays of differing dimension end if end dotProduct     -----------------...
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...
#Haskell
Haskell
import qualified Data.Map as M   type NodeID = Maybe Rational data Node a = Node {vNode :: a, pNode, nNode :: NodeID} type DLList a = M.Map Rational (Node a)   empty = M.empty   singleton a = M.singleton 0 $ Node a Nothing Nothing   fcons :: a -> DLList a -> DLList a fcons a list | M.null list = singleton a ...
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root
Digital root/Multiplicative digital root
The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i {\displaystyle i} to 0 ...
#Ada
Ada
with Ada.Text_IO, Generic_Root; use Generic_Root;   procedure Multiplicative_Root is   procedure Compute is new Compute_Root("*"); -- "*" for multiplicative roots   package TIO renames Ada.Text_IO; package NIO is new TIO.Integer_IO(Number);   procedure Print_Numbers(Target_Root: Number; How_Many: Natural)...
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.
#Wren
Wren
/* dns_query.wren */   class Net { foreign static lookupHost(host) }   var host = "orange.kame.net" var addrs = Net.lookupHost(host).split(", ") System.print(addrs.join("\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.
#zkl
zkl
zkl: Network.TCPClientSocket.addrInfo("www.kame.net") L("orange.kame.net",L("203.178.141.194","2001:200:dff:fff1:216:3eff:feb1:44d7"))
http://rosettacode.org/wiki/Dragon_curve
Dragon curve
Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an...
#Ruby
Ruby
Point = Struct.new(:x, :y) Line = Struct.new(:start, :stop)   Shoes.app(:width => 800, :height => 600, :resizable => false) do   def split_segments(n) dir = 1 @segments = @segments.inject([]) do |new, l| a, b, c, d = l.start.x, l.start.y, l.stop.x, l.stop.y   mid_x = a + (c-a)/2.0 - (d-b)/2.0*dir ...
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...
#Sidef
Sidef
func linear_combination(coeffs) { var res = "" for e,f in (coeffs.kv) { given(f) { when (1) { res += "+e(#{e+1})" } when (-1) { res += "-e(#{e+1})" } case (.> 0) { res += "+#{f}*e(#{e+1})" ...
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 ...
#Arturo
Arturo
dotProduct: function [a,b][ [ensure equal? size a size b]   result: 0 loop 0..(size a)-1 'i [ result: result + a\[i] * b\[i] ] return result ]   print dotProduct @[1, 3, neg 5] @[4, neg 2, neg 1] print dotProduct [1 2 3] [4 5 6]
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...
#Icon_and_Unicon
Icon and Unicon
  class DoubleList (item)   method head () node := item every (node := node.traverse_backwards ()) # move to start of list return node end   method tail () node := item every (node := node.traverse_forwards ()) # move to end of list return node end   method insert_at_head (value) h...
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root
Digital root/Multiplicative digital root
The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i {\displaystyle i} to 0 ...
#ALGOL_68
ALGOL 68
BEGIN # Multiplicative Digital Roots # # structure to hold the results of calculating the digital root & persistence # MODE DR = STRUCT( INT root, INT persistence ); # returns the product of the digits of number # OP DIGITPRODU...
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...
#Run_BASIC
Run BASIC
graphic #g, 600,600 RL$ = "R" loc = 90 pass = 0   [loop] #g "cls ; home ; north ; down ; fill black" for i =1 to len(RL$) v = 255 * i /len(RL$) #g "color "; v; " 120 "; 255 -v #g "go "; loc if mid$(RL$,i,1) ="R" then #g "turn 90" else #g "turn -90" next i   #g "color 255 120 0" #g "go "; loc LR$ ="" 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...
#Tcl
Tcl
proc lincom {factors} { set exp 0 set res "" foreach f $factors { incr exp if {$f == 0} { continue } elseif {$f == 1} { append res "+e($exp)" } elseif {$f == -1} { append res "-e($exp)" } elseif {$f > 0} { append res "+$...
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 ...
#AutoHotkey
AutoHotkey
Vet1 := "1,3,-5" Vet2 := "4 , -2 , -1" MsgBox % DotProduct( Vet1 , Vet2 )   ;---------------------------   DotProduct( VectorA , VectorB ) { Sum := 0 StringSplit, ArrayA, VectorA, `,, %A_Space% StringSplit, ArrayB, VectorB, `,, %A_Space% If ( ArrayA0 <> ArrayB0 ) Return ERROR While ( A_Index <= ArrayA0 ) ...
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...
#J
J
list=: 2 3 5 7 11
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root
Digital root/Multiplicative digital root
The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i {\displaystyle i} to 0 ...
#ALGOL_W
ALGOL W
begin  % calculate the Multiplicative Digital Root (mdr) and Multiplicative Persistence (mp) of n % procedure getMDR ( integer value n  ; integer result mdr, mp ) ; begin mp  := 0; mdr := abs n; while mdr > 9 do begin integer v; ...
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...
#Rust
Rust
  use ggez::{ conf::{WindowMode, WindowSetup}, error::GameResult, event, graphics::{clear, draw, present, Color, MeshBuilder}, nalgebra::Point2, Context, }; use std::time::Duration;   // L-System to create the sequence needed for a Dragon Curve. // This function creates the next generation given...
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...
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Text   Module Module1   Function LinearCombo(c As List(Of Integer)) As String Dim sb As New StringBuilder For i = 0 To c.Count - 1 Dim n = c(i) If n < 0 Then If sb.Length = 0 Then sb.Append("-") Else ...
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 ...
#AWK
AWK
  # syntax: GAWK -f DOT_PRODUCT.AWK BEGIN { v1 = "1,3,-5" v2 = "4,-2,-1" if (split(v1,v1arr,",") != split(v2,v2arr,",")) { print("error: vectors are of unequal lengths") exit(1) } printf("%g\n",dot_product(v1arr,v2arr)) exit(0) } function dot_product(v1,v2, i,sum) { for (i in v1...