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...
#Java
Java
  import java.util.LinkedList;   public class DoublyLinkedList {   public static void main(String[] args) { LinkedList<String> list = new LinkedList<String>(); list.addFirst("Add First"); list.addLast("Add Last 1"); list.addLast("Add Last 2"); list.addLast("Add Last 1"); ...
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 ...
#AWK
AWK
# Multiplicative Digital Roots   BEGIN {   printMdrAndMp( 123321 ); printMdrAndMp( 7739 ); printMdrAndMp( 893 ); printMdrAndMp( 899998 );   tabulateMdr( 5 );   } # BEGIN   function printMdrAndMp( n ) { calculateMdrAndMp( n ); printf( "%6d: MDR: %d, MP: %2d\n", n, MDR, MP ); } # printMdr...
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...
#Scala
Scala
import javax.swing.JFrame import java.awt.Graphics   class DragonCurve(depth: Int) extends JFrame(s"Dragon Curve (depth $depth)") {   setBounds(100, 100, 800, 600); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   val len = 400 / Math.pow(2, depth / 2.0); val startingAngle = -depth * (Math.PI / 4); val steps...
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem
Dinesman's multiple-dwelling problem
Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of...
#11l
11l
-V BAKER = 0 COOPER = 1 FLETCHER = 2 MILLER = 3 SMITH = 4 names = [‘Baker’, ‘Cooper’, ‘Fletcher’, ‘Miller’, ‘Smith’]   V floors = Array(1..5)   L I floors[BAKER] != 5 & floors[COOPER] != 1 & floors[FLETCHER] !C (1, 5) & floors[MILLER] > floors[COOPER] & abs(floors[SMIT...
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these le...
#11l
11l
F sentenceType(s) I s.empty R ‘’   [Char] types L(c) s I c == ‘?’ types.append(Char(‘Q’)) E I c == ‘!’ types.append(Char(‘E’)) E I c == ‘.’ types.append(Char(‘S’))   I s.last !C ‘?!.’ types.append(Char(‘N’))   R types.join(‘|’)   V s = ‘hi there, 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...
#Vlang
Vlang
import strings   fn linear_combo(c []int) string { mut sb := strings.new_builder(128) for i, n in c { if n == 0 { continue } mut op := '' match true { n < 0 && sb.len == 0 { op = "-" } n < 0{ op = " - " } n > ...
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...
#Wren
Wren
import "/fmt" for Fmt   var linearCombo = Fn.new { |c| var sb = "" var i = 0 for (n in c) { if (n != 0) { var op = (n < 0 && sb == "") ? "-" : (n < 0) ? " - " : (n > 0 && sb == "") ? "" : " + " var av = n.abs ...
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 ...
#BASIC
BASIC
  100 : 110 REM DOT PRODUCT 120 : 130 REM INITIALIZE VECTORS OF LENGTH N 140 N = 3 150 DIM V1(N): DIM V2(N) 160 FOR I = 1 TO N 170 V1(I) = INT ( RND (1) * 20 - 9.5) 180 V2(I) = INT ( RND (1) * 20 - 9.5) 190 NEXT I 300 : 310 REM CALCULATE THE DOT PRODUCT 320 : 330 FOR I = 1 TO N:DP = DP + V1...
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...
#JavaScript
JavaScript
show(DLNode)
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 ...
#Bracmat
Bracmat
( & ( MP/MDR = prod L n . ( prod = d . @(!arg:%@?d ?arg)&!d*prod$!arg | 1 ) & !arg:?L & whl ' ( @(!arg:? [>1) & (prod$!arg:?arg) !L:?L ) & !L:? [?n & (!n+-1.!arg) ) & ( test = n .  !arg:%?n ?arg ...
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...
#Scilab
Scilab
n_folds=10   folds=[]; folds=[0 1];   old_folds=[]; vectors=[];   i=[];   for i=2:n_folds+1   curve_length=length(folds);   vectors=folds(1:curve_length-1)-folds(curve_length);   vectors=vectors.*exp(90/180*%i*%pi);   new_folds=folds(curve_length)+vectors;   j=curve_length;   while j>1 f...
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem
Dinesman's multiple-dwelling problem
Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; procedure Dinesman is subtype Floor is Positive range 1 .. 5; type People is (Baker, Cooper, Fletcher, Miller, Smith); type Floors is array (People'Range) of Floor; type PtFloors is access all Floors;   function Constrained (f : PtFloors) return Boolean is begin i...
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these le...
#ALGOL_68
ALGOL 68
BEGIN # determuine the type of a sentence by looking at the final punctuation # CHAR exclamation = "E"; # classification codes... # CHAR question = "Q"; CHAR serious = "S"; CHAR neutral = "N"; # returns the type(s) of the sentence(s) in s - exclamation, question, # # ...
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these le...
#AutoHotkey
AutoHotkey
Sentence := "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it" Msgbox, % SentenceType(Sentence)   SentenceType(Sentence) { Sentence := Trim(Sentence) Loop, Parse, Sentence, .?! { N := (!E && !Q && !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...
#zkl
zkl
fcn linearCombination(coeffs){ [1..].zipWith(fcn(n,c){ if(c==0) "" else "%s*e(%s)".fmt(c,n) },coeffs) .filter().concat("+").replace("+-","-").replace("1*","") or 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 ...
#BASIC256
BASIC256
dim zero3d = {0.0, 0.0, 0.0} dim zero5d = {0.0, 0.0, 0.0, 0.0, 0.0} dim x = {1.0, 0.0, 0.0} dim y = {0.0, 1.0, 0.0} dim z = {0.0, 0.0, 1.0} dim q = {1.0, 1.0, 3.14159} dim r = {-1.0, 2.618033989, 3.0}   print " q dot r = "; dot(q, r) print " zero3d dot zero5d = "; dot(zero3d, zero5d) print " zero3d dot x ...
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 ...
#bc
bc
/* Calculate the dot product of two vectors a and b (represented as * arrays) of size n. */ define d(a[], b[], n) { auto d, i   for (i = 0; i < n; i++) { d += a[i] * b[i] } return(d) }   a[0] = 1 a[1] = 3 a[2] = -5 b[0] = 4 b[1] = -2 b[2] = -1 d(a[], b[], 3)
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...
#Julia
Julia
show(DLNode)
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 ...
#C
C
  #include <stdio.h>   #define twidth 5 #define mdr(rmdr, rmp, n)\ do { *rmp = 0; _mdr(rmdr, rmp, n); } while (0)   void _mdr(int *rmdr, int *rmp, long long n) { /* Adjust r if 0 case, so we don't return 1 */ int r = n ? 1 : 0; while (n) { r *= (n % 10); n /= 10; }   (*rmp)++; ...
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...
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i"; include "math.s7i"; include "draw.s7i"; include "keybd.s7i";   var float: angle is 0.0; var integer: x is 220; var integer: y is 220;   const proc: turn (in integer: degrees) is func begin angle +:= flt(degrees) * PI / 180.0 end func;   const proc: forward ...
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem
Dinesman's multiple-dwelling problem
Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of...
#ALGOL_68
ALGOL 68
# attempt to solve the dinesman Multiple Dwelling problem #   # SETUP #   # special floor values # INT top floor = 4; INT bottom floor = 0;   # mode to specify the persons floor constraint # MODE PERSON = STRUCT( STRING name, REF INT floor, PROC( INT )BOOL ok );   # yields TRUE if the floor of the specified pe...
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these le...
#AWK
AWK
  # syntax: GAWK -f DETERMINE_SENTENCE_TYPE.AWK BEGIN { str = "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it" main(str) main("Exclamation! Question? Serious. Neutral") exit(0) } function ma...
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these le...
#CLU
CLU
% This iterator takes a string and yields one of 'E', 'Q', % 'S' or 'N' for every sentence found. % Because sentences are separated by punctuation, only the % last one can be 'N'.   sentence_types = iter (s: string) yields (char) own punct: string := "!?."  % relevant character classes own space: string := " \t...
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these le...
#Epoxy
Epoxy
const SentenceTypes: { ["?"]:"Q", ["."]:"S", ["!"]:"E" }   fn DetermineSentenceType(Char) return SentenceTypes[Char]||"N" cls   fn GetSentences(Text) var Sentences: [], Index: 0, Length: #Text loop i:0;i<Length;i+:1 do var Char: string.subs(Text,i,1) var Type: DetermineSentenceType(Char) if Type != "N" ...
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 ...
#BCPL
BCPL
get "libhdr"   let dotproduct(A, B, len) = valof $( let acc = 0 for i=0 to len-1 do acc := acc + A!i * B!i resultis acc $)   let start() be $( let A = table 1, 3, -5 let B = table 4, -2, -1 writef("%N*N", dotproduct(A, B, 3)) $)
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...
#Kotlin
Kotlin
// version 1.1.2   class LinkedList<E> { class Node<E>(var data: E, var prev: Node<E>? = null, var next: Node<E>? = null) { override fun toString(): String { val sb = StringBuilder(this.data.toString()) var node = this.next while (node != null) { sb.append...
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 ...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   class Program { static Tuple<int, int> DigitalRoot(long num) { int mp = 0; while (num > 9) { num = num.ToString().ToCharArray().Select(x => x - '0').Aggregate((a, b) => a * b); mp++; } ...
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...
#SequenceL
SequenceL
import <Utilities/Math.sl>; import <Utilities/Conversion.sl>;   initPoints := [[0,0],[1,0]];   f1(point(1)) := let matrix := [[cos(45 * (pi/180)), -sin(45 * (pi/180))], [sin(45 * (pi/180)), cos(45 * (pi/180))]]; in head(transpose((1/sqrt(2)) * matmul(matrix, transpose([point]))));   f2(point(1)) := let ...
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem
Dinesman's multiple-dwelling problem
Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of...
#AutoHotkey
AutoHotkey
  # syntax: GAWK -f DINESMANS_MULTIPLE-DWELLING_PROBLEM.AWK BEGIN { for (Baker=1; Baker<=5; Baker++) { for (Cooper=1; Cooper<=5; Cooper++) { for (Fletcher=1; Fletcher<=5; Fletcher++) { for (Miller=1; Miller<=5; Miller++) { for (Smith=1; Smith<=5; Smith++) { if (rule...
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these le...
#Factor
Factor
USING: combinators io kernel regexp sequences sets splitting wrap.strings ;   ! courtesy of https://www.infoplease.com/common-abbreviations   CONSTANT: common-abbreviations { "A.B." "abbr." "Acad." "A.D." "alt." "A.M." "Assn." "at. no." "at. wt." "Aug." "Ave." "b." "B.A." "B.C." "b.p." "B.S." "c." "Capt." "...
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these le...
#FreeBASIC
FreeBASIC
function sentype( byref s as string ) as string 'determines the sentence type of the first sentence in the string 'returns "E" for an exclamation, "Q" for a question, "S" for serious 'and "N" for neutral. 'modifies the string to remove the first sentence for i as uinteger = 1 to len(s) if mi...
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these le...
#Go
Go
package main   import ( "fmt" "strings" )   func sentenceType(s string) string { if len(s) == 0 { return "" } var types []string for _, c := range s { if c == '?' { types = append(types, "Q") } else if c == '!' { types = append(types, "E") ...
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 ...
#Befunge_93
Befunge 93
  v Space for variables v Space for vector1 v Space for vector2 v http://rosettacode.org/wiki/Dot_product >00pv >>55+":htgneL",,,,,,,,&:0` | v,,,,,,,"Length can't be negative."+55< >,,,,,,,,,,,,,,,,,,,@ |!`-10< ...
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...
#Lua
Lua
-- Doubly Linked List in Lua 6/15/2020 db ------------------- -- IMPLEMENTATION: -------------------   local function Node(data) return { data=data } --implied: return { data=data, prev=nil, next=nil } end   local List = { head = nil, tail = nil, insertHead = function(self, data) local node = Node(data) ...
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#8080_Assembly
8080 Assembly
;; On the 44th day of Discord in the YOLD 3186, ddate ;; has finally come to CP/M. bdos: equ 5 ; CP/M syscalls puts: equ 9 putch: equ 2 fcb: equ 5ch month: equ fcb + 1 ; use the FCB as the date argument day: equ month + 2 year: equ day + 2 org 100h ;; CP/M will try to parse the command line arguments 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 ...
#C.2B.2B
C++
  #include <iomanip> #include <map> #include <vector> #include <iostream> using namespace std;   void calcMDR( int n, int c, int& a, int& b ) { int m = n % 10; n /= 10; while( n ) { m *= ( n % 10 ); n /= 10; } if( m >= 10 ) calcMDR( m, ++c, a, b ); else { a = m; b = c; } }   void table() { ...
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...
#Sidef
Sidef
var rules = Hash( x => 'x+yF+', y => '-Fx-y', )   var lsys = LSystem( width: 600, height: 600,   xoff: -430, yoff: -380,   len: 8, angle: 90, color: 'dark green', )   lsys.execute('Fx', 11, "dragon_curve.png", rules)
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem
Dinesman's multiple-dwelling problem
Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of...
#AWK
AWK
  # syntax: GAWK -f DINESMANS_MULTIPLE-DWELLING_PROBLEM.AWK BEGIN { for (Baker=1; Baker<=5; Baker++) { for (Cooper=1; Cooper<=5; Cooper++) { for (Fletcher=1; Fletcher<=5; Fletcher++) { for (Miller=1; Miller<=5; Miller++) { for (Smith=1; Smith<=5; Smith++) { if (rule...
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these le...
#jq
jq
  # Input: a string # Output: a stream of sentence type indicators def sentenceTypes: def trim: sub("^ +";"") | sub(" +$";""); def parse: capture("(?<s>[^?!.]*)(?<p>[?!.])(?<remainder>.*)" ) // {p:"", remainder:""}; def encode: if . == "?" then "Q" elif . == "!" then "E" elif . == "." then "...
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these le...
#Julia
Julia
const text = """ Hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it"""   haspunctotype(s) = '.' in s ? "S" : '!' in s ? "E" : '?' in s ? "Q" : "N"   text = replace(text, "\n" => " ") parsed = strip.(split(text,...
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these le...
#Lua
Lua
text = "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it" p2t = { [""]="N", ["."]="S", ["!"]="E", ["?"]="Q" } for s, p in text:gmatch("%s*([^%!%?%.]+)([%!%?%.]?)") do print(s..p..": "..p2t[p]) end
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these le...
#Perl
Perl
use strict; use warnings; use feature 'say'; use Lingua::Sentence;   my $para1 = <<'EOP'; hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it EOP   my $para2 = <<'EOP'; Just because there are punctuation charact...
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 ...
#BQN
BQN
•Show 1‿3‿¯5 +´∘× 4‿¯2‿¯1   # as a tacit function DotP ← +´× •Show 1‿3‿¯5 DotP 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...
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { Form 80, 50 Class Null {} Global Null->Null() Class Node { group pred, succ dat=0 Remove { Print "destroyed", .dat } class: module Node { .pred->Null ...
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#8086_Assembly
8086 Assembly
;; DDATE for MS-DOS (assembles using nasm) bits 16 cpu 8086 tlength: equ 80h cmdtail: equ 81h putch: equ 2 puts: equ 9 getdate: equ 2Ah org 100h section .text ;; Check if a date was given mov bl,[tlength] ; Length of command line and bl,bl ; Is it zero? jz gettoday ; Then get today's date ;; ...
http://rosettacode.org/wiki/Dijkstra%27s_algorithm
Dijkstra's algorithm
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path pro...
#11l
11l
T Edge String start String end Int cost   F (start, end, cost) .start = start .end = end .cost = cost   T Graph [Edge] edges Set[String] vertices   F (edges) .edges = edges.map((s, e, c) -> Edge(s, e, c)) .vertices = Set(.edges.map(e -> e.start)).union(Set(.edges.map(e...
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displ...
#11l
11l
F digital_root(=n) V ap = 0 L n >= 10 n = sum(String(n).map(digit -> Int(digit))) ap++ R (ap, n)   L(n) [Int64(627615), 39390, 588225, 393900588225, 55] Int64 persistance, root (persistance, root) = digital_root(n) print(‘#12 has additive persistance #2 and digital root #..’.format(n, pers...
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 ...
#CLU
CLU
digits = iter (n: int) yields (int) while n>0 do yield(n//10) n := n/10 end end digits   mdr = proc (n: int) returns (int,int) i: int := 0 while n>=10 do m: int := 1 for d: int in digits(n) do m := m * d end n := m i := i+1 end ...
http://rosettacode.org/wiki/Dragon_curve
Dragon curve
Create and display a dragon curve fractal. (You may either display the curve directly or write it to an image file.) Algorithms Here are some brief notes the algorithms used and how they might suit various languages. Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an...
#Smalltalk
Smalltalk
levels = 16 level = 0 step = 1 > draw(level) level += step  ? level>levels step = -1 level += step*2 .  ? level=0, step = 1 #.delay(1) <   draw(level)= mx,my = #.scrsize() fs = #.min(mx,my)/2 r = fs/2^((level-1)/2) x = mx/2+fs*#.sqrt(2)/2 y = my/2+fs/4 a = #.pi/4*(level-2) #.scroff() #...
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem
Dinesman's multiple-dwelling problem
Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of...
#BASIC
BASIC
print "Los apartamentos están numerados del 0 (bajo) al 4 (ático)." print "Baker, Cooper, Fletcher, Miller y Smith viven en apartamentos diferentes." print "- Baker no vive en el último apartamento (ático)." print "- Cooper no vive en el piso inferior (bajo)." print "- Fletcher no vive ni en el ático ni en el bajo." pr...
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these le...
#Phix
Phix
with javascript_semantics constant s = `hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it` sequence t = split_any(trim(s),"?!."), u = substitute_all(s,t,repeat("|",length(t))), v = substitu...
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these le...
#Python
Python
import re   txt = """ Hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it"""   def haspunctotype(s): return 'S' if '.' in s else 'E' if '!' in s else 'Q' if '?' in s else 'N'   txt = re.sub('\n', '', txt) pa...
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 ...
#Bracmat
Bracmat
( dot = a A z Z .  !arg:(%?a ?z.%?A ?Z) & !a*!A+dot$(!z.!Z) | 0 ) & out$(dot$(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 ...
#C
C
#include <stdio.h> #include <stdlib.h>   int dot_product(int *, int *, size_t);   int main(void) { int a[3] = {1, 3, -5}; int b[3] = {4, -2, -1};   printf("%d\n", dot_product(a, b, sizeof(a) / sizeof(a[0])));   return EXIT_SUCCESS; }   int dot_product(int *a, int *b, size_t n) { ...
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ds = CreateDataStructure["DoublyLinkedList"]; ds["Append", #] & /@ {1, 5, 7, 0, 3, 2}; ds["Prepend", 9]; ds["Append", 4]; (* This is adding at the end and then swap to insert in to the middle: *) ds["Append", 14]; ds["SwapPart", Round[ds["Length"]/2], ds["Length"]]; ds["Elements"]
http://rosettacode.org/wiki/Dice_game_probabilities
Dice game probabilities
Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six. They roll their dice and sum the totals of the faces. The player with the highest total wins (i...
#11l
11l
F throw_die(n_sides, n_dice, s, [Int] &counts) I n_dice == 0 counts[s]++ R L(i) 1..n_sides throw_die(n_sides, n_dice - 1, s + i, counts)   F beating_probability(n_sides1, n_dice1, n_sides2, n_dice2) V len1 = (n_sides1 + 1) * n_dice1 V C1 = [0] * len1 throw_die(n_si...
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#Ada
Ada
with Ada.Calendar.Arithmetic; with Ada.Text_IO; with Ada.Integer_Text_IO; with Ada.Strings.Unbounded; with Ada.Strings.Unbounded.Text_IO; with Ada.Command_Line;   procedure Discordian is use Ada.Calendar; use Ada.Strings.Unbounded; use Ada.Command_Line; package UStr_IO renames Ada.Strings.Unbounded.Text_IO;...
http://rosettacode.org/wiki/Dijkstra%27s_algorithm
Dijkstra's algorithm
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path pro...
#Ada
Ada
private with Ada.Containers.Ordered_Maps; generic type t_Vertex is (<>); package Dijkstra is   type t_Graph is limited private;   -- Defining a graph (since limited private, only way to do this is to use the Build function) type t_Edge is record From, To : t_Vertex; Weight  : Positive; end r...
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displ...
#360_Assembly
360 Assembly
* Digital root 21/04/2017 DIGROOT CSECT USING DIGROOT,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) save previous context ST R13,4(R15) link backward ST...
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displ...
#Ada
Ada
package Generic_Root is type Number is range 0 .. 2**63-1; type Number_Array is array(Positive range <>) of Number; type Base_Type is range 2 .. 16; -- any reasonable base to write down numb   generic with function "&"(X, Y: Number) return Number; -- instantiate with "+" for additive digital ro...
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 ...
#Common_Lisp
Common Lisp
  (defun mdr/p (n) "Return a list with MDR and MP of n" (if (< n 10) (list n 0) (mdr/p-aux n 1 1)))   (defun mdr/p-aux (n a c) (cond ((and (zerop n) (< a 10)) (list a c)) ((zerop n) (mdr/p-aux a 1 (+ c 1))) (t (mdr/p-aux (floor n 10) (* (rem n 10) a) c))))   (defun first-n-number-for-each-root (n &opti...
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...
#SPL
SPL
levels = 16 level = 0 step = 1 > draw(level) level += step  ? level>levels step = -1 level += step*2 .  ? level=0, step = 1 #.delay(1) <   draw(level)= mx,my = #.scrsize() fs = #.min(mx,my)/2 r = fs/2^((level-1)/2) x = mx/2+fs*#.sqrt(2)/2 y = my/2+fs/4 a = #.pi/4*(level-2) #.scroff() #...
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem
Dinesman's multiple-dwelling problem
Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of...
#Bracmat
Bracmat
( Baker Cooper Fletcher Miller Smith:?people & ( constraints = .  !arg  : ~(? Baker)  : ~(Cooper ?)  : ~(Fletcher ?|? Fletcher)  : ? Cooper ? Miller ?  : ~(? Smith Fletcher ?|? Fletcher Smith ?)  : ~(? Cooper Fletcher ?|? Fletcher Cooper ?) ) & ( solutio...
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these le...
#Raku
Raku
use Lingua::EN::Sentence;   my $paragraph = q:to/PARAGRAPH/; hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it     Just because there are punctuation characters like "?", "!" or especially "." present, it does...
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these le...
#Vlang
Vlang
fn sentence_type(s string) string { if s.len == 0 { return "" } mut types := []string{} for c in s.split('') { if c == '?' { types << "Q" } else if c == '!' { types << "E" } else if c == '.' { types << "S" } } if s[s.len...
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these le...
#Wren
Wren
var sentenceType = Fn.new { |s| if (s.count == 0) return "" var types = [] for (c in s) { if (c == "?") { types.add("Q") } else if (c == "!") { types.add("E") } else if (c == ".") { types.add("S") } } if (!"?!.".contains(s[-1])) typ...
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 ...
#C.23
C#
static void Main(string[] args) { Console.WriteLine(DotProduct(new decimal[] { 1, 3, -5 }, new decimal[] { 4, -2, -1 })); Console.Read(); }   private static decimal DotProduct(decimal[] vec1, decimal[] vec2) { if (vec1 == null) return 0;   if (vec2 == null) return 0;   if (vec1.Length != vec2.Length) return...
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...
#Nim
Nim
type List[T] = object head, tail: Node[T]   Node[T] = ref TNode[T]   TNode[T] = object next, prev: Node[T] data: T   proc initList[T](): List[T] = discard   proc newNode[T](data: T): Node[T] = new(result) result.data = data   proc prepend[T](l: var List[T], n: Node[T]) = n.next = l.head if l.h...
http://rosettacode.org/wiki/Dice_game_probabilities
Dice game probabilities
Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six. They roll their dice and sum the totals of the faces. The player with the highest total wins (i...
#Action.21
Action!
INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit   BYTE FUNC Roll(BYTE sides,dices) BYTE i,sum   sum=0 FOR i=1 TO dices DO sum==+Rand(sides)+1 OD RETURN (sum)   PROC Test(BYTE sides1,dices1,sides2,dices2) INT i,count=[10000],sum1,sum2,wins1,wins2,draws REAL r1,r2,p   wins1=0 wins2=0 draws=0 FOR i=...
http://rosettacode.org/wiki/Dice_game_probabilities
Dice game probabilities
Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six. They roll their dice and sum the totals of the faces. The player with the highest total wins (i...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with Ada.Numerics.Discrete_Random;   procedure Main is package real_io is new Float_IO (Long_Float); use real_io;   type Dice is record Faces  : Positive; Num_Dice : Positive; end record;   procedure Roll_Dice (The_Dice : in Dice; Count : out Natural) is ...
http://rosettacode.org/wiki/Dining_philosophers
Dining philosophers
The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra. Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a rou...
#Ada
Ada
with Ada.Numerics.Float_Random; use Ada.Numerics.Float_Random; with Ada.Text_IO; use Ada.Text_IO;   with Synchronization.Generic_Mutexes_Array;   procedure Test_Dining_Philosophers is type Philosopher is (Aristotle, Kant, Spinoza, Marx, Russel); package Fork_Arrays is new Synchronization.Generic_M...
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#ALGOL_68
ALGOL 68
BEGIN # DISCORDIAN DATE CALCULATION - TRANSLATION OF MAD VIA ALGOL W # INT greg, gmonth, gday, gyear; []STRING holys = []STRING( "MUNG", "MOJO", "SYA", "ZARA", "MALA" )[ AT 0 ]; []STRING holys0 = []STRING( "CHAO", "DISCO", "CONFU", "BURE", "AF" )[ AT 0 ]; []STRING disday = []STRING( "SWE...
http://rosettacode.org/wiki/Dijkstra%27s_algorithm
Dijkstra's algorithm
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path pro...
#ALGOL_68
ALGOL 68
# -*- coding: utf-8 -*- #   COMMENT REQUIRED BY "prelude_dijkstras_algorithm.a68" CO MODE ROUTELEN = ~; ROUTELEN route len infinity = max ~; PROC route len add = (VERTEX v, ROUTE r)ROUTELEN: route len OF v + route len OF r; # or MAX(v,r) # MODE VERTEXPAYLOAD = ~; PROC dijkstra fix value error = (STRING ms...
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displ...
#ALGOL_68
ALGOL 68
# calculates the digital root and persistance of n # PROC digital root = ( LONG LONG INT n, REF INT root, persistance )VOID: BEGIN LONG LONG INT number := ABS n; persistance := 0; WHILE persistance PLUSAB 1; LONG LONG INT digit sum := 0; WHILE number > 0 ...
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 ...
#Component_Pascal
Component Pascal
  MODULE MDR; IMPORT StdLog, Strings, TextMappers, DevCommanders;   PROCEDURE CalcMDR(x: LONGINT; OUT mdr, mp: LONGINT); VAR str: ARRAY 64 OF CHAR; i: INTEGER; BEGIN mdr := 1; mp := 0; LOOP Strings.IntToString(x,str); IF LEN(str$) = 1 THEN mdr := x; EXIT END; i := 0;mdr := 1; WHILE i < LEN(str$) DO mdr :...
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...
#SVG
SVG
<?xml version="1.0" standalone="yes"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:l="http://www.w3.org/1999/xlink" width="400" height="400"> <style type="text/css"><![CDATA[ line { stroke...
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem
Dinesman's multiple-dwelling problem
Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of...
#C
C
#include <stdio.h> #include <stdlib.h>   int verbose = 0; #define COND(a, b) int a(int *s) { return (b); } typedef int(*condition)(int *);   /* BEGIN problem specific setup */ #define N_FLOORS 5 #define TOP (N_FLOORS - 1) int solution[N_FLOORS] = { 0 }; int occupied[N_FLOORS] = { 0 };   enum tenants { baker = 0, coop...
http://rosettacode.org/wiki/Determine_sentence_type
Determine sentence type
Use these sentences: "hi there, how are you today? I'd like to present to you the washing machine 9001. You have been nominated to win one of these! Just make sure you don't break it." Task Search for the last used punctuation in a sentence, and determine its type according to its punctuation. Output one of these le...
#XPL0
XPL0
include xpllib; \for StrLen int Sentence, N, Len; char Str; [Sentence:= ["hi there, how are you today?", "I'd like to present to you the washing machine 9001.", "You have been nominated to win one of these!", "Just make sure you don't break it"]; for N:= 0 to 3 do [Str:= Sent...
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 ...
#C.2B.2B
C++
#include <iostream> #include <numeric>   int main() { int a[] = { 1, 3, -5 }; int b[] = { 4, -2, -1 };   std::cout << std::inner_product(a, a + sizeof(a) / sizeof(a[0]), b, 0) << std::endl;   return 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...
#Oberon-2
Oberon-2
  IMPORT Basic; TYPE Node* = POINTER TO NodeDesc; NodeDesc* = (* ABSTRACT *) RECORD prev-,next-: Node; END;   DLList* = POINTER TO DLListDesc; DLListDesc* = RECORD first-,last-: Node; size-: INTEGER; END;  
http://rosettacode.org/wiki/Dice_game_probabilities
Dice game probabilities
Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six. They roll their dice and sum the totals of the faces. The player with the highest total wins (i...
#BASIC
BASIC
dado1 = 9: lado1 = 4 dado2 = 6: lado2 = 6 total1 = 0: total2 = 0   for i = 0 to 1 for cont = 1 to 100000 jugador1 = lanzamiento(dado1, lado1) jugador2 = lanzamiento(dado2, lado2) if jugador1 > jugador2 then total1 = total1 + 1 else if jugador1 <> jugador2 then...
http://rosettacode.org/wiki/Dice_game_probabilities
Dice game probabilities
Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six. They roll their dice and sum the totals of the faces. The player with the highest total wins (i...
#C
C
#include <stdio.h> #include <stdint.h>   typedef uint32_t uint; typedef uint64_t ulong;   ulong ipow(const uint x, const uint y) { ulong result = 1; for (uint i = 1; i <= y; i++) result *= x; return result; }   uint min(const uint x, const uint y) { return (x < y) ? x : y; }   void throw_die(con...
http://rosettacode.org/wiki/Dining_philosophers
Dining philosophers
The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra. Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a rou...
#AutoHotkey
AutoHotkey
#Persistent SetWorkingDir, %A_ScriptDir% FileDelete, output.txt EnoughForks := 2 ; required forks to begin eating Fork1 := Fork2 := Fork3 := Fork4 := Fork5 := 1 ; fork supply per philosopher SetTimer, AristotleWaitForLeftFork SetTimer, KantWaitForLeftFork SetTimer, SpinozaWaitForLeftFork SetTimer, MarxWaitForLeftFork S...
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#ALGOL_W
ALGOL W
BEGIN % DISCORDIAN DATE CALCULATION - TRANSLATION OF MAD  % INTEGER GREG, GMONTH, GDAY, GYEAR; STRING(16) ARRAY HOLY5 ( 0 :: 4 ); STRING(16) ARRAY HOLY50 ( 0 :: 4 ); STRING(16) ARRAY DISDAY ( 0 :: 4 ); STRING(16) ARRAY DISSSN ( 0 :: 4 ); INTEGER ARRAY MLENGT ( 0 ...
http://rosettacode.org/wiki/Dijkstra%27s_algorithm
Dijkstra's algorithm
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path pro...
#Applesoft_BASIC
Applesoft BASIC
100 O$ = "A" : T$ = "EF" 110 DEF FN N(P) = ASC(MID$(N$,P+(P=0),1))-64 120 DIM D(26),UNVISITED(26) 130 DIM PREVIOUS(26) : TRUE = 1 140 LET M = -1 : INFINITY = M 150 FOR I = 0 TO 26 160 LET D(I) = INFINITY : NEXT 170 FOR NE = M TO 1E38 STEP .5 180 READ C$ 190 IF LEN(C$) THEN NEXT 200 DIM C(NE),FROM(NE),T(NE) ...
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displ...
#ALGOL_W
ALGOL W
begin    % calculates the digital root and persistence of an integer in base 10  %  % in order to allow for numbers larger than 2^31, the number is passed  %  % as the lower and upper digits e.g. 393900588225 can be processed by  %  % specifying upper = 393900, lower = 58825 ...
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displ...
#AppleScript
AppleScript
on digitalroot(N as integer) script math to sum(L) if L = {} then return 0 (item 1 of L) + sum(rest of L) end sum end script   set i to 0 set M to N   repeat until M < 10 set digits to the characters of (M as text) set M to math's sum(digits) set i to i + 1 end repeat   {N:N, persistences:i, root...
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 ...
#D
D
import std.stdio, std.algorithm, std.typecons, std.range, std.conv;   /// Multiplicative digital root. auto mdRoot(in int n) pure /*nothrow*/ { auto mdr = [n]; while (mdr.back > 9) mdr ~= reduce!q{a * b}(1, mdr.back.text.map!(d => d - '0')); //mdr ~= mdr.back.text.map!(d => d - '0').mul; ...
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...
#Tcl
Tcl
package require Tk   set pi [expr acos(-1)] set r2 [expr sqrt(2)]   proc turn {degrees} { global a pi set a [expr {$a + $degrees*$pi/180}] } proc forward {len} { global a coords lassign [lrange $coords end-1 end] x y lappend coords [expr {$x + cos($a)*$len}] [expr {$y + sin($a)*$len}] } proc dragon ...
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem
Dinesman's multiple-dwelling problem
Task Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of...
#C.2B.2B
C++
#include <algorithm> #include <array> #include <cmath> #include <functional> #include <string> #include <iostream> #include <list>   int main() { constexpr auto floors = 5u; constexpr auto top = floors - 1u, bottom = 0u;   using namespace std; array<string, floors> tenants = { "Baker", "Cooper", "Fletch...
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 ...
#Clojure
Clojure
(defn dot-product [& matrix] {:pre [(apply == (map count matrix))]} (apply + (apply map * matrix)))   (defn dot-product2 [x y] (->> (interleave x y) (partition 2 2) (map #(apply * %)) (reduce +)))   (defn dot-product3 "Dot product of vectors. Tested on version 1.8.0." [v1 v2] {:pre [(= (cou...
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...
#Objeck
Objeck
  use Collection;   class Program { function : Main(args : String[]) ~ Nil { list := List->New(); list->AddFront("first"); list->AddBack("last"); list->Insert("middle");   list->Forward(); do { list->Get()->As(String)->PrintLine(); list->Previous(); } while(list->Get() <> N...
http://rosettacode.org/wiki/Dice_game_probabilities
Dice game probabilities
Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six. They roll their dice and sum the totals of the faces. The player with the highest total wins (i...
#C.2B.2B
C++
#include <cmath> #include <cstdint> #include <iomanip> #include <iostream> #include <map>   // Returns map from sum of faces to number of ways it can happen std::map<uint32_t, uint32_t> get_totals(uint32_t dice, uint32_t faces) { std::map<uint32_t, uint32_t> result; for (uint32_t i = 1; i <= faces; ++i) ...
http://rosettacode.org/wiki/Dining_philosophers
Dining philosophers
The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra. Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a rou...
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"TIMERLIB"   nSeats% = 5 DIM Name$(nSeats%-1), Fork%(nSeats%-1), tID%(nSeats%-1), Leftie%(nSeats%-1)   Name$() = "Aristotle", "Kant", "Spinoza", "Marx", "Russell" Fork%() = TRUE : REM All forks are initially on the table Leftie%(RND(nSeats%)-1) = TRUE : REM One philosop...
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#AppleScript
AppleScript
on gregorianToDiscordian(inputDate) -- Input: AppleScript date object. (* Discordian years are aligned with, and the same length as, Gregorian years. Each has 73 5-day weeks and 5 73-day seasons. (73 * 5 = 365.) The first day of a Discordian year is also that of its first week and first seas...
http://rosettacode.org/wiki/Dijkstra%27s_algorithm
Dijkstra's algorithm
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path pro...
#Arturo
Arturo
define :graph [vertices, neighbours][]   initGraph: function [edges][ vs: [] ns: #[] loop edges 'e [ [src, dst, cost]: e vs: sort unique append vs src vs: sort unique append vs dst if not? key? ns src -> ns\[src]: []   ns\[src]: ns\[src] ++ @[@[dst, cost]] ] t...
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displ...
#Applesoft_BASIC
Applesoft BASIC
1 GOSUB 430"BASE SETUP 2 FOR E = 0 TO 1 STEP 0 3 GOSUB 7"READ 4 ON E + 1 GOSUB 50, 10 5 NEXT E 6 END   7 READ N$ 8 E = N$ = "" 9 RETURN   10 GOSUB 7"READ BASE 20 IF E THEN RETURN 30 BASE = VAL(N$) 40 READ N$   50 GOSUB 100"DIGITAL ROOT 60 GOSUB 420: PRINT " HAS AD"; 70 PRINT "DITIVE PERSISTENCE"; 80 PRINT " "P"...
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displ...
#Arturo
Arturo
droot: function [num][ persistence: 0 until [ num: sum to [:integer] split to :string num persistence: persistence + 1 ][ num < 10 ] return @[num, persistence] ]   loop [627615, 39390, 588225, 393900588225] 'i [ a: droot i print [i "has additive persistence" a\0 "and digital root...
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 ...
#Elixir
Elixir
defmodule Digital do def mdroot(n), do: mdroot(n, 0)   defp mdroot(n, persist) when n < 10, do: {n, persist} defp mdroot(n, persist), do: mdroot(product(n, 1), persist+1)   defp product(0, prod), do: prod defp product(n, prod), do: product(div(n, 10), prod*rem(n, 10))   def task1(data) do IO.puts "Numbe...
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...
#Plain_TeX
Plain TeX
\input tikz.tex \usetikzlibrary{lindenmayersystems}   \pgfdeclarelindenmayersystem{Dragon curve}{ \symbol{S}{\pgflsystemdrawforward} \rule{F -> F+S} \rule{S -> F-S} } \tikzpicture \draw [lindenmayer system={Dragon curve, step=10pt, axiom=F, order=8}] lindenmayer system; \endtikzpicture \bye