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/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 ...
#Maxima
Maxima
a: matrix([2, 9, 4], [7, 5, 3], [6, 1, 8])$   determinant(a); -360   permanent(a); 900
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 ...
#.D0.9C.D0.9A-61.2F52
МК-61/52
П4 ИПE П2 КИП0 ИП0 П1 С/П ИП4 / КП2 L1 06 ИПE П3 ИП0 П1 Сx КП2 L1 17 ИП0 ИП2 + П1 П2 ИП3 - x#0 34 С/П ПП 80 БП 21 КИП0 ИП4 С/П КИП2 - * П4 ИП0 П3 x#0 35 Вx С/П КИП2 - <-> / КП1 L3 45 ИП1 ИП0 + П3 ИПE П1 П2 КИП1 /-/ ПП 80 ИП3 + П3 ИП1 - x=0 61 ИП0 П1 КИП3 КП2 L1 74 БП 12 ИП0 <-> ^ КИП3 * КИП1 + КП2 -> L0 82 -> П0 В/О
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.
#Haskell
Haskell
import qualified Control.Exception as C check x y = C.catch (x `div` y `seq` return False) (\_ -> return True)
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...
#ERRE
ERRE
  PROGRAM NUMERIC   PROCEDURE IS_NUMERIC(S$->ANS%) LOCAL T1,T1$ T1=VAL(S$) T1$=STR$(T1) ANS%=(T1$=S$) OR T1$=" "+S$ END PROCEDURE   BEGIN PRINT(CHR$(12);) INPUT("Enter a string",S$) IS_NUMERIC(S$->ANS%) IF ANS% THEN PRINT("is num") ELSE PRINT("not num") END PROGRAM  
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...
#Euphoria
Euphoria
include get.e   function is_numeric(sequence s) sequence val val = value(s) return val[1]=GET_SUCCESS and atom(val[2]) end function
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 ...
#jq
jq
# Emit null if there is no duplicate, else [c, [ix1, ix2]] def firstDuplicate: label $out | foreach explode[] as $i ({ix: -1}; .ix += 1 | .ix as $ix | .iu = ([$i] | implode) | .[.iu] += [ $ix] ; if .[.iu]|length == 2 then [.iu, .[.iu]], break $out else empty end ) // null ;
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 ...
#Julia
Julia
arr(s) = [c for c in s] alldup(a) = filter(x -> length(x) > 1, [findall(x -> x == a[i], a) for i in 1:length(a)]) firstduplicate(s) = (a = arr(s); d = alldup(a); isempty(d) ? nothing : first(d))   function testfunction(strings) println("String | Length | All Unique | First Duplicate | Pos...
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...
#Quackery
Quackery
[ false -1 rot witheach [ 2dup = iff [ drop dip not conclude ] else nip ] drop ] is collapsible ( $ --> b )   [ [] -1 rot witheach [ 2dup = iff drop else [ nip dup dip join ] ] drop ] is collaps...
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...
#R
R
collapse_string <- function(string){   str_iterable <- strsplit(string, "")[[1]]   message(paste0("Original String: ", "<<<", string, ">>>\n", "Length: ", length(str_iterable)))   detect <- rep(TRUE, length(str_iterable))     for(i in 2:length(str_iterable)){   if(length(str_it...
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...
#Racket
Racket
#lang racket   (define (collapse text) (if (< (string-length text) 2) text (string-append (if (equal? (substring text 0 1) (substring text 1 2)) "" (substring text 0 1)) (collapse (substring text 1)))))   ; Test cases (define tcs '("" "\"If I were two-faced, would I be weari...
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...
#OCaml
OCaml
  (* Task: Determine if a string has all the same characters *)   (* Create a function that determines whether all characters in a string are identical, or returns the index of first different character.   Using the option type here to combine the functionality. *) let str_first_diff_char (s : string) : int o...
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...
#PureBasic
PureBasic
Macro Tell(Mutex, Message) ; Make a macro to easy send info back to main thread LockMutex(Mutex) LastElement(Queue()) AddElement(Queue()) Queue() = Message SignalSemaphore(Semaphore) UnlockMutex(Mutex) EndMacro   ;Set up a data structure to pass needed info into the threads Structure Thread_Paramete...
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#PowerShell
PowerShell
  function ConvertTo-Discordian ( [datetime]$GregorianDate ) { $DayOfYear = $GregorianDate.DayOfYear $Year = $GregorianDate.Year + 1166 If ( [datetime]::IsLeapYear( $GregorianDate.Year ) -and $DayOfYear -eq 60 ) { $Day = "St. Tib's Day" } Else { If ( [datetime]::IsLeapYear( $GregorianDate.Year ) -and $DayOf...
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...
#Racket
Racket
  #lang racket (require (planet jaymccarthy/dijkstra:1:2))   (define edges '([a . ((b 7)(c 9)(f 14))] [b . ((c 10)(d 15))] [c . ((d 11)(f 2))] [d . ((e 6))] [e . ((f 9))]))   (define (node-edges n) (cond [(assoc n edges) => rest] ['()])) (define edge-weight second) (define edge-end first)   (match/...
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...
#Nim
Nim
import strutils   proc droot(n: int64): auto = var x = @[n] while x[x.high] > 10: var s = 0'i64 for dig in $x[x.high]: s += parseInt("" & dig) x.add s return (x.len - 1, x[x.high])   for n in [627615'i64, 39390'i64, 588225'i64, 393900588225'i64]: let (a, d) = droot(n) echo align($n, 12)," ha...
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...
#Oforth
Oforth
: sumDigits(n, base) 0 while(n) [ n base /mod ->n + ] ;   : digitalRoot(n, base) 0 while(n 9 >) [ 1 + sumDigits(n, base) ->n ] n swap Pair new ;
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...
#REXX
REXX
/*REXX program solves the Dinesman's multiple─dwelling problem with "natural" wording.*/ names= 'Baker Cooper Fletcher Miller Smith' /*names of multiple─dwelling tenants. */ #tenants= words(names) /*the number of tenants in the building*/ floors= 5; top= floors; bottom= ...
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 ...
#Lambdatalk
Lambdatalk
  {def dotp {def dotp.r {lambda {:v1 :v2 :acc} {if {A.empty? :v1} then :acc else {dotp.r {A.rest :v1} {A.rest :v2} {+ {* {A.first :v1} {A.first :v2}} :acc}}}}} {lambda {:v1 :v2} {if {= {A.length :v1} {A.length :v2}} then {dotp.r :v1 :v2 0} else Vectors must be of equal length}}} ...
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...
#Ruby
Ruby
strings = ["", '"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/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...
#Rust
Rust
fn squeezable_string<'a>(s: &'a str, squeezable: char) -> impl Iterator<Item = char> + 'a { let mut previous = None;   s.chars().filter(move |c| match previous { Some(p) if p == squeezable && p == *c => false, _ => { previous = Some(*c); true } }) }   fn main(...
http://rosettacode.org/wiki/Deming%27s_Funnel
Deming's Funnel
W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to ...
#Swift
Swift
import Foundation   let dxs = [ -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001, -0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047, -0.095, 0.695, 0.340, ...
http://rosettacode.org/wiki/Deming%27s_Funnel
Deming's Funnel
W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to ...
#Tcl
Tcl
package require Tcl 8.6 namespace path {tcl::mathop tcl::mathfunc}   proc funnel {items rule} { set x 0.0 set result {} foreach item $items { lappend result [+ $x $item] set x [apply $rule $x $item] } return $result }   proc mean {items} { / [+ {*}$items] [double [llength $items]] } proc stdde...
http://rosettacode.org/wiki/Department_numbers
Department numbers
There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (different from each other) and mu...
#Clojure
Clojure
(let [n (range 1 8)] (for [police n sanitation n fire n  :when (distinct? police sanitation fire)  :when (even? police)  :when (= 12 (+ police sanitation fire))] (println police sanitation fire)))
http://rosettacode.org/wiki/Delegates
Delegates
A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern. Objects ...
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { \\ there are some kinds of objects in M2000, one of them is the Group, the user object \\ the delegate is a pointer to group \\ 1. We pass parameters to function operations$(), $ means that this function return string value \\ 2. We see how this can be done with pointers to group global doc$ \\...
http://rosettacode.org/wiki/Delegates
Delegates
A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern. Objects ...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
delegator[del_]@operate := If[StringQ[del@operate], del@operate, "default implementation"]; del1 = Null; del2@banana = "phone"; del3@operate = "delegate implementation"; Print[delegator[#]@operate] & /@ {del1, del2, del3};
http://rosettacode.org/wiki/Delegates
Delegates
A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern. Objects ...
#NGS
NGS
{ type Delegator   F init(d:Delegator) d.delegate = null   F default_impl(d:Delegator) 'default implementation'   F operation(d:Delegator) default_impl(d)   F operation(d:Delegator) { guard defined thing guard thing is Fun try { d.delegate.thing() } catch(e:ImplNotFound) { # Might be unrelated exce...
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)...
#Nim
Nim
import strformat   type Point = tuple[x, y: float]   type Triangle = array[3, Point]   func `$`(p: Point): string = fmt"({p.x:.1f}, {p.y:.1f})"   func `$`(t: Triangle): string = fmt"Triangle {t[0]}, {t[1]}, {t[2]}"   func det2D(t: Triangle): float = t[0].x * (t[1].y - t[2].y) + t[1].x * (t[2].y - t[0].y) + t[...
http://rosettacode.org/wiki/Delete_a_file
Delete a file
Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#Free_Pascal
Free Pascal
program deletion(input, output, stdErr); const rootDirectory = '/'; // might have to be altered for other platforms inputTextFilename = 'input.txt'; docsFilename = 'docs'; var fd: file; begin assign(fd, inputTextFilename); erase(fd);   rmDir(docsFilename);   assign(fd, rootDirectory + inputTextFilename); erase...
http://rosettacode.org/wiki/Delete_a_file
Delete a file
Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   ' delete file and empty sub-directory in current directory   Kill "input.txt" RmDir "docs"   ' delete file and empty sub-directory in root directory c:\ ' deleting file in root requires administrative privileges in Windows 10   'Kill "c:\input.txt" 'RmDir "c:\docs"   Print "Press any key to quit" Sl...
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 ...
#Nim
Nim
import sequtils, permutationsswap   type Matrix[M,N: static[int]] = array[M, array[N, float]]   proc det[M,N](a: Matrix[M,N]): float = let n = toSeq 0..a.high for sigma, sign in n.permutations: var x = sign.float for i in n: x *= a[i][sigma[i]] result += x   proc perm[M,N](a: Matrix[M,N]): float = let...
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 ...
#Ol
Ol
  ; helper function that returns rest of matrix by col/row (define (rest matrix i j) (define (exclude1 l x) (append (take l (- x 1)) (drop l x))) (exclude1 (map exclude1 matrix (repeat i (length matrix))) j))   ; superfunction for determinant and permanent (define (super matrix math) (let ...
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.
#hexiscript
hexiscript
let a 1 let b 0 if tostr (a / (b + 0.)) = "inf" println "Divide by Zero" else println a / b endif
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.
#HicEst
HicEst
FUNCTION zero_divide(num, denom) XEQ( num// "/" // denom, *99) ! on error jump to label 99 zero_divide = 0 ! division OK RETURN   99 zero_divide = 1 END
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...
#F.23
F#
let is_numeric a = fst (System.Double.TryParse a)
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...
#Factor
Factor
: numeric? ( string -- ? ) string>number >boolean ;
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 ...
#Kotlin
Kotlin
import java.util.HashMap   fun main() { System.out.printf("%-40s  %2s  %10s  %8s  %s  %s%n", "String", "Length", "All Unique", "1st Diff", "Hex", "Positions") System.out.printf("%-40s  %2s  %10s  %8s  %s  %s%n", "------------------------", "------", "----------", "--------", "---", "---------") for (s in ar...
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...
#Raku
Raku
map { my $squish = .comb.squish.join; printf "\nLength: %2d <<<%s>>>\nCollapsible: %s\nLength: %2d <<<%s>>>\n", .chars, $_, .chars != $squish.chars, $squish.chars, $squish }, lines   q:to/STRINGS/;   "If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ..11111111111111111111111...
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...
#REXX
REXX
/*REXX program "collapses" all immediately repeated characters in a string (or strings).*/ @.= /*define a default for the @. array. */ parse arg x /*obtain optional argument from the CL.*/ if x\='' then @.1= x ...
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...
#Pascal
Pascal
program SameNessOfChar; {$IFDEF FPC} {$MODE DELPHI}{$OPTIMIZATION ON,ALL}{$CODEALIGN proc=16}{$ALIGN 16} {$ELSE} {$APPTYPE CONSOLE} {$ENDIF} uses sysutils;//Format const TestData : array[0..6] of String = ('',' ','2','333','.55','tttTTT','4444 444k'); function PosOfDifferentChar(const s: String):Native...
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...
#Python
Python
import threading import random import time   # Dining philosophers, 5 Phillies with 5 forks. Must have two forks to eat. # # Deadlock is avoided by never waiting for a fork while holding a fork (locked) # Procedure is to do block while waiting to get first fork, and a nonblocking # acquire of second fork. If failed to...
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#Prolog
Prolog
% See https://en.wikipedia.org/wiki/Discordian_calendar   main:- test(2022, 4, 20), test(2020, 5, 24), test(2020, 2, 29), test(2019, 7, 15), test(2025, 3, 19), test(2017, 12, 8).   test(Gregorian_year, Gregorian_month, Gregorian_day):- ddate(Gregorian_year, Gregorian_month, Gregorian_day, ...
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...
#Raku
Raku
class Graph { has (%.edges, %.nodes);   method new(*@args){ my (%edges, %nodes); for @args { %edges{.[0] ~ .[1]} = $_; %nodes{.[0]}.push( .[0] ~ .[1] ); %nodes{.[1]}.push( .[0] ~ .[1] ); } self.bless(edges => %edges, nodes => %nodes); }   method neighbours ($source) { my (%...
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...
#Ol
Ol
  (define (digital-root num) (if (less? num 10) num (let loop ((num num) (sum 0)) (if (zero? num) (digital-root sum) (loop (div num 10) (+ sum (mod num 10)))))))   (print (digital-root 627615)) (print (digital-root 39390)) (print (digital-root 588225)) (print (digital-roo...
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...
#Ring
Ring
  floor1 = "return baker!=cooper and baker!=fletcher and baker!=miller and baker!=smith and cooper!=fletcher and cooper!=miller and cooper!=smith and fletcher!=miller and fletcher!=smith and miller!=smith" floor2 = "return baker!=4" floor3 = "return cooper!=0" floor4 = "return fletche...
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 ...
#LFE
LFE
(defun dot-product (a b) (: lists foldl #'+/2 0 (: lists zipwith #'*/2 a b)))  
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 ...
#Liberty_BASIC
Liberty BASIC
vectorA$ = "1, 3, -5" vectorB$ = "4, -2, -1" print "DotProduct of ";vectorA$;" and "; vectorB$;" is "; print DotProduct(vectorA$, vectorB$)   'arbitrary length vectorA$ = "3, 14, 15, 9, 26" vectorB$ = "2, 71, 18, 28, 1" print "DotProduct of ";vectorA$;" and "; vectorB$;" is "; print DotProduct(vectorA$, vectorB$)   end...
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...
#Sidef
Sidef
func squeeze(str, c) { str.gsub(Regex("(" + c.escape + ")" + '\1+'), {|s1| s1 }) }   var strings = ["", '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ', "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell ...
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...
#Tcl
Tcl
# Set test data as a list pairing even and odd values # as test string and squeeze character(s) respectively. set test { {} {" "} {"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln } {"-"} {..1111111111111111111111111111111111111111111111111111111111111117777888} {"7"} {I never giv...
http://rosettacode.org/wiki/Deming%27s_Funnel
Deming's Funnel
W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to ...
#Vlang
Vlang
import math   type Rule = fn(f64, f64) f64   const ( dxs = [ -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001, -0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -...
http://rosettacode.org/wiki/Deming%27s_Funnel
Deming's Funnel
W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to ...
#Wren
Wren
import "/math" for Nums import "/fmt" for Fmt   var dxs = [ -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001, -0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.0...
http://rosettacode.org/wiki/Department_numbers
Department numbers
There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (different from each other) and mu...
#CLU
CLU
start_up = proc () po: stream := stream$primary_output()   stream$putl(po, "P S F\n- - -") for police: int in int$from_to_by(2,7,2) do for sanitation: int in int$from_to(1,7) do for fire: int in int$from_to(1,7) do if police~=sanitation & sanitation~=fi...
http://rosettacode.org/wiki/Department_numbers
Department numbers
There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (different from each other) and mu...
#COBOL
COBOL
IDENTIFICATION DIVISION. PROGRAM-ID. DEPARTMENT-NUMBERS.   DATA DIVISION. WORKING-STORAGE SECTION. 01 BANNER PIC X(24) VALUE "POLICE SANITATION FIRE". 01 COMBINATION. 03 FILLER PIC X(5) VALUE SPACES. 03 POLICE PIC 9. 03 FIL...
http://rosettacode.org/wiki/Delegates
Delegates
A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern. Objects ...
#Nim
Nim
#################################################################################################### # Base delegate.   type Delegate = ref object of RootObj nil   method thing(d: Delegate): string {.base.} = ## Default implementation of "thing". ## Using a method rather than a proc allows dynamic dispatch. "de...
http://rosettacode.org/wiki/Delegates
Delegates
A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern. Objects ...
#Objeck
Objeck
interface Thingable { method : virtual : public : Thing() ~ String; }   class Delegator { @delegate : Thingable;   New() { }   method : public : SetDelegate(delegate : Thingable) ~ Nil { @delegate := delegate; }   method : public : Operation() ~ String { if(@delegate = Nil) { return "defa...
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)...
#ooRexx
ooRexx
/*-------------------------------------------------------------------- * Determine if two triangles overlap * Fully (?) tested with integer coordinates of the 6 corners * This was/is an exercise with ooRexx * Removed the fraction arithmetic *-------------------------------------------------------------------*/ Parse Ve...
http://rosettacode.org/wiki/Delete_a_file
Delete a file
Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#Furor
Furor
  ###sysinclude dir.uh // =================== argc 3 < { #s ."Usage: " 0 argv print SPACE 1 argv print ." filename\n" end } 2 argv 'e !istrue { #s ."The given file ( " 2 argv print ." ) doesn't exist!\n" end } 2 argv removefile end  
http://rosettacode.org/wiki/Delete_a_file
Delete a file
Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#Gambas
Gambas
Public Sub Main()   Kill User.home &/ "input.txt" Rmdir User.home &/ "docs"   'Administrative privileges (sudo) would be required to mess about in Root - I'm not going there!   End
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 ...
#PARI.2FGP
PARI/GP
matdet(M)
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 ...
#Perl
Perl
#!/usr/bin/perl use strict; use warnings; use PDL; use PDL::NiceSlice;   sub permanent{ my $mat = shift; my $n = shift // $mat->dim(0); return undef if $mat->dim(0) != $mat->dim(1); return $mat(0,0) if $n == 1; my $sum = 0; --$n; my $m = $mat(1:,1:)->copy; for(my $i = 0; $i <= $n; ++$i){ $sum += $mat($i,0) * ...
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.
#HolyC
HolyC
try { Print("%d\n", 10 / 0); } catch { Print("Divide by zero"); }
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.
#i
i
//Division by zero is defined in 'i' so the result can be checked to determine division by zero. concept IsDivisionByZero(a, b) { c = a/b if c = 0 and a - 0 or a = 0 and c > 0 print( a, "/", b, " is a division by zero.") return end print( a, "/", b, " is not division by zero.") }   software { IsDivisionByZero(...
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.
#Icon_and_Unicon
Icon and Unicon
procedure main() &error := 1 udef := 1 / 0 | stop("Run-time error ", &errornumber, " : ", &errortext," in line #",&line," - converted to failure") end
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...
#Fantom
Fantom
  class Main { // function to see if str contains a number of any of built-in types static Bool readNum (Str str) { int := Int.fromStr (str, 10, false) // use base 10 if (int != null) return true float := Float.fromStr (str, false) if (float != null) return true decimal := Decimal.fromStr (st...
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...
#Forth
Forth
: is-numeric ( addr len -- ) 2dup snumber? ?dup if \ not standard, but >number is more cumbersome to use 0< if -rot type ." as integer = " . else 2swap type ." as double = " <# #s #> type then else 2dup >float if type ." as float = " f. else type ." isn't numeric in base " base...
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 ...
#Lua
Lua
local find, format = string.find, string.format local function printf(fmt, ...) print(format(fmt,...)) end   local pattern = '(.).-%1' -- '(.)' .. '.-' .. '%1'   function report_dup_char(subject) local pos1, pos2, char = find(subject, pattern)   local prefix = format('"%s" (%d)', subject, #subject) if pos1 ...
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...
#Ring
Ring
  load "stdlib.ring"   see "working..." + nl + nl str = ["The better the 4-wheel drive, the further you'll be from help when ya get stuck!", "I never give 'em hell, I just tell the truth, and they think it's hell.", "..1111111111111111111111111111111111111111111111111111111111111117777888"] strsave = str ...
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...
#Ruby
Ruby
strings = ["", '"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/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...
#Rust
Rust
fn collapse_string(val: &str) -> String { let mut output = String::new(); let mut chars = val.chars().peekable();   while let Some(c) = chars.next() { while let Some(&b) = chars.peek() { if b == c { chars.next(); } else { break; } ...
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...
#Perl
Perl
use strict; use warnings; use feature 'say'; use utf8; binmode(STDOUT, ':utf8'); use List::AllUtils qw(uniq); use Unicode::UCD 'charinfo'; use Unicode::Normalize qw(NFC);   for my $str ( '', ' ', '2', '333', '.55', 'tttTTT', '4444 444k', 'Δ👍👨', '🇬🇧🇬🇧🇬🇧🇬🇧', "\N{LATIN C...
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...
#Racket
Racket
  #lang racket   ;; Racket has traditional semaphores in addition to several higher level ;; synchronization tools. (Note that these semaphores are used for Racket's ;; green-threads, there are also "future semaphores" which are used for OS ;; threads, with a similar interface.)   ;; ----------------------------------...
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#PureBasic
PureBasic
Procedure.s Discordian_Date(Y, M, D) Protected DoY=DayOfYear(Date(Y,M,D,0,0,0)), Yold$=Str(Y+1166) Dim S.s(4) S(0)="Chaos": S(1)="Discord": S(2)="Confusion": S(3)="Bureaucracy" S(4)="The Aftermath" If (Y%4=0 And Y%100) Or Y%400=0 If M=2 And D=29 ProcedureReturn "St. Tib's Day, YOLD " + Yold$ Els...
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...
#REXX
REXX
/*REXX program determines the least costly path between two vertices given a list. */ $.= copies(9, digits() ) /*edge cost: indicates doesn't exist. */ xList= '!. @. $. beg fin bestP best$ xx yy' /*common EXPOSEd variables for subs. */ @abc= 'abcdefghijklmnopqrstuvwxyz' ...
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...
#PARI.2FGP
PARI/GP
dsum(n)=my(s); while(n, s+=n%10; n\=10); s additivePersistence(n)=my(s); while(n>9, s++; n=dsum(n)); s digitalRoot(n)=if(n, (n-1)%9+1, 0)
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...
#Pascal
Pascal
program DigitalRoot;   {$mode objfpc}{$H+}   uses {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, {$ENDIF}{$ENDIF} SysUtils, StrUtils;   // FPC has no Big mumbers implementation, Int64 will suffice.   procedure GetDigitalRoot(Value: Int64; Base: Byte; var DRoot, Pers: Integer); var i: Integer; DigitSum: Int64; ...
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...
#Ruby
Ruby
def solve( problem ) lines = problem.split(".") names = lines.first.scan( /[A-Z]\w*/ ) re_names = Regexp.union( names ) # Later on, search for these keywords (the word "not" is handled separately). words = %w(first second third fourth fifth sixth seventh eighth ninth tenth bottom top higher lower adjacent)...
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 ...
#LLVM
LLVM
; This is not strictly LLVM, as it uses the C library function "printf". ; LLVM does not provide a way to print values, so the alternative would be ; to just load the string into memory, and that would be boring.   ; Additional comments have been inserted, as well as changes made from the output produced by clang such ...
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...
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Linq.Enumerable   Module Module1   Function Squeeze(s As String, c As Char) As String If String.IsNullOrEmpty(s) Then Return "" End If Return s(0) + New String(Range(1, s.Length - 1).Where(Function(i) s(i) <> c OrElse s(i) <> s(i - 1)).Select(Function(i) s(i)).ToAr...
http://rosettacode.org/wiki/Deming%27s_Funnel
Deming's Funnel
W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to ...
#zkl
zkl
fcn funnel(dxs, rule){ x:=0.0; rxs:=L(); foreach dx in (dxs){ rxs.append(x + dx); x = rule(x,dx); } rxs }   fcn mean(xs){ xs.sum(0.0)/xs.len() }   fcn stddev(xs){ m:=mean(xs); (xs.reduce('wrap(sum,x){ sum + (x-m)*(x-m) },0.0)/xs.len()).sqrt(); }   fcn experiment(label,dxs,dys,rule){ rxs...
http://rosettacode.org/wiki/Department_numbers
Department numbers
There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (different from each other) and mu...
#Cowgol
Cowgol
include "cowgol.coh";   typedef Dpt is int(1, 7);   # print combination if valid sub print_comb(p: Dpt, s: Dpt, f: Dpt) is var out: uint8[] := {'*',' ','*',' ','*','\n',0}; out[0] := p + '0'; out[2] := s + '0'; out[4] := f + '0'; if p != s and p != f and f != s and p+s+f == 12 then print(&ou...
http://rosettacode.org/wiki/Department_numbers
Department numbers
There is a highly organized city that has decided to assign a number to each of their departments:   police department   sanitation department   fire department Each department can have a number between   1   and   7   (inclusive). The three department numbers are to be unique (different from each other) and mu...
#D
D
  import std.stdio, std.range;   void main() { int sol = 1; writeln("\t\tFIRE\t\tPOLICE\t\tSANITATION"); foreach( f; iota(1,8) ) { foreach( p; iota(1,8) ) { foreach( s; iota(1,8) ) { if( f != p && f != s && p != s && !( p & 1 ) && ( f + s + p == 12 ) ) { ...
http://rosettacode.org/wiki/Delegates
Delegates
A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern. Objects ...
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   @interface Delegator : NSObject {   id delegate; }   - (id)delegate; - (void)setDelegate:(id)obj; - (NSString *)operation;   @end   @implementation Delegator   - (id)delegate {   return delegate; }   - (void)setDelegate:(id)obj {   delegate = obj; // Weak reference }   - ...
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)...
#Pascal
Pascal
  program TrianglesOverlap; { The program looks for a separating line between the triangles. It's known that only the triangle sides (produced) need to be considered as possible separators (except in the degenerate case when both triangles are reduced to a point). If there's a strong separator, i.e. one that is disjoin...
http://rosettacode.org/wiki/Delete_a_file
Delete a file
Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#GAP
GAP
# Apparently GAP can only remove a file, not a directory RemoveFile("input.txt"); # true RemoveFile("docs"); # fail
http://rosettacode.org/wiki/Delete_a_file
Delete a file
Task Delete a file called "input.txt" and delete a directory called "docs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
#Go
Go
package main import "os"   func main() { os.Remove("input.txt") os.Remove("/input.txt") os.Remove("docs") os.Remove("/docs") // recursively removes contents: os.RemoveAll("docs") os.RemoveAll("/docs") }
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 ...
#Phix
Phix
with javascript_semantics function minor(sequence a, integer x, integer y) integer l = length(a)-1 sequence result = repeat(repeat(0,l),l) for i=1 to l do for j=1 to l do result[i][j] = a[i+(i>=x)][j+(j>=y)] end for end for return result end function function det(sequen...
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.
#IDL
IDL
if not finite( <i>expression</i> ) then ...
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.
#J
J
funnydiv=: 0 { [: (,:'division by zero detected')"_^:(_ e. |@,) (,>:)@:(,:^:(0<#@$))@[ %"_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.
#Java
Java
public static boolean infinity(double numer, double denom){ return Double.isInfinite(numer/denom); }
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...
#Fortran
Fortran
FUNCTION is_numeric(string) IMPLICIT NONE CHARACTER(len=*), INTENT(IN) :: string LOGICAL :: is_numeric REAL :: x INTEGER :: e READ(string,*,IOSTAT=e) x is_numeric = e == 0 END FUNCTION is_numeric
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...
#Free_Pascal
Free Pascal
function isNumeric(const potentialNumeric: string): boolean; var potentialInteger: integer; potentialReal: real; integerError: integer; realError: integer; begin integerError := 0; realError := 0;   // system.val attempts to convert numerical value representations. // It accepts all notations as they are accept...
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 ...
#Maple
Maple
CheckUnique:=proc(s) local i, index; printf("input: \"%s\", length: %a\n", s, StringTools:-Length(s)); for i from 1 to StringTools:-Length(s) do index := StringTools:-SearchAll(s[i], s); if (numelems([index]) > 1) then printf("The given string has duplicated characters.\n"); printf("The first duplicated c...
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 ...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[UniqueCharacters] UniqueCharacters[s_String] := Module[{c, len, good = True}, c = Characters[s]; len = Length[c]; Print[s, " with length ", len]; Do[ If[c[[i]] == c[[j]], Print["Character ", c[[i]], " is repeated at positions ", i, " and ", j]; good = False ] , {i, len - 1}, ...
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...
#Scala
Scala
object CollapsibleString {   /**Collapse a string (if possible)*/ def collapseString (s : String) : String = { var res = s var isOver = false var i = 0 if(res.size == 0) res else while(!isOver){ if(res(i) == res(i+1)){ res = res.take(i) ++ res.drop(i+1) i-=1 } i...
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...
#Phix
Phix
with javascript_semantics procedure samechar(sequence s) string msg = "all characters are the same" integer l = length(s) if l>=2 then integer ch = s[1] for i=2 to l do integer si = s[i] if si!=ch then string su = utf32_to_utf8({si}) ms...
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...
#Raku
Raku
class Fork { has $!lock = Lock.new; method grab($who, $which) { say "$who grabbing $which fork"; $!lock.lock; } method drop($who, $which) { say "$who dropping $which fork"; $!lock.unlock; } }   class Lollipop { has $!channel = Channel.new; method mine($who) { $!channel.send($who) } m...
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#Python
Python
import datetime, calendar   DISCORDIAN_SEASONS = ["Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"]   def ddate(year, month, day): today = datetime.date(year, month, day) is_leap_year = calendar.isleap(year) if is_leap_year and month == 2 and day == 29: return "St. Tib's Day, YOLD " +...
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...
#Ring
Ring
  # Project : Dijkstra's algorithm   graph = [["a", "b", 7], ["a", "c", 9], ["a", "f", 14], ["b", "c", 10], ["b", "d", 15], ["c", "d", 11], ["c", "f", 2], ["d", "e", 6], ["e", "f", 9]]   dbegin = "a" dend = "...
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...
#Perl
Perl
#!perl use strict; use warnings; use List::Util qw(sum);   my @digit = (0..9, 'a'..'z'); my %digit = map { +$digit[$_], $_ } 0 .. $#digit;   sub base { my ($n, $b) = @_; $b ||= 10; die if $b > @digit; my $result = ''; while( $n ) { $result .= $digit[ $n % $b ]; $n = int( $n / $b ); } re...
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...
#Scala
Scala
import scala.math.abs   object Dinesman3 extends App { val tenants = List("Baker", "Cooper2", "Fletcher4", "Miller", "Smith") val (groundFloor, topFloor) = (1, tenants.size)   /** Rules with related tenants and restrictions*/ val exclusions = List((suggestedFloor0: Map[String, Int]) => suggestedFloor0("Bake...
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 ...
#Logo
Logo
to dotprod :a :b output apply "sum (map "product :a :b) end   show dotprod [1 3 -5] [4 -2 -1]  ; 3