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/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.23
C#
public class Program { public static void Main() { const int count = 5; const int Baker = 0, Cooper = 1, Fletcher = 2, Miller = 3, Smith = 4; string[] names = { nameof(Baker), nameof(Cooper), nameof(Fletcher), nameof(Miller), nameof(Smith) };   Func<int[], bool>[] constraints = {...
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 ...
#CLU
CLU
% Compute the dot product of two sequences % If the sequences are not the same length, it signals length_mismatch % Any type may be used as long as it supports addition and multiplication dot_product = proc [T: type] (a, b: sequence[T]) returns (T) signals (length_mismatch, empty, overflow) ...
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...
#Oforth
Oforth
Object Class new: DNode(value, mutable prev, mutable next)   DNode method: initialize  := next := prev := value ; DNode method: value @value ; DNode method: prev @prev ; DNode method: next @next ; DNode method: setPrev := prev ; DNode method: setNext  := next ; DNode method: << @value << ;   DNode method: insertAft...
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...
#D
D
import std.stdio, std.range, std.algorithm;   void throwDie(in uint nSides, in uint nDice, in uint s, uint[] counts) pure nothrow @safe @nogc { if (nDice == 0) { counts[s]++; return; }   foreach (immutable i; 1 .. nSides + 1) throwDie(nSides, nDice - 1, s + i, counts); }   real beati...
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...
#C
C
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <stdarg.h>   #define N 5 const char *names[N] = { "Aristotle", "Kant", "Spinoza", "Marx", "Russell" }; pthread_mutex_t forks[N];   #define M 5 /* think bubbles */ const char *topic[M] = { "Spaghetti!", "Life", "Universe", "Everythi...
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#AWK
AWK
  # DDATE.AWK - Gregorian to Discordian date contributed by Dan Nielsen # syntax: GAWK -f DDATE.AWK [YYYYMMDD | YYYY-MM-DD | MM-DD-YYYY | DDMMMYYYY | YYYY] ... # examples: # GAWK -f DDATE.AWK today # GAWK -f DDATE.AWK 20110722 one date # GAWK -f DDATE.AWK 20110722 20120229 two dates ...
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...
#AutoHotkey
AutoHotkey
Dijkstra(data, start){ nodes := [], dist := [], Distance := [], dist := [], prev := [], Q := [], min := "x" for each, line in StrSplit(data, "`n" , "`r") field := StrSplit(line,"`t"), nodes[field.1] := 1, nodes[field.2] := 1 , Distance[field.1,field.2] := field.3, Distance[field.2,field.1] := field.3 dist[start]...
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...
#AutoHotkey
AutoHotkey
p := {} for key, val in [30,1597,381947,92524902,448944221089] { n := val while n > 9 { m := 0 Loop, Parse, n m += A_LoopField n := m, i := A_Index } p[A_Index] := [val, n, i] }   for key, val in p Output .= val[1] ": Digital Root = " val[2] ", Additive Persis...
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 ...
#F.23
F#
  // mdr. Nigel Galloway: June 29th., 2021 let rec fG n g=if n=0 then g else fG(n/10)(g*(n%10)) let mdr n=let rec mdr n g=if n<10 then (n,g) else mdr(fG n 1)(g+1) in mdr n 0 [123321; 7739; 893; 899998] |> List.iter(fun i->let n,g=mdr i in printfn "%d has mdr=%d with persitance %d" i n g) let fN g=Seq.initInfinite id|>S...
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...
#LaTeX
LaTeX
\documentclass{minimal} \usepackage{tikz} \usetikzlibrary{lindenmayersystems} \pgfdeclarelindenmayersystem{Dragon curve}{ \symbol{S}{\pgflsystemdrawforward} \rule{F -> -F++S-} \rule{S -> +F--S+} } \foreach \i in {1,...,8} { \hbox{ order=\i \hspace{.5em} \begin{tikzpicture}[baseli...
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...
#Ceylon
Ceylon
shared void run() {   function notAdjacent(Integer a, Integer b) => (a - b).magnitude >= 2; function allDifferent(Integer* ints) => ints.distinct.size == ints.size;   value solutions = [ for (baker in 1..4) for (cooper in 2..5) for (fletcher in 2..4) for (miller in 2..5) for (smith in 1..5) if (miller > ...
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 ...
#CoffeeScript
CoffeeScript
dot_product = (ary1, ary2) -> if ary1.length != ary2.length throw "can't find dot product: arrays have different lengths" dotprod = 0 for v, i in ary1 dotprod += v * ary2[i] dotprod   console.log dot_product([ 1, 3, -5 ], [ 4, -2, -1 ]) # 3 try console.log dot_product([ 1, 3, -5 ], [ 4, -2, -1, 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...
#Phix
Phix
+------------> start | +--+--+-----+ | | | ---+---> 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...
#Factor
Factor
USING: dice generalizations kernel math prettyprint sequences ; IN: rosetta-code.dice-probabilities   : winning-prob ( a b c d -- p ) [ [ random-roll ] 2bi@ > ] 4 ncurry [ 100000 ] dip replicate [ [ t = ] count ] [ length ] bi /f ;   9 4 6 6 winning-prob 5 10 6 7 winning-prob [ . ] bi@
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...
#Gambas
Gambas
' Gambas module file   Public Sub Main() Dim iSides, iPlayer1, iPlayer2, iTotal1, iTotal2, iCount, iCount0 As Integer Dim iDice1 As Integer = 9 Dim iDice2 As Integer = 6 Dim iSides1 As Integer = 4 Dim iSides2 As Integer = 6   Randomize   For iCount0 = 0 To 1 For iCount = 1 To 100000 iPlayer1 = Roll(iDice1, iSides...
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running
Determine if only one instance is running
This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
#Ada
Ada
with Ada.Text_IO;   procedure Single_Instance is   package IO renames Ada.Text_IO; Lock_File: IO.File_Type; Lock_File_Name: String := "single_instance.magic_lock";   begin begin IO.Open(File => Lock_File, Mode=> IO.In_File, Name => Lock_File_Name); IO.Close(Lock_File); IO.Put_Line("I can't...
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...
#C.23
C#
  using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks;   namespace Dining_Philosophers { class Program { private const int DinerCount = 5; private static List<Diner> Diners = new List<Diner>(); private...
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#BASIC
BASIC
#INCLUDE "datetime.bi"   DECLARE FUNCTION julian(AS DOUBLE) AS INTEGER   SeasonNames: DATA "Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath" Weekdays: DATA "Setting Orange", "Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle" DaysPreceding1stOfMonth: ' jan feb mar apr may jun jul aug sep oct n...
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...
#C
C
#include <stdio.h> #include <stdlib.h> #include <limits.h>   typedef struct { int vertex; int weight; } edge_t;   typedef struct { edge_t **edges; int edges_len; int edges_size; int dist; int prev; int visited; } vertex_t;   typedef struct { vertex_t **vertices; int vertices_len;...
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...
#AWK
AWK
# syntax: GAWK -f DIGITAL_ROOT.AWK BEGIN { n = split("627615,39390,588225,393900588225,10,199",arr,",") for (i=1; i<=n; i++) { dr = digitalroot(arr[i],10) printf("%12.0f has additive persistence %d and digital root of %d\n",arr[i],p,dr) } exit(0) } function digitalroot(n,b) { p = 0 # glo...
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 ...
#Factor
Factor
USING: arrays formatting fry io kernel lists lists.lazy math math.text.utils prettyprint sequences ; IN: rosetta-code.multiplicative-digital-root   : mdr ( n -- {persistence,root} ) 0 swap [ 1 digit-groups dup length 1 > ] [ product [ 1 + ] dip ] while dup empty? [ drop { 0 } ] when first 2array ;   : print...
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...
#TI-89_BASIC
TI-89 BASIC
Define dragon = (iter, xform) Prgm Local a,b If iter > 0 Then dragon(iter-1, xform*[[.5,.5,0][–.5,.5,0][0,0,1]]) dragon(iter-1, xform*[[–.5,.5,0][–.5,–.5,1][0,0,1]]) Else xform*[0;0;1]→a xform*[0;1;1]→b PxlLine floor(a[1,1]), floor(a[2,1]), floor(b[1,1]), floor(b[2,1]) EndIf EndPrgm   FnOff ...
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...
#Clojure
Clojure
(ns rosettacode.dinesman (:use [clojure.core.logic] [clojure.tools.macro :as macro]))   ; whether x is immediately above (left of) y in list s; uses pattern matching on s (defne aboveo [x y s] ([_ _ (x y . ?rest)]) ([_ _ [_ . ?rest]] (aboveo x y ?rest)))   ; whether x is on a higher floor than y...
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 ...
#Common_Lisp
Common Lisp
(defun dot-product (a b) (apply #'+ (mapcar #'* (coerce a 'list) (coerce b 'list))))
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...
#PicoLisp
PicoLisp
+------------> start | +--+--+-----+ | | | ---+---> 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...
#Go
Go
package main   import( "math" "fmt" )   func minOf(x, y uint) uint { if x < y { return x } return y }   func throwDie(nSides, nDice, s uint, counts []uint) { if nDice == 0 { counts[s]++ return } for i := uint(1); i <= nSides; i++ { throwDie(nSides, nDice -...
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running
Determine if only one instance is running
This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
#AutoHotkey
AutoHotkey
PRAGMA INCLUDE <sys/file.h> OPTION DEVICE O_NONBLOCK   OPEN ME$ FOR DEVICE AS me   IF flock(me, LOCK_EX | LOCK_NB) <> 0 THEN PRINT "I am already running, exiting..." END ENDIF   PRINT "Running this program, doing things..." SLEEP 5000   CLOSE DEVICE me
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running
Determine if only one instance is running
This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
#BaCon
BaCon
PRAGMA INCLUDE <sys/file.h> OPTION DEVICE O_NONBLOCK   OPEN ME$ FOR DEVICE AS me   IF flock(me, LOCK_EX | LOCK_NB) <> 0 THEN PRINT "I am already running, exiting..." END ENDIF   PRINT "Running this program, doing things..." SLEEP 5000   CLOSE DEVICE me
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running
Determine if only one instance is running
This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
#Bash_Shell
Bash Shell
  local fd=${2:-200}   # create lock file eval "exec $fd>/tmp/my_lock.lock"   # acquire the lock, or fail flock -nx $fd \ && # do something if you got the lock \ || # do something if you did not get the lock  
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running
Determine if only one instance is running
This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
#BBC_BASIC
BBC BASIC
SYS "CreateMutex", 0, 1, "UniqueLockName" TO Mutex% SYS "GetLastError" TO lerr% IF lerr% = 183 THEN SYS "CloseHandle", Mutex% SYS "MessageBox", @hwnd%, "I am already running", 0, 0 QUIT ENDIF   SYS "ReleaseMutex", Mutex% SYS "CloseHandle", Mutex% END
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...
#C.2B.2B
C++
#include <algorithm> #include <array> #include <chrono> #include <iostream> #include <mutex> #include <random> #include <string> #include <string_view> #include <thread>   const int timeScale = 42; // scale factor for the philosophers task duration   void Message(std::string_view message) { // thread safe printing...
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#Batch_File
Batch File
@echo off goto Parse   Discordian Date Converter:   Usage: ddate ddate /v ddate /d isoDate ddate /v /d isoDate   :Parse shift if "%0"=="" goto Prologue if "%0"=="/v" set Verbose=1 if "%0"=="/d" set dateToTest=%1 if "%0"=="/d" shift goto Parse   :Prologue if "%dateToTest%"=="" set dateToTest=%date% for...
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...
#C.23
C#
using static System.Linq.Enumerable; using static System.String; using static System.Console; using System.Collections.Generic; using System; using EdgeList = System.Collections.Generic.List<(int node, double weight)>;   public static class Dijkstra { public static void Main() { Graph graph = new Graph(6); ...
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...
#BASIC
BASIC
DECLARE SUB digitalRoot (what AS LONG)   'test inputs: digitalRoot 627615 digitalRoot 39390 digitalRoot 588225   SUB digitalRoot (what AS LONG) DIM w AS LONG, t AS LONG, c AS INTEGER   w = ABS(what) IF w > 10 THEN DO c = c + 1 WHILE w t = t + (w MOD (10)) ...
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 ...
#Fortran
Fortran
  !Implemented by Anant Dixit (Oct, 2014) program mdr implicit none integer :: i, mdr, mp, n, j character(len=*), parameter :: hfmt = '(A18)', nfmt = '(I6)' character(len=*), parameter :: cfmt = '(A3)', rfmt = '(I3)', ffmt = '(I9)'   write(*,hfmt) 'Number MDR MP ' write(*,*) '------------------'   i = 123321 call r...
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...
#Vedit_macro_language
Vedit macro language
File_Open("|(USER_MACRO)\dragon.bmp", OVERWRITE+NOEVENT) BOF Del_Char(ALL)   #11 = 640 // width of the image #12 = 480 // height of the image Call("CREATE_BMP")   #1 = 384 // dx #2 = 0 // dy #3 = 6 // depth of recursion #4 = 1 // flip #5 = 150 // x #6 = 300 // y Call("DRAGON") Buf_Close(NOMSG)   Sys(`start "...
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...
#Common_Lisp
Common Lisp
  (defpackage :dinesman (:use :cl :screamer) (:export :dinesman :dinesman-list)) (in-package :dinesman)   (defun distinctp (list) (equal list (remove-duplicates list)))   (defun dinesman () (all-values (let ((baker (an-integer-between 1 5)) (cooper (an-integer-between 1 5)) (flet...
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 ...
#Component_Pascal
Component Pascal
  MODULE DotProduct; IMPORT StdLog;   PROCEDURE Calculate*(x,y: ARRAY OF INTEGER): INTEGER; VAR i,sum: INTEGER; BEGIN sum := 0; FOR i:= 0 TO LEN(x) - 1 DO INC(sum,x[i] * y[i]); END; RETURN sum END Calculate;   PROCEDURE Test*; VAR i,sum: INTEGER; v1,v2: ARRAY 3 OF INTEGER; BEGIN v1[0] := 1;v1[1] := 3;v1[2] :=...
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...
#PL.2FI
PL/I
  define structure 1 Node, 2 value fixed decimal, 2 back_pointer handle(Node), 2 fwd_pointer handle(Node);  
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...
#Haskell
Haskell
import Control.Monad (replicateM) import Data.List (group, sort)   succeeds :: (Int, Int) -> (Int, Int) -> Double succeeds p1 p2 = sum [ realToFrac (c1 * c2) / totalOutcomes | (s1, c1) <- countSums p1 , (s2, c2) <- countSums p2 , s1 > s2 ] where totalOutcomes = realToFrac $ uncurry (^) p1 * un...
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running
Determine if only one instance is running
This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
#C
C
#include <fcntl.h> /* fcntl, open */ #include <stdlib.h> /* atexit, getenv, malloc */ #include <stdio.h> /* fputs, printf, puts, snprintf */ #include <string.h> /* memcpy */ #include <unistd.h> /* sleep, unlink */   /* Filename for only_one_instance() lock. */ #define INSTANCE_LOCK "rosetta-code-lock"   void fail(const...
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...
#Clojure
Clojure
(defn make-fork [] (ref true))   (defn make-philosopher [name forks food-amt] (ref {:name name :forks forks :eating? false :food food-amt}))   (defn start-eating [phil] (dosync (if (every? true? (map ensure (:forks @phil))) ; <-- the essential solution (do (doseq [f (:forks @phil)] (alter f no...
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"DATELIB"   PRINT "01/01/2011 -> " FNdiscordian("01/01/2011") PRINT "05/01/2011 -> " FNdiscordian("05/01/2011") PRINT "28/02/2011 -> " FNdiscordian("28/02/2011") PRINT "01/03/2011 -> " FNdiscordian("01/03/2011") PRINT "22/07/2011 -> " FNdiscordian("22/07/2011") PR...
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...
#C.2B.2B
C++
#include <iostream> #include <vector> #include <string> #include <list>   #include <limits> // for numeric_limits   #include <set> #include <utility> // for pair #include <algorithm> #include <iterator>     typedef int vertex_t; typedef double weight_t;   const weight_t max_weight = std::numeric_limits<double>::infinit...
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...
#Batch_File
Batch File
:: Digital Root Task from Rosetta Code Wiki :: Batch File Implementation :: (Base 10)   @echo off setlocal enabledelayedexpansion :: THE MAIN THING for %%x in (9876543214 393900588225 1985989328582 34559) do call :droot %%x echo( pause exit /b :: /THE MAIN THING :: THE FUNCTION :droot set inp2sum=%1 set persist=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 ...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Function multDigitalRoot(n As UInteger, ByRef mp As Integer, base_ As Integer = 10) As Integer Dim mdr As Integer mp = 0 Do mdr = IIf(n > 0, 1, 0) While n > 0 mdr *= n Mod base_ n = n \ base_ Wend mp += 1 n = mdr Loop until mdr < base_ Return mdr End Funct...
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...
#Visual_Basic
Visual Basic
Option Explicit Const Pi As Double = 3.14159265358979 Dim angle As Double Dim nDepth As Integer Dim nColor As Long   Private Sub Form_Load() nColor = vbBlack nDepth = 12 DragonCurve End Sub   Sub DragonProc(size As Double, ByVal split As Integer, d As Integer) If split = 0 Then xForm.Line -Step(-Co...
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...
#Crystal
Crystal
module Enumerable(T) def index!(element) index(element).not_nil! end end   residents = [:Baker, :Cooper, :Fletcher, :Miller, :Smith]   predicates = [ ->(p : Array(Symbol)){ :Baker != p.last }, ->(p : Array(Symbol)){ :Cooper != p.first }, ->(p : Array(Symbol)){ :Fletcher != p.first && :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 ...
#Cowgol
Cowgol
include "cowgol.coh";   sub dotproduct(a: [int32], b: [int32], len: intptr): (n: int32) is n := 0; while len > 0 loop n := n + [a] * [b]; a := @next a; b := @next b; len := len - 1; end loop; end sub;   sub printsgn(n: int32) is if n<0 then print_char('-'); ...
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...
#PowerShell
PowerShell
  $list = New-Object -TypeName 'Collections.Generic.LinkedList[PSCustomObject]'   for($i=1; $i -lt 10; $i++) { $list.AddLast([PSCustomObject]@{ID=$i; X=100+$i;Y=200+$i}) | Out-Null }   $list  
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...
#J
J
gen_dict =: (({. , #)/.~@:,@:(+/&>)@:{@:(# <@:>:@:i.)~ ; ^)&x:   beating_probability =: dyad define 'C0 P0' =. gen_dict/ x 'C1 P1' =. gen_dict/ y (C0 +/@:,@:(>/&:({."1) * */&:({:"1)) C1) % (P0 * P1) )
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...
#Java
Java
import java.util.Random;   public class Dice{ private static int roll(int nDice, int nSides){ int sum = 0; Random rand = new Random(); for(int i = 0; i < nDice; i++){ sum += rand.nextInt(nSides) + 1; } return sum; }   private static int diceGame(int p1Dice, int p1Sides, int p2Dice, int p2Sides, int roll...
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running
Determine if only one instance is running
This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
#C.23
C#
using System; using System.Net; using System.Net.Sockets;   class Program { static void Main(string[] args) { try { TcpListener server = new TcpListener(IPAddress.Any, 12345); server.Start(); }   catch (SocketException e) { if (e.SocketErr...
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running
Determine if only one instance is running
This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
#C.2B.2B
C++
#include <afx.h>
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running
Determine if only one instance is running
This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
#Clojure
Clojure
(import (java.net ServerSocket InetAddress))   (def *port* 12345) ; random large port number (try (new ServerSocket *port* 10 (. InetAddress getLocalHost)) (catch IOException e (System/exit 0))) ; port taken, so app is already running
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...
#Common_Lisp
Common Lisp
(in-package :common-lisp-user)   ;; ;; FLAG -- if using quicklisp, you can get bordeaux-threads loaded up ;; with: (ql:quickload :bordeaux-threads) ;;   (defvar *philosophers* '(Aristotle Kant Spinoza Marx Russell))   (defclass philosopher () ((name :initarg :name :reader name-of) (left-fork :initarg :left-fork :...
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#Befunge
Befunge
0" :raeY">:#,_&>\" :htnoM">:#,_&>04p" :yaD">:#,_$&>55+,1-:47*v v"f I".+1%,,,,"Day I":$_:#<0#!4#:p#-4#1g4-#0+#<<_v#!*!-2g40!-< >"o",,,/:5+*66++:4>g#<:#44#:9#+*#1-#,_$$0 v_v#!< >$ 0 "yaD " v @,+55.+*+92"j"$_,#!>#:<", in the YOLD"*84 <.>,:^ :"St. Tib's"< $# #"#"##"#"Chaos$Discord$Confusion$Bureaucracy$The Aftermath$
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...
#Clojure
Clojure
  (declare neighbours process-neighbour prepare-costs get-next-node unwind-path all-shortest-paths)     ;; Main algorithm     (defn dijkstra "Given two nodes A and B, and graph, finds shortest path from point A to point B. Given one node and graph, finds all shortest pat...
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...
#BBC_BASIC
BBC BASIC
*FLOAT64 PRINT "Digital root of 627615 is "; FNdigitalroot(627615, 10, p) ; PRINT " (additive persistence " ; p ")" PRINT "Digital root of 39390 is "; FNdigitalroot(39390, 10, p) ; PRINT " (additive persistence " ; p ")" PRINT "Digital root of 588225 is "; FNdigitalroot(588225, 10, 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...
#Befunge
Befunge
0" :rebmun retnE">:#,_0 0v v\1:/+55p00<v\`\0::-"0"<~< #>:55+%00g+^>9`+#v_+\ 1+\^ >|`9:p000<_v#`1\$< v"gi"< |> \ 1 + \ >0" :toor lat"^ >$$00g\1+^@,+<v"Di",>#+ 5< >:#,_$ . 5 5 ^>:#,_\.55+,v ^"Additive Persistence: "<
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 ...
#Go
Go
package main   import "fmt"   // Only valid for n > 0 && base >= 2 func mult(n uint64, base int) (mult uint64) { for mult = 1; mult > 0 && n > 0; n /= uint64(base) { mult *= n % uint64(base) } return }   // Only valid for n >= 0 && base >= 2 func MultDigitalRoot(n uint64, base int) (mp, mdr int) { var m uint64 f...
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...
#Visual_Basic_.NET
Visual Basic .NET
Option Explicit On Imports System.Math   Public Class DragonCurve Dim nDepth As Integer = 12 Dim angle As Double Dim MouseX, MouseY As Integer Dim CurrentX, CurrentY As Integer Dim nColor As Color = Color.Black   Private Sub DragonCurve_Click(sender As Object, e As EventArgs) Handles Me.Click ...
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...
#D
D
import std.stdio, std.math, std.algorithm, std.traits, permutations2;   void main() { enum Names { Baker, Cooper, Fletcher, Miller, Smith }   immutable(bool function(in Names[]) pure nothrow)[] predicates = [ s => s[Names.Baker] != s.length - 1, s => s[Names.Cooper] != 0, s => s[Names.Fl...
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 ...
#Crystal
Crystal
class Vector property x, y, z   def initialize(@x : Int64, @y : Int64, @z : Int64) end   def dot_product(other : Vector) (self.x * other.x) + (self.y * other.y) + (self.z * other.z) end end   puts Vector.new(1, 3, -5).dot_product Vector.new(4, -2, -1) # => 3   class Array def dot_product(other) raise ...
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...
#PureBasic
PureBasic
DataSection ;the list of words that will be added to the list words: Data.s "One", "Two", "Three", "Four", "Five", "Six", "EndOfData" EndDataSection     Procedure displayList(List x.s(), title$) ;display all elements from list of strings Print(title$) ForEach x() Print(x() + " ") Next PrintN("") E...
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...
#JacaScript
JacaScript
  let Player = function(dice, faces) { this.dice = dice; this.faces = faces; this.roll = function() { let results = []; for (let x = 0; x < dice; x++) results.push(Math.floor(Math.random() * faces +1)); return eval(results.join('+')); } }   function contest(player1, player2, rounds) { let re...
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running
Determine if only one instance is running
This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
#D
D
  bool is_unique_instance() { import std.socket; auto socket = new Socket(AddressFamily.UNIX, SocketType.STREAM); auto addr = new UnixAddress("\0/tmp/myapp.uniqueness.sock"); try { socket.bind(addr); return true; } catch (SocketOSException e) { import core.stdc.er...
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running
Determine if only one instance is running
This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
#Delphi
Delphi
program OneInstance;   {$APPTYPE CONSOLE}   uses SysUtils, Windows;   var FMutex: THandle; begin FMutex := CreateMutex(nil, True, 'OneInstanceMutex'); if FMutex = 0 then RaiseLastOSError else begin try if GetLastError = ERROR_ALREADY_EXISTS then Writeln('Program already running. Closing...
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running
Determine if only one instance is running
This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
#Erlang
Erlang
7> erlang:register( aname, erlang:self() ). true 8> erlang:register( aname, erlang:self() ). ** exception error: bad argument in function register/2 called as register(aname,<0.42.0>)
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...
#D
D
import std.stdio, std.algorithm, std.string, std.parallelism, core.sync.mutex;   void eat(in size_t i, in string name, Mutex[] forks) { writeln(name, " is hungry."); immutable j = (i + 1) % forks.length;   // Take forks i and j. The lower one first to prevent deadlock. auto fork1 = forks[min(i, j...
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#C
C
#include <stdlib.h> #include <stdio.h> #include <time.h>   #define day_of_week( x ) ((x) == 1 ? "Sweetmorn" :\ (x) == 2 ? "Boomtime" :\ (x) == 3 ? "Pungenday" :\ (x) == 4 ? "Prickle-Prickle" :\ "Setting Orange")   #d...
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...
#Commodore_BASIC
Commodore BASIC
100 NV=0: REM NUMBER OF VERTICES 110 READ N$:IF N$<>"" THEN NV=NV+1:GOTO 110 120 NE=0: REM NUMBER OF EDGES 130 READ N1:IF N1 >= 0 THEN READ N2,W:NE=NE+1:GOTO 130 140 DIM VN$(NV-1),VD(NV-1,2): REM VERTEX NAMES AND DATA 150 DIM ED(NE-1,2): REM EDGE DATA 160 RESTORE 170 FOR I=0 TO NV-1 180 : READ VN$(I): REM VERTEX NAME ...
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...
#BQN
BQN
DSum ← +´10{⌽𝕗|⌊∘÷⟜𝕗⍟(↕1+·⌊𝕗⋆⁼1⌈⊢)} Root ← 0⊸{(×○⌊÷⟜10)◶⟨𝕨‿𝕩,(1+𝕨)⊸𝕊 Dsum⟩𝕩}   P ← •Show ⊢∾Root P 627615 P 39390 P 588225 P 393900588225
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...
#Bracmat
Bracmat
( root = sum persistence n d .  !arg:(~>9.?) |  !arg:(?n.?persistence) & 0:?sum & ( @( !n  :  ? (#%@?d&!d+!sum:?sum&~)  ? ) | root$(!sum.!persistence+1) ) ) & ( 627615 39390 588225 393900588225 10 199 ...
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 ...
#Haskell
Haskell
import Control.Arrow import Data.Array import Data.LazyArray import Data.List (unfoldr) import Data.Tuple import Text.Printf   -- The multiplicative persistence (MP) and multiplicative digital root (MDR) of -- the argument. mpmdr :: Integer -> (Int, Integer) mpmdr = (length *** head) . span (> 9) . iterate (product . d...
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...
#Wren
Wren
import "graphics" for Canvas, Color import "dome" for Window   class Game { static init() { Window.title = "Dragon curve" Window.resize(800, 600) Canvas.resize(800, 600) var iter = 14 var turns = getSequence(iter) var startingAngle = -iter * Num.pi / 4 var side...
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...
#EchoLisp
EchoLisp
  (require 'hash) (require' amb)   ;; ;; Solver ;;   (define (dwelling-puzzle context names floors H) ;; each amb calls gives a floor to a name (for ((name names)) (hash-set H name (amb context floors))) ;; They live on different floors. (amb-require (distinct? (amb-choices context))) (constraints floors ...
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 ...
#D
D
void main() { import std.stdio, std.numeric;   [1.0, 3.0, -5.0].dotProduct([4.0, -2.0, -1.0]).writeln; }
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...
#Python
Python
  from collections import deque   some_list = deque(["a", "b", "c"]) print(some_list)   some_list.appendleft("Z") print(some_list)   for value in reversed(some_list): print(value)  
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...
#jq
jq
# To take advantage of gojq's arbitrary-precision integer arithmetic: def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);   # Input: an array (aka: counts) def throwDie($nSides; $nDice; $s): if $nDice == 0 then .[$s] += 1 else reduce range(1; $nSides + 1) as $i (.; throwDie($nSides; $nDice-1; $s...
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...
#Julia
Julia
play(ndices::Integer, nfaces::Integer) = (nfaces, ndices) ∋ 0 ? 0 : sum(rand(1:nfaces) for i in 1:ndices)   simulate(d1::Integer, f1::Integer, d2::Integer, f2::Integer; nrep::Integer=1_000_000) = mean(play(d1, f1) > play(d2, f2) for _ in 1:nrep)   println("\nPlayer 1: 9 dices, 4 faces\nPlayer 2: 6 dices, 6 faces\nP...
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running
Determine if only one instance is running
This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
#FreeBASIC
FreeBASIC
Shell("tasklist > temp.txt")   Dim linea As String Open "temp.txt" For Input As #1 Do While Not Eof(1) Line Input #1, linea If Instr(linea, "fbc.exe") = 0 Then Print "Task is Running" : Exit Do Loop Close #1 Shell("del temp.txt") Sleep
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running
Determine if only one instance is running
This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
#Go
Go
package main   import ( "fmt" "net" "time" )   const lNet = "tcp" const lAddr = ":12345"   func main() { if _, err := net.Listen(lNet, lAddr); err != nil { fmt.Println("an instance was already running") return } fmt.Println("single instance started") time.Sleep(10 * time.Seco...
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running
Determine if only one instance is running
This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
#Haskell
Haskell
import Control.Concurrent import System.Directory (doesFileExist, getAppUserDataDirectory, removeFile) import System.IO (withFile, Handle, IOMode(WriteMode), hPutStr)   oneInstance :: IO () oneInstance = do -- check if file "$HOME/.myapp.lock" exists user <- getAppUserDataDirectory "myapp.lock" locked <...
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...
#Delphi
Delphi
  program dining_philosophers; uses Classes, SysUtils, SyncObjs;   const PHIL_COUNT = 5; LIFESPAN = 7; DELAY_RANGE = 950; DELAY_LOW = 50; PHIL_NAMES: array[1..PHIL_COUNT] of string = ('Aristotle', 'Kant', 'Spinoza', 'Marx', 'Russell'); type TFork = TCriticalSection; // TPhilosopher =...
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#C.23
C#
using System;   public static class DiscordianDate { static readonly string[] seasons = { "Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath" }; static readonly string[] weekdays = { "Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange" }; static readonly string[] apostles = ...
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...
#Common_Lisp
Common Lisp
  (defparameter *w* '((a (a b . 7) (a c . 9) (a f . 14)) (b (b c . 10) (b d . 15)) (c (c d . 11) (c f . 2)) (d (d e . 6)) (e (e f . 9))))   (defvar *r* nil)   (defun dijkstra-short-path (i g) (setf *r* nil) (paths i g 0 `(,i)) (car (sor...
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...
#C
C
#include <stdio.h>   int droot(long long int x, int base, int *pers) { int d = 0; if (pers) for (*pers = 0; x >= base; x = d, (*pers)++) for (d = 0; x; d += x % base, x /= base); else if (x && !(d = x % (base - 1))) d = base - 1;   return d; }   int main(void) { int i, d, pers; long long x[] = {627615, 39...
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 ...
#Icon_and_Unicon
Icon and Unicon
procedure main(A) write(right("n",8)," ",right("MP",8),right("MDR",5)) every r := mdr(n := 123321|7739|893|899998) do write(right(n,8),":",right(r[1],8),right(r[2],5)) write() write(right("MDR",5)," ","[n0..n4]") every m := 0 to 9 do { writes(right(m,5),": [") every writes(r...
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...
#X86_Assembly
X86 Assembly
.model tiny .code .486 org 100h ;assume ax=0, bx=0, sp=-2 start: mov al, 13h ;(ah=0) set 320x200 video graphics mode int 10h push 0A000h pop es mov si, 8000h ;color   mov cx, 75*256+100 ;coordi...
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...
#Elixir
Elixir
defmodule Dinesman do def problem do names = ~w( Baker Cooper Fletcher Miller Smith )a predicates = [fn(c)-> :Baker != List.last(c) end, fn(c)-> :Cooper != List.first(c) end, fn(c)-> :Fletcher != List.first(c) && :Fletcher != List.last(c) end, fn(c)-> floo...
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 ...
#Dart
Dart
num dot(List<num> A, List<num> B){ if (A.length != B.length){ throw new Exception('Vectors must be of equal size'); } num result = 0; for (int i = 0; i < A.length; i++){ result += A[i] * B[i]; } return result; }   void main(){ var l = [1,3,-5]; var k = [4,-2,-1]; print(dot(l,k)); }
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 ...
#Delphi
Delphi
program Project1;   {$APPTYPE CONSOLE}   type doublearray = array of Double;   function DotProduct(const A, B : doublearray): Double; var I: integer; begin assert (Length(A) = Length(B), 'Input arrays must be the same length'); Result := 0; for I := 0 to Length(A) - 1 do Result := Result + (A[I] * B[I]); en...
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...
#Racket
Racket
  #lang racket (define-struct dlist (head tail) #:mutable #:transparent) (define-struct dlink (content prev next) #:mutable #:transparent)   (define (insert-between dlist before after data)  ; Insert a fresh link containing DATA after existing link  ; BEFORE if not nil and before existing link AFTER if not nil (de...
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...
#Kotlin
Kotlin
// version 1.1.2   fun throwDie(nSides: Int, nDice: Int, s: Int, counts: IntArray) { if (nDice == 0) { counts[s]++ return } for (i in 1..nSides) throwDie(nSides, nDice - 1, s + i, counts) }   fun beatingProbability(nSides1: Int, nDice1: Int, nSides2: Int, nDice2: Int): Double { val len1 ...
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running
Determine if only one instance is running
This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
#Icon_and_Unicon
Icon and Unicon
procedure main(A) if not open(":"||54321,"na") then stop("Already running") repeat {} # busy loop end
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running
Determine if only one instance is running
This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
#Java
Java
import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.UnknownHostException;   public class SingletonApp { private static final int PORT = 65000; // random large port number private static ServerSocket s;   // static initializer static { try { ...
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...
#E
E
  (lib 'tasks)   (define names #(Aristotle Kant Spinoza Marx Russell)) (define abouts #("Wittgenstein" "the nature of the World" "Kant" "starving" "spaghettis" "the essence of things" "Ω" "📞" "⚽️" "🍅" "🌿" "philosophy" "💔" "👠" "rosetta code" "his to-do list" )) (define (about) (format "thinking about %a...
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#C.2B.2B
C++
  #include <iostream> #include <algorithm> #include <vector> #include <sstream> #include <iterator> using namespace std; class myTuple { public: void set( int a, int b, string c ) { t.first.first = a; t.first.second = b; t.second = c; } bool operator == ( pair<int, int> p ) { return p.first == t.first.first && ...
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...
#D
D
import std.stdio, std.typecons, std.algorithm, std.container;   alias Vertex = string; alias Weight = int;   struct Neighbor { Vertex target; Weight weight; }   alias AdjacencyMap = Neighbor[][Vertex];   pure dijkstraComputePaths(Vertex source, Vertex target, AdjacencyMap adjacencyMap){ Weight[Vertex] minDi...