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/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...
#Crystal
Crystal
def digital_root(n : Int, base = 10) : Int max_single_digit = base - 1 n = n.abs if n > max_single_digit n = 1 + (n - 1) % max_single_digit end n end   puts digital_root 627615 puts digital_root 39390 puts digital_root 588225 puts digital_root 7, base: 3
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 ...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
  ClearAll[mdr, mp, nums]; mdr[n_] := NestWhile[Times @@ IntegerDigits[#] &, n, # > 9 &]; mp[n_] := Length@NestWhileList[Times @@ IntegerDigits[#] &, n, # > 9 &] - 1; TableForm[{#, mdr[#], mp[#]} & /@ {123321, 7739, 893, 899998}, TableHeadings -> {None, {"Number", "MDR", "MP"}}] nums = ConstantArray[{}, 10]; For[i = ...
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...
#Haskell
Haskell
import Data.List (permutations) import Control.Monad (guard)   dinesman :: [(Int,Int,Int,Int,Int)] dinesman = do -- baker, cooper, fletcher, miller, smith are integers representing -- the floor that each person lives on, from 1 to 5   -- Baker, Cooper, Fletcher, Miller, and Smith live on different floors -- of...
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 ...
#Elixir
Elixir
defmodule Vector do def dot_product(a,b) when length(a)==length(b), do: dot_product(a,b,0) def dot_product(_,_) do raise ArgumentError, message: "Vectors must have the same length." end   defp dot_product([],[],product), do: product defp dot_product([h1|t1], [h2|t2], product), do: dot_product(t1, t2, prod...
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 ...
#Elm
Elm
dotp: List number -> List number -> Maybe number dotp a b = if List.length a /= List.length b then Nothing else Just (List.sum <| List.map2 (*) a b)   dotp [1,3,-5] [4,-2,-1])
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable
Determine if a string is squeezable
Determine if a character string is   squeezable. And if so,   squeeze the string   (by removing any number of a   specified   immediately repeated   character). This task is very similar to the task     Determine if a character string is collapsible     except that only a specified character is   squeezed   instead...
#BASIC
BASIC
10 DEFINT A-Z 20 READ N: DIM S$(N): FOR I=1 TO N: READ S$(I): NEXT 30 READ S,C$: IF S=0 THEN END 40 PRINT "Character: '";C$;"'" 50 O$=S$(S): GOSUB 200 60 I$=S$(S): GOSUB 100: GOSUB 200 70 PRINT 80 GOTO 30 100 REM -- 101 REM -- Squeeze I$ on character C$, output in O$ 102 REM -- 105 O$ = "" 110 X = INSTR(I$,C$) 120 IF X...
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable
Determine if a string is squeezable
Determine if a character string is   squeezable. And if so,   squeeze the string   (by removing any number of a   specified   immediately repeated   character). This task is very similar to the task     Determine if a character string is collapsible     except that only a specified character is   squeezed   instead...
#BCPL
BCPL
get "libhdr"   // Squeeze a string let squeeze(in, ch, out) = valof $( out%0 := 0 for i=1 to in%0 if i=1 | in%i~=ch | in%(i-1)~=ch $( out%0 := out%0 + 1 out%(out%0) := in%i $) resultis out $)   // Print string with brackets and length let brackets(s) be writef("%N: <<<%...
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array length String length Cop...
#8th
8th
: number? >n >kind ns:n n:= ;
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array length String length Cop...
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly Raspberry PI */ /* program strNumber.s */     /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc"  ...
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...
#Tcl
Tcl
package require Tcl 8.4 proc dl {_name cmd {where error} {value ""}} { upvar 1 $_name N switch -- $cmd { insert { if ![info exists N()] {set N() {"" "" 0}} set id [lindex $N() 2] lset N() 2 [incr id] switch -- $where { head { ...
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters
Determine if a string has all unique characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are unique   indicate if or which character is duplicated and where   display each string and its length   (as the strings are being ...
#11l
11l
F processString(input) [Char = Int] charMap V dup = Char("\0") V index = 0 V pos1 = -1 V pos2 = -1 L(key) input index++ I key C charMap dup = key pos1 = charMap[key] pos2 = index L.break charMap[key] = index V unique = I dup == Char("\0") {‘yes’...
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible
Determine if a string is collapsible
Determine if a character string is   collapsible. And if so,   collapse the string   (by removing   immediately repeated   characters). If a character string has   immediately repeated   character(s),   the repeated characters are to be deleted (removed),   but not the primary (1st) character(s). An   immediatel...
#APL
APL
task←{ ⍝ Collapse a string collapse←{(1,¯1↓⍵≠1⌽⍵)/⍵}   ⍝ Given a function ⍺⍺, display a string in brackets, ⍝ along with its length, and do the same for the result ⍝ of applying ⍺⍺ to the string. display←{ bracket←{(⍕⍴⍵),' «««',⍵,'»»»'} ↑(⊂bracket ⍵),(⊂bracket ⍺⍺ ⍵) }   ⍝ Strings fro...
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible
Determine if a string is collapsible
Determine if a character string is   collapsible. And if so,   collapse the string   (by removing   immediately repeated   characters). If a character string has   immediately repeated   character(s),   the repeated characters are to be deleted (removed),   but not the primary (1st) character(s). An   immediatel...
#Arturo
Arturo
lines: [ {::} {:"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln :} {:..1111111111111111111111111111111111111111111111111111111111111117777888:} {:I never give 'em hell, I just tell the truth, and they think it's hell. :} {: -...
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...
#Python
Python
from itertools import product   def gen_dict(n_faces, n_dice): counts = [0] * ((n_faces + 1) * n_dice) for t in product(range(1, n_faces + 1), repeat=n_dice): counts[sum(t)] += 1 return counts, n_faces ** n_dice   def beating_probability(n_sides1, n_dice1, n_sides2, n_dice2): c1, p1 = gen_dict(n...
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters
Determine if a string has all the same characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are the same   indicate if or which character is different from the previous character   display each string and its length   (as the...
#Arturo
Arturo
strings: [ "", " ", "2", "333", ".55", "tttTTT", "4444 444k", "pépé", "🐶🐶🐺🐶", "🎄🎄🎄🎄" ]   allSameChars?: function [str][ if empty? str -> return ø current: first str loop.with:'i str 'ch [ if ch <> current -> return i ] return ø ]   loop strings 's [ prints ["\"" ++ s...
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters
Determine if a string has all the same characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are the same   indicate if or which character is different from the previous character   display each string and its length   (as the...
#AutoHotkey
AutoHotkey
testCases := ["", " ", "2", "333", ".55", "tttTTT", "4444 4444k"] for key, str in testCases { MsgBox % "Examining `'" str "`' which has a length of " StrLen(str) ":`n" if (StrLen(str) == 0) or (StrLen(str) == 1) { MsgBox % " All characters in the string are the same.`n" continue } firstChar := SubStr(str, 1,...
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.
#Ring
Ring
  # Project : Determine if only one instance is running   task = "ringw.exe" taskname = "tasklist.txt" remove(taskname) system("tasklist >> tasklist.txt") fp = fopen(taskname,"r") tasks = read("tasklist.txt") counttask = count(tasks,task) if counttask > 0 see task + " running in " + counttask + " instances" + nl els...
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.
#Ruby
Ruby
def main puts "first instance" sleep 20 puts :done end   if $0 == __FILE__ if File.new(__FILE__).flock(File::LOCK_EX | File::LOCK_NB) main else raise "another instance of this program is running" end end   __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.
#Run_BASIC
Run BASIC
if instr(shell$("tasklist"),"rbp.exe") <> 0 then print "Task is Running"
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.
#Rust
Rust
use std::net::TcpListener;   fn create_app_lock(port: u16) -> TcpListener { match TcpListener::bind(("0.0.0.0", port)) { Ok(socket) => { socket }, Err(_) => { panic!("Couldn't lock port {}: another instance already running?", port); } } }   fn remove_app_l...
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...
#Go
Go
package main   import ( "hash/fnv" "log" "math/rand" "os" "time" )   // Number of philosophers is simply the length of this list. // It is not otherwise fixed in the program. var ph = []string{"Aristotle", "Kant", "Spinoza", "Marx", "Russell"}   const hunger = 3 // number of times eac...
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#Fortran
Fortran
  program discordianDate implicit none ! Declare variables character(32) :: arg character(15) :: season,day,holyday character(80) :: Output,fmt1,fmt2,fmt3 character(2) :: dayfix,f1,f2,f3,f4 integer :: i,j,k,daysofyear,dayofweek,seasonnum,yold,dayofseason,t1,t2,t3 integer,dimension(8) :: ...
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...
#Icon_and_Unicon
Icon and Unicon
procedure main(A) graph := getGraph() repeat { writes("What is the start node? ") start := \graph.nodes[read()] | stop() writes("What is the finish node? ") finish := read() | stop()   QMouse(graph,start,finish) waitForCompletion() # block until all quantum mice h...
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...
#D
D
import std.stdio, std.typecons, std.conv, std.bigint, std.math, std.traits;   Tuple!(uint, Unqual!T) digitalRoot(T)(in T inRoot, in uint base) pure nothrow in { assert(base > 1); } body { Unqual!T root = inRoot.abs; uint persistence = 0; while (root >= base) { auto num = root; roo...
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 ...
#Nim
Nim
import strutils, sequtils, sugar   proc mdroot(n: int): tuple[mp, mdr: int] = var mdr = @[n] while mdr[mdr.high] > 9: var n = 1 for dig in $mdr[mdr.high]: n *= parseInt($dig) mdr.add n (mdr.high, mdr[mdr.high])   for n in [123321, 7739, 893, 899998]: echo align($n, 6)," ",mdroot(n) echo ""   v...
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...
#Icon_and_Unicon
Icon and Unicon
invocable all global nameL, nameT, rules   procedure main() # Dinesman   nameT := table() nameL := ["Baker", "Cooper", "Fletcher", "Miller", "Smith"] rules := [ [ distinct ], [ "~=", "Baker", top() ], [ "~=", "Cooper", bottom() ], [ "~=", "Fletcher", top...
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 ...
#Emacs_Lisp
Emacs Lisp
(defun dot-product (v1 v2) (let ((res 0)) (dotimes (i (length v1)) (setq res (+ (* (elt v1 i) (elt v2 i)) res))) res))   (dot-product [1 2 3] [1 2 3]) ;=> 14 (dot-product '(1 2 3) '(1 2 3)) ;=> 14
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable
Determine if a string is squeezable
Determine if a character string is   squeezable. And if so,   squeeze the string   (by removing any number of a   specified   immediately repeated   character). This task is very similar to the task     Determine if a character string is collapsible     except that only a specified character is   squeezed   instead...
#C
C
  #include<string.h> #include<stdlib.h> #include<stdio.h>   #define COLLAPSE 0 #define SQUEEZE 1   typedef struct charList{ char c; struct charList *next; } charList;   /* Implementing strcmpi, the case insensitive string comparator, as it is not part of the C Standard Library.   Comment this out if testing on ...
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap
Determine if two triangles overlap
Determining if two triangles in the same plane overlap is an important topic in collision detection. Task Determine which of these pairs of triangles overlap in 2D:   (0,0),(5,0),(0,5)     and   (0,0),(5,0),(0,6)   (0,0),(0,5),(5,0)     and   (0,0),(0,5),(5,0)   (0,0),(5,0),(0,5)     and   (-10,0),(-5,0),(-1,6)...
#11l
11l
T Triangle (Float, Float) p1, p2, p3   F (p1, p2, p3) .p1 = p1 .p2 = p2 .p3 = p3   F String() R ‘Triangle: #., #., #.’.format(.p1, .p2, .p3)   F.const det2D() R .p1[0] * (.p2[1] - .p3[1]) + .p2[0] * (.p3[1] - .p1[1]) + .p3[0] * (.p1[1] - .p2[1])   F checkTriWinding(...
http://rosettacode.org/wiki/Determinant_and_permanent
Determinant and permanent
For a given matrix, return the determinant and the permanent of the matrix. The determinant is given by det ( A ) = ∑ σ sgn ⁡ ( σ ) ∏ i = 1 n M i , σ i {\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}} while the permanent is given by ...
#11l
11l
F s_permutations(seq) V items = [[Int]()] L(j) seq [[Int]] new_items L(item) items V i = L.index I i % 2 new_items [+]= (0 .. item.len).map(i -> @item[0 .< i] [+] [@j] [+] @item[i ..]) E new_items [+]= (item.len .< -1).step(-1).map(i -> @item[0 .< i] ...
http://rosettacode.org/wiki/Detect_division_by_zero
Detect division by zero
Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
#68000_Assembly
68000 Assembly
  1 0 n:/ Inf? . cr  
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array length String length Cop...
#Action.21
Action!
INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit   BYTE FUNC AreEqual(CHAR ARRAY a,b) BYTE i   IF a(0)#b(0) THEN RETURN (0) FI FOR i=1 to a(0) DO IF a(i)#b(i) THEN RETURN (0) FI OD RETURN (1)   BYTE FUNC IsNumeric(CHAR ARRAY s) CHAR ARRAY tmp(20) INT i CARD c REAL r   i=ValI(s) ...
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array length String length Cop...
#ActionScript
ActionScript
public function isNumeric(num:String):Boolean { return !isNaN(parseInt(num)); }
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...
#Visual_Basic_.NET
Visual Basic .NET
Public Class DoubleLinkList(Of T) Private m_Head As Node(Of T) Private m_Tail As Node(Of T)   Public Sub AddHead(ByVal value As T) Dim node As New Node(Of T)(Me, value)   If m_Head Is Nothing Then m_Head = Node m_Tail = m_Head Else node.Next = m_Head ...
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters
Determine if a string has all unique characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are unique   indicate if or which character is duplicated and where   display each string and its length   (as the strings are being ...
#Action.21
Action!
PROC PrintBH(BYTE a) BYTE ARRAY hex=['0 '1 '2 '3 '4 '5 '6 '7 '8 '9 'A 'B 'C 'D 'E 'F]   Put(hex(a RSH 4)) Put(hex(a&$0F)) RETURN   PROC Test(CHAR ARRAY s) BYTE i,j,n,pos1,pos2   pos1=0 pos2=0 n=s(0)-1 IF n=255 THEN n=0 FI FOR i=1 TO n DO FOR j=i+1 TO s(0) DO IF s(j)=s(i) THEN pos...
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters
Determine if a string has all unique characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are unique   indicate if or which character is duplicated and where   display each string and its length   (as the strings are being ...
#Ada
Ada
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Ada.Text_IO; use Ada.Text_IO; procedure Test_All_Chars_Unique is procedure All_Chars_Unique (S : in String) is begin Put_Line ("Input = """ & S & """, length =" & S'Length'Image); for I in S'First .. S'Last - 1 loop for J in I + 1 .. S'L...
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible
Determine if a string is collapsible
Determine if a character string is   collapsible. And if so,   collapse the string   (by removing   immediately repeated   characters). If a character string has   immediately repeated   character(s),   the repeated characters are to be deleted (removed),   but not the primary (1st) character(s). An   immediatel...
#AutoHotkey
AutoHotkey
collapsible_string(str){ for i, ch in StrSplit(str){ if (ch <> prev) res .= ch prev := ch } return "original string:`t" StrLen(str) " characters`t«««" str "»»»`nresultant string:`t" StrLen(res) " characters`t«««" res "»»»" }
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible
Determine if a string is collapsible
Determine if a character string is   collapsible. And if so,   collapse the string   (by removing   immediately repeated   characters). If a character string has   immediately repeated   character(s),   the repeated characters are to be deleted (removed),   but not the primary (1st) character(s). An   immediatel...
#AWK
AWK
  # syntax: GAWK -f DETERMINE_IF_A_STRING_IS_COLLAPSIBLE.AWK BEGIN { for (i=1; i<=9; i++) { for (j=1; j<=i; j++) { arr[0] = arr[0] i } } arr[++n] = "" arr[++n] = "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " arr[++n] = "..111111111111111111111111111...
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...
#R
R
probability <- function(facesCount1, diceCount1, facesCount2, diceCount2) { mean(replicate(10^6, sum(sample(facesCount1, diceCount1, replace = TRUE)) > sum(sample(facesCount2, diceCount2, replace = TRUE)))) } cat("Player 1's probability of victory is", probability(4, 9, 6, 6), "in the first game and", probability...
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...
#Racket
Racket
#lang racket   (define probs# (make-hash))   (define (NdD n d) (hash-ref! probs# (cons n d) (λ () (cond [(= n 0) ; every chance of nothing! (hash 0 1)] [else (for*/fold ((hsh (hash))) (((i p) (in-hash (NdD (sub1 n) d))) (r (in-range 1 (+ d 1)))) (hash-update hsh (+ r...
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters
Determine if a string has all the same characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are the same   indicate if or which character is different from the previous character   display each string and its length   (as the...
#AWK
AWK
  # syntax: GAWK -f DETERMINE_IF_A_STRING_HAS_ALL_THE_SAME_CHARACTERS.AWK BEGIN { for (i=0; i<=255; i++) { ord_arr[sprintf("%c",i)] = i } # build array[character]=ordinal_value n = split(", ,2,333,.55,tttTTT,4444 444k",arr,",") for (i in arr) { width = max(width,length(arr[i])) } width += 2 ...
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.
#Scala
Scala
import java.io.IOException import java.net.{InetAddress, ServerSocket}   object SingletonApp extends App { private val port = 65000   try { val s = new ServerSocket(port, 10, InetAddress.getLocalHost) } catch { case _: IOException => // port taken, so app is already running println("Applicat...
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.
#Sidef
Sidef
# For this to work, you need to explicitly # store the returned fh inside a variable. var fh = File(__FILE__).open_r   # Now call the flock() method on it fh.flock(File.LOCK_EX | File.LOCK_NB) -> || die "I'm already running!"   # Your code here... say "Running..." Sys.sleep(20) say 'Done!'
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.
#Swift
Swift
import Foundation   let globalCenter = NSDistributedNotificationCenter.defaultCenter() let time = NSDate().timeIntervalSince1970   globalCenter.addObserverForName("OnlyOne", object: nil, queue: NSOperationQueue.mainQueue()) {not in if let senderTime = not.userInfo?["time"] as? NSTimeInterval where senderTime != tim...
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.
#Tcl
Tcl
package require Tcl 8.6 try { # Pick a port number based on the name of the main script executing socket -server {apply {{chan args} {close $chan}}} -myaddr localhost \ [expr {1024 + [zlib crc32 [file normalize $::argv0]] % 30000}] } trap {POSIX EADDRINUSE} {} { # Generate a nice error message ...
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...
#Groovy
Groovy
import groovy.transform.Canonical   import java.util.concurrent.locks.Lock import java.util.concurrent.locks.ReentrantLock   @Canonical class Fork { String name Lock lock = new ReentrantLock()   void pickUp(String philosopher) { lock.lock() println " $philosopher picked up $name" }   ...
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#FreeBASIC
FreeBASIC
#Include "datetime.bi"   meses: Data "Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath" dias_laborales: Data "Setting Orange", "Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle" dias_previos_al_1er_mes: ' ene feb mar abr may jun jul ago sep oct nov dic Data 0, 31, 59, 90, 120, 151, 181, 212, ...
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...
#J
J
  NB. verbs and adverb parse_table=: ;:@:(LF&= [;._2 -.&CR) mp=: $:~ :(+/ .*) NB. matrix product min=: <./ NB. minimum Index=: (i.`)(`:6) NB. Index adverb   dijkstra=: dyad define 'LINK WEIGHT'=. , (0 _ ,. 2) <;.3 y 'SOURCE SINK'=. |: LINK F...
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...
#Dc
Dc
?[10~rd10<p]sp[+z1<q]sq[lpxlqxd10<r]dsrxp
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...
#DCL
DCL
$ x = p1 $ count = 0 $ sum = x $ loop1: $ length = f$length( x ) $ if length .eq. 1 then $ goto done $ i = 0 $ sum = 0 $ loop2: $ digit = f$extract( i, 1, x ) $ sum = sum + digit $ i = i + 1 $ if i .lt. length then $ goto loop2 $ x = f$string( sum ) $ count = count + 1 $ goto loop1 $ done: $ write sys$o...
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 ...
#PARI.2FGP
PARI/GP
a(n)=my(i);while(n>9,n=factorback(digits(n));i++);[i,n]; apply(a, [123321, 7739, 893, 899998]) v=vector(10,i,[]); forstep(n=0,oo,1, t=a(n)[2]+1; if(#v[t]<5,v[t]=concat(v[t],n); if(vecmin(apply(length,v))>4, return(v))))
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...
#J
J
possible=: ((i.!5) A. i.5) { 'BCFMS'
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 ...
#Erlang
Erlang
dotProduct(A,B) when length(A) == length(B) -> dotProduct(A,B,0); dotProduct(_,_) -> erlang:error('Vectors must have the same length.').   dotProduct([H1|T1],[H2|T2],P) -> dotProduct(T1,T2,P+H1*H2); dotProduct([],[],P) -> P.   dotProduct([1,3,-5],[4,-2,-1]).
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable
Determine if a string is squeezable
Determine if a character string is   squeezable. And if so,   squeeze the string   (by removing any number of a   specified   immediately repeated   character). This task is very similar to the task     Determine if a character string is collapsible     except that only a specified character is   squeezed   instead...
#C.23
C#
using System; using static System.Linq.Enumerable;   public class Program { static void Main() { SqueezeAndPrint("", ' '); SqueezeAndPrint("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-'); SqueezeAndPrint("..1111111111111111111111111111111111111111111111...
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap
Determine if two triangles overlap
Determining if two triangles in the same plane overlap is an important topic in collision detection. Task Determine which of these pairs of triangles overlap in 2D:   (0,0),(5,0),(0,5)     and   (0,0),(5,0),(0,6)   (0,0),(0,5),(5,0)     and   (0,0),(0,5),(5,0)   (0,0),(5,0),(0,5)     and   (-10,0),(-5,0),(-1,6)...
#Ada
Ada
  WITH Ada.Text_IO; USE Ada.Text_IO;   PROCEDURE Main IS TYPE Vertex IS MOD 3; TYPE Point IS ARRAY (0 .. 1) OF Float; TYPE Triangle IS ARRAY (Vertex) OF Point; TYPE Triangle_Vertices IS ARRAY (0 .. 5) OF Float;   FUNCTION Same_Side (A, B, M, N : Point) RETURN Boolean IS FUNCTION Aff (U : Point) RET...
http://rosettacode.org/wiki/Determinant_and_permanent
Determinant and permanent
For a given matrix, return the determinant and the permanent of the matrix. The determinant is given by det ( A ) = ∑ σ sgn ⁡ ( σ ) ∏ i = 1 n M i , σ i {\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}} while the permanent is given by ...
#360_Assembly
360 Assembly
* Matrix arithmetic 13/05/2016 MATARI START STM R14,R12,12(R13) save caller's registers LR R12,R15 set R12 as base register USING MATARI,R12 notify assembler LA R11,SAVEAREA get the address of my savearea ST R13,4(...
http://rosettacode.org/wiki/Determinant_and_permanent
Determinant and permanent
For a given matrix, return the determinant and the permanent of the matrix. The determinant is given by det ( A ) = ∑ σ sgn ⁡ ( σ ) ∏ i = 1 n M i , σ i {\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}} while the permanent is given by ...
#Arturo
Arturo
printMatrix: function [m][ loop m 'row -> print map row 'val [pad to :string .format:".2f" val 6] print "--------------------------------" ]   permutations: function [arr][ d: 1 c: array.of: size arr 0 xs: new arr sign: 1   ret: new @[@[xs, sign]]   while [true][ while [d > 1][ ...
http://rosettacode.org/wiki/Detect_division_by_zero
Detect division by zero
Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
#8th
8th
  1 0 n:/ Inf? . cr  
http://rosettacode.org/wiki/Detect_division_by_zero
Detect division by zero
Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
#ABAP
ABAP
report zdiv_zero data x type i. try. x = 1 / 0. catch CX_SY_ZERODIVIDE. write 'Divide by zero.'. endtry.  
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array length String length Cop...
#Ada
Ada
package Numeric_Tests is function Is_Numeric (Item : in String) return Boolean; end Numeric_Tests;
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array length String length Cop...
#Aime
Aime
integer is_numeric(text s) { return !trap_q(alpha, s, 0); }   integer main(void) { if (!is_numeric("8192&*")) { o_text("Not numeric.\n"); } if (is_numeric("8192")) { o_text("Numeric.\n"); }   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...
#Wren
Wren
import "/llist" for DLinkedList   var dll = DLinkedList.new() for (i in 1..3) dll.add(i) System.print(dll) for (i in 1..3) dll.remove(i) System.print(dll)
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters
Determine if a string has all unique characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are unique   indicate if or which character is duplicated and where   display each string and its length   (as the strings are being ...
#ALGOL_68
ALGOL 68
BEGIN # mode to hold the positions of duplicate characters in a string # MODE DUPLICATE = STRUCT( INT original, first duplicate ); # finds the first non-unique character in s and returns its position # # and the position of the original character in a DUPLICATE # # if all characters...
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible
Determine if a string is collapsible
Determine if a character string is   collapsible. And if so,   collapse the string   (by removing   immediately repeated   characters). If a character string has   immediately repeated   character(s),   the repeated characters are to be deleted (removed),   but not the primary (1st) character(s). An   immediatel...
#BaCon
BaCon
DATA "" DATA "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " DATA "..1111111111111111111111111111111111111111111111111111111111111117777888" DATA "I never give 'em hell, I just tell the truth, and they think it's hell. " DATA " --- Harry S ...
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible
Determine if a string is collapsible
Determine if a character string is   collapsible. And if so,   collapse the string   (by removing   immediately repeated   characters). If a character string has   immediately repeated   character(s),   the repeated characters are to be deleted (removed),   but not the primary (1st) character(s). An   immediatel...
#BASIC
BASIC
10 READ N% 20 FOR A% = 1 TO N% 30 READ I$: GOSUB 100 40 PRINT LEN(I$); "<<<"; I$; ">>>" 50 PRINT LEN(O$); "<<<"; O$; ">>>" 55 PRINT 60 NEXT 70 END 100 REM Collapse I$ into O$ 105 IF I$="" THEN O$=I$: RETURN 110 O$=SPACE$(LEN(I$)) 120 P$=LEFT$(I$,1) 130 MID$(O$,1,1)=P$ 140 O%=2 150 FOR I%=2 TO LEN(I$) 160 C$=MID$(I$,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...
#Raku
Raku
sub likelihoods ($roll) { my ($dice, $faces) = $roll.comb(/\d+/); my @counts; @counts[$_]++ for [X+] |(1..$faces,) xx $dice; return [@counts[]:p], $faces ** $dice; }   sub beating-probability ([$roll1, $roll2]) { my (@c1, $p1) := likelihoods $roll1; my (@c2, $p2) := likelihoods $roll2; my $p...
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters
Determine if a string has all the same characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are the same   indicate if or which character is different from the previous character   display each string and its length   (as the...
#BASIC
BASIC
  10 'SAVE"SAMECHAR", A 20 DEFINT A-Z 30 DATA ""," ","2","333",".55","tttTTT","4444 444k", "FIN" 40 ' Main program cycle 50 CLS 60 PRINT "Program SameChar" 70 PRINT "Determines if a string has the same character or not." 80 PRINT 90 WHILE S$<>"FIN" 100 READ S$ 110 IF S$="FIN" THEN 150 120 GOSUB 190 ' Revision ...
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.
#TXR
TXR
;;; Define some typedefs for clear correspondence with Win32 (typedef HANDLE cptr) (typedef LPSECURITY_ATTRIBUTES cptr) (typedef WINERR (enum WINERR ERROR_SUCCESS (ERROR_ALREADY_EXISTS 183))) (typedef BOOL (enum BOOL FALSE TRUE)) (typedef LPCWSTR wstr)   ;;; More familiar spelling for null...
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.
#UNIX_Shell
UNIX Shell
  # (c) Copyright 2005 Mark Hobley # # This is free software. This file can be redistributed or modified # under the terms of version 1.2 of the GNU Free Documentation Licence # as published by the Free Software Foundation. #   singleinstance () { if [ -d $SRUNDIR ] ; then if [ -w $SRUNDIR ] ; then if ...
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.
#Visual_Basic
Visual Basic
Dim onlyInstance as Boolean onlyInstance = not App.PrevInstance
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.
#Wren
Wren
import "io" for File, FileFlags   var specialFile = "wren-exclusive._sp" var checkOneInstanceRunning = Fn.new { // attempt to create the special file with exclusive access var ff = FileFlags.create | FileFlags.exclusive File.openWithFlags(specialFile, ff) { |file| } // closes automatically if successful } ...
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...
#Haskell
Haskell
module Philosophers where   import Control.Monad import Control.Concurrent import Control.Concurrent.STM import System.Random   -- TMVars are transactional references. They can only be used in transactional actions. -- They are either empty or contain one value. Taking an empty reference fails and -- putting a value in...
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#Go
Go
package ddate   import ( "strconv" "strings" "time" )   // Predefined formats for DiscDate.Format const ( DefaultFmt = "Pungenday, Discord 5, 3131 YOLD" OldFmt = `Today is Pungenday, the 5th day of Discord in the YOLD 3131 Celebrate Mojoday` )   // Formats passed to DiscDate.Format are proty...
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...
#Java
Java
  import java.io.*; import java.util.*;   public class Dijkstra { private static final Graph.Edge[] GRAPH = { new Graph.Edge("a", "b", 7), new Graph.Edge("a", "c", 9), new Graph.Edge("a", "f", 14), new Graph.Edge("b", "c", 10), new Graph.Edge("b", "d", 15), new Graph.Edge("c", "d"...
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...
#Delphi
Delphi
  class APPLICATION   inherit ARGUMENTS   create make   feature {NONE} -- Initialization   digital_root_test_values: ARRAY [INTEGER_64] -- Test values. once Result := <<670033, 39390, 588225, 393900588225>> -- base 10 end   digital_root_expected_result: ARRAY [INTEGER_64] -- Expected result values. ...
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 ...
#Pascal
Pascal
program MultRoot; {$IFDEF FPC} {$MODE DELPHI}{$OPTIMIZATION ON,ALL}{$CODEALIGN proc=16} {$ENDIF} {$IFDEF WINDOWS} {$APPTYPE CONSOLE} {$ENDIF} uses sysutils; type tMul3Dgt = array[0..999] of Uint32; tMulRoot = record mrNum, mrMul, mrPers : Uint64; end; ...
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...
#Java
Java
import java.util.*;   class DinesmanMultipleDwelling {   private static void generatePermutations(String[] apartmentDwellers, Set<String> set, String curPermutation) { for (String s : apartmentDwellers) { if (!curPermutation.contains(s)) { String nextPermutation = curPermutation ...
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 ...
#Euphoria
Euphoria
function dotprod(sequence a, sequence b) atom sum a *= b sum = 0 for n = 1 to length(a) do sum += a[n] end for return sum end function   ? dotprod({1,3,-5},{4,-2,-1})
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable
Determine if a string is squeezable
Determine if a character string is   squeezable. And if so,   squeeze the string   (by removing any number of a   specified   immediately repeated   character). This task is very similar to the task     Determine if a character string is collapsible     except that only a specified character is   squeezed   instead...
#C.2B.2B
C++
#include <algorithm> #include <string> #include <iostream>   template<typename char_type> std::basic_string<char_type> squeeze(std::basic_string<char_type> str, char_type ch) { auto i = std::unique(str.begin(), str.end(), [ch](char_type a, char_type b) { return a == ch && b == ch; }); str.erase(i, str.e...
http://rosettacode.org/wiki/Descending_primes
Descending primes
Generate and show all primes with strictly descending decimal digits. See also OEIS:A052014 - Primes with distinct digits in descending order Related Ascending primes
#ALGOL_68
ALGOL 68
BEGIN # find all primes with strictly decreasing digits # PR read "primes.incl.a68" PR # include prime utilities # PR read "rows.incl.a68" PR # include array utilities # [ 1 : 512 ]INT primes; # there will be at most 512 (2^9) primes # ...
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap
Determine if two triangles overlap
Determining if two triangles in the same plane overlap is an important topic in collision detection. Task Determine which of these pairs of triangles overlap in 2D:   (0,0),(5,0),(0,5)     and   (0,0),(5,0),(0,6)   (0,0),(0,5),(5,0)     and   (0,0),(0,5),(5,0)   (0,0),(5,0),(0,5)     and   (-10,0),(-5,0),(-1,6)...
#ALGOL_W
ALGOL W
begin % determine if two triangles overlap % record Point ( real x, y ); record Triangle ( reference(Point) p1, p2, p3 ); procedure WritePoint ( reference(Point) value p ) ; writeon( r_w := 3, r_d := 1, r_format := "A", s_w := 0, "(", x(p), ", ", y(p), ")" ); procedure WriteTriangle ( referen...
http://rosettacode.org/wiki/Determinant_and_permanent
Determinant and permanent
For a given matrix, return the determinant and the permanent of the matrix. The determinant is given by det ( A ) = ∑ σ sgn ⁡ ( σ ) ∏ i = 1 n M i , σ i {\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}} while the permanent is given by ...
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h>   double det_in(double **in, int n, int perm) { if (n == 1) return in[0][0];   double sum = 0, *m[--n]; for (int i = 0; i < n; i++) m[i] = in[i + 1] + 1;   for (int i = 0, sgn = 1; i <= n; i++) { sum += sgn * (in[i][0] * det_in(m, n, perm)); if (i == ...
http://rosettacode.org/wiki/Detect_division_by_zero
Detect division by zero
Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
#Ada
Ada
-- Divide By Zero Detection   with Ada.Text_Io; use Ada.Text_Io; with Ada.Float_Text_Io; use Ada.Float_Text_Io; with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;   procedure Divide_By_Zero is Fnum : Float := 1.0; Fdenom : Float := 0.0; Fresult : Float; Inum : Integer := 1; Idenom : Integer := 0; Ires...
http://rosettacode.org/wiki/Detect_division_by_zero
Detect division by zero
Task Write a function to detect a   divide by zero error   without checking if the denominator is zero.
#Aime
Aime
integer divide(integer n, integer d) { return n / d; }   integer can_divide(integer n, integer d) { return !trap(divide, n, d); }   integer main(void) { if (!can_divide(9, 0)) { o_text("Division by zero.\n"); }   return 0; }
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array length String length Cop...
#ALGOL_68
ALGOL 68
PROC is numeric = (REF STRING string) BOOL: ( BOOL out := TRUE; PROC call back false = (REF FILE f)BOOL: (out:= FALSE; TRUE);   FILE memory; associate(memory, string); on value error(memory, call back false); on logical file end(memory, call back false);   UNION (INT, REAL, COMPL) numeric:=0.0; # use a ...
http://rosettacode.org/wiki/Doubly-linked_list/Definition
Doubly-linked list/Definition
Define the data structure for a complete Doubly Linked List. The structure should support adding elements to the head, tail and middle of the list. The structure should not allow circular loops See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definitio...
#zkl
zkl
class Node{ fcn init(_value,_prev=Void,_next=Void) { var value=_value, prev=_prev, next=_next; } fcn toString{ value.toString() } fcn append(value){ // loops not allowed: create a new Node b,c := Node(value,self,next),next; next=b; if(c) c.prev=b; b } fcn delete{ if(...
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters
Determine if a string has all unique characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are unique   indicate if or which character is duplicated and where   display each string and its length   (as the strings are being ...
#AppleScript
AppleScript
use AppleScript version "2.4" use framework "Foundation" use scripting additions   on run script showSource on |λ|(s) quoted("'", s) & " (" & length of s & ")" end |λ| end script   script showDuplicate on |λ|(mb) script go on |λ|(tpl) ...
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible
Determine if a string is collapsible
Determine if a character string is   collapsible. And if so,   collapse the string   (by removing   immediately repeated   characters). If a character string has   immediately repeated   character(s),   the repeated characters are to be deleted (removed),   but not the primary (1st) character(s). An   immediatel...
#BCPL
BCPL
get "libhdr"   // Collapse a string let collapse(in, out) = valof $( let o = 0 for i = 1 to in%0 unless i>1 & in%i = in%(i-1) $( o := o + 1 out%o := in%i $) out%0 := o resultis out $)   // Print string with brackets and length let brackets(s) be writef("%N: <<<%S>>>...
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible
Determine if a string is collapsible
Determine if a character string is   collapsible. And if so,   collapse the string   (by removing   immediately repeated   characters). If a character string has   immediately repeated   character(s),   the repeated characters are to be deleted (removed),   but not the primary (1st) character(s). An   immediatel...
#Bracmat
Bracmat
( colapse = previous . str $ ( vap $ ( ( = .  !arg:!previous& | !arg:?previous ) . !arg ) ) ) & ( testcolapse = len . (len=.@(!arg:? [?arg)&!arg) & out$(str$(««« !arg "»»» " len$!arg)) & ...
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible
Determine if a string is collapsible
Determine if a character string is   collapsible. And if so,   collapse the string   (by removing   immediately repeated   characters). If a character string has   immediately repeated   character(s),   the repeated characters are to be deleted (removed),   but not the primary (1st) character(s). An   immediatel...
#C
C
  #include<string.h> #include<stdlib.h> #include<stdio.h>   #define COLLAPSE 0 #define SQUEEZE 1   typedef struct charList{ char c; struct charList *next; } charList;   /* Implementing strcmpi, the case insensitive string comparator, as it is not part of the C Standard Library.   Comment this out if testing on ...
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...
#REXX
REXX
/* REXX */ Numeric Digits 30 Call test '9 4 6 6' Call test '5 10 6 7' Exit test: Parse Arg w1 s1 w2 s2 plist1=pp(w1,s1) p1.=0 Do x=w1 To w1*s1 Parse Var plist1 p1.x plist1 End plist2=pp(w2,s2) p2.=0 Do x=w2 To w2*s2 Parse Var plist2 p2.x plist2 End p2low.=0 Do x=w1 To w1*s1 Do y=0 To x-1 p2low.x=p2low.x+p...
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters
Determine if a string has all the same characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are the same   indicate if or which character is different from the previous character   display each string and its length   (as the...
#BCPL
BCPL
get "libhdr"   let diffchar(s) = valof $( for i=2 to s%0 unless s%i = s%1 resultis i resultis 0 $)   let show(s) be $( let i = diffchar(s) writef("*"%S*" (length %N): ", s, s%0) test i=0 do writes("all the same.*N") or writef("'%C' at index %N.*N", s%i, i) $)   let start() be $( s...
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters
Determine if a string has all the same characters
Task Given a character string   (which may be empty, or have a length of zero characters):   create a function/procedure/routine to:   determine if all the characters in the string are the same   indicate if or which character is different from the previous character   display each string and its length   (as the...
#C
C
  #include<string.h> #include<stdio.h>   int main(int argc,char** argv) { int i,len; char reference;   if(argc>2){ printf("Usage : %s <Test String>\n",argv[0]); return 0; }   if(argc==1||strlen(argv[1])==1){ printf("Input string : \"%s\"\nLength : %d\nAll characters are ident...
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...
#Icon_and_Unicon
Icon and Unicon
global forks, names   procedure main(A) names := ["Aristotle","Kant","Spinoza","Marks","Russell"] write("^C to terminate") nP := *names forks := [: |mutex([])\nP :] every p := !nP do thread philosopher(p) delay(-1) end   procedure philosopher(n) f1 := forks[min(n, n%*forks+1)] f2 := fork...
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#Haskell
Haskell
import Data.Time (isLeapYear) import Data.Time.Calendar.MonthDay (monthAndDayToDayOfYear) import Text.Printf (printf)   type Year = Integer type Day = Int type Month = Int   data DDate = DDate Weekday Season Day Year | StTibsDay Year deriving (Eq, Ord)   data Season = Chaos | Discord ...
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...
#JavaScript
JavaScript
  const dijkstra = (edges,source,target) => { const Q = new Set(), prev = {}, dist = {}, adj = {}   const vertex_with_min_dist = (Q,dist) => { let min_distance = Infinity, u = null   for (let v of Q) { if (dist[v] < min_distance) { ...
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...
#Eiffel
Eiffel
  class APPLICATION   inherit ARGUMENTS   create make   feature {NONE} -- Initialization   digital_root_test_values: ARRAY [INTEGER_64] -- Test values. once Result := <<670033, 39390, 588225, 393900588225>> -- base 10 end   digital_root_expected_result: ARRAY [INTEGER_64] -- Expected result values. ...
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 ...
#Perl
Perl
use warnings; use strict;   sub mdr { my $n = shift; my($count, $mdr) = (0, $n); while ($mdr > 9) { my($m, $dm) = ($mdr, 1); while ($m) { $dm *= $m % 10; $m = int($m/10); } $mdr = $dm; $count++; } ($count, $mdr); }   print "Number: (MP, MDR)\n====== =========\n"; foreach my $n...
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...
#JavaScript
JavaScript
(() => { 'use strict';   // concatMap :: (a -> [b]) -> [a] -> [b] const concatMap = (f, xs) => [].concat.apply([], xs.map(f));   // range :: Int -> Int -> [Int] const range = (m, n) => Array.from({ length: Math.floor(n - m) + 1 }, (_, i) => m + i);   // and :: [Bool] ...
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 ...
#F.23
F#
let dot_product (a:array<'a>) (b:array<'a>) = if Array.length a <> Array.length b then failwith "invalid argument: vectors must have the same lengths" Array.fold2 (fun acc i j -> acc + (i * j)) 0 a b