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/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 ...
#Logtalk
Logtalk
dot_product(A, B, Sum) :- dot_product(A, B, 0, Sum).   dot_product([], [], Sum, Sum). dot_product([A| As], [B| Bs], Acc, Sum) :- Acc2 is Acc + A*B, dot_product(As, Bs, Acc2, Sum).
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...
#Vlang
Vlang
// Returns squeezed string, original and new lengths in // unicode code points (not normalized). fn squeeze(s string, c string) (string, int, int) { mut r := s.runes() mut t := c.runes()[0] le, mut del := r.len, 0 for i := le - 2; i >= 0; i-- { if r[i] == t && r[i] == r[i+1] { r.dele...
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...
#Wren
Wren
import "/fmt" for Fmt   // Returns squeezed string, original and new lengths in // unicode code points (not normalized). var squeeze = Fn.new { |s, ch| var c = s.codePoints.toList var le = c.count if (le < 2) return [s, le, le] for (i in le-2..0) { if (c[i] == ch.codePoints[0] && c[i] == c[i+1])...
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...
#Delphi
Delphi
  program Department_numbers;   {$APPTYPE CONSOLE}   uses System.SysUtils;   var i, j, k, count: Integer;   begin writeln('Police Sanitation Fire'); writeln('------ ---------- ----'); count := 0; i := 2; while i < 7 do begin for j := 1 to 7 do begin if j = i then Continue; ...
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 ...
#Oforth
Oforth
Object Class new: Delegate1   Object Class new: Delegate2 Delegate2 method: thing "Delegate implementation" println ;   Object Class new: Delegator(delegate) Delegator method: initialize  := delegate ;   Delegator method: operation @delegate respondTo(#thing) ifTrue: [ @delegate thing return ] "Default implement...
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 ...
#ooRexx
ooRexx
  delegator = .delegator~new -- no delegate say delegator~operation -- an invalid delegate type delegator~delegate = "Some string" say delegator~operation -- a good delegate delegator~delegate = .thing~new say delegator~operation -- a directory object with a thing entry defined d = .directory~new d~thing = "delegate ...
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 ...
#OxygenBasic
OxygenBasic
  class DelegateA 'not implmenting thing() '============== ' string message   end class   class DelegateB 'implementing thing() '============== ' string message   method thing() as string return message end method ' end class     Class Delegator '============== ' has DelegateA dgA has DelegateB dgB ' method operation()...
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)...
#Perl
Perl
use strict; use warnings;   sub det2D { my $p1 = shift or die "4 Missing first point\n"; my $p2 = shift or die "Missing second point\n"; my $p3 = shift or die "Missing third point\n";   return $p1->{x} * ($p2->{y} - $p3->{y}) + $p2->{x} * ($p3->{y} - $p1->{y}) + $p3->{x} * ($p1->{y} - ...
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.
#Groovy
Groovy
// Gets the first filesystem root. On most systems this will be / or c:\ def fsRoot = File.listRoots().first()   // Create our list of files (including directories) def files = [ new File("input.txt"), new File(fsRoot, "input.txt"), new File("docs"), new File(fsRoot, "docs") ]   /* W...
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 ...
#PowerShell
PowerShell
  function det-perm ($array) { if($array) { $size = $array.Count function prod($A) { $prod = 1 if($A) { $A | foreach{$prod *= $_} } $prod } function generate($sign, $n, $A) { if($n -eq 1) { $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.
#JavaScript
JavaScript
function divByZero(dividend,divisor) { var quotient=dividend/divisor; if(isNaN(quotient)) return 0; //Can be changed to whatever is desired by the programmer to be 0, false, or Infinity return quotient; //Will return Infinity or -Infinity in cases of, for example, 5/0 or -7/0 respectively } alert(divBy...
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.
#jq
jq
def div(x;y): if y==0 then error("NaN") else x/y 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...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Dim Shared symbols(0 To 15) As UByte For i As Integer = 48 to 57 symbols(i - 48) = i Next For i As Integer = 97 to 102 symbols(i - 87) = i Next   Const plus As UByte = 43 Const minus As Ubyte = 45 Const dot As UByte = 46   Function isNumeric(s As Const String, base_ As Integer = 10) As Boolea...
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 ...
#Nanoquery
Nanoquery
def analyze(s) s = str(s) println "Examining [" + s + "] which has a length of " + str(len(s)) + ":"   if len(s) < 2 println "\tAll characters in the string are unique." return end   seen = list() for i in range(0, len(s) - 2) ...
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 ...
#Nim
Nim
import unicode, strformat   proc checkUniqueChars(s: string) =   echo fmt"Checking string ""{s}"":" let runes = s.toRunes for i in 0..<runes.high: let rune = runes[i] for j in (i+1)..runes.high: if runes[j] == rune: echo "The string contains duplicate characters." echo fmt"Character ...
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...
#Sidef
Sidef
func squeeze(str) { str.gsub(/(.)\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 the truth, and they think it'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...
#Smalltalk
Smalltalk
#( 'The better the 4-wheel drive, the further you''ll be from help when ya get stuck!' 'headmistressship' 'aardvark' '😍😀🙌💃😍😍😍🙌' ) do:[:eachWord | |shortened|   shortened := String streamContents:[:out | eachWord inject:nil into:[:prev :this | prev ~= this ifTrue:[out nextPut...
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...
#PicoLisp
PicoLisp
(de equal? (Str) (let (Lst (chop Str) C (car Lst) P 2 F) (prin Str ": ") (for A (cdr Lst) (NIL (= A C) (on F) (prin "First different character " A)) (inc 'P) ) (if F (prinl " at position: " P) (prinl "all characters are the same")) ) ) (equal?) (equal? " ") (equal? "333") (eq...
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...
#Plain_English
Plain English
To run: Start up. Show the uniformity of "". Show the uniformity of " ". Show the uniformity of "2". Show the uniformity of "333". Show the uniformity of ".55". Show the uniformity of "tttTTT". Show the uniformity of "4444 444k". Wait for the escape key. Shut down.   To find the first different character in a string ...
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...
#REXX
REXX
/*REXX program demonstrates a solution in solving the dining philosophers problem. */ signal on halt /*branches to HALT: (on Ctrl─break).*/ parse arg seed diners /*obtain optional arguments from the CL*/ if datatype(seed, 'W') then call random ,, see...
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#Racket
Racket
#lang racket/base ;;;; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ;;;; Derived from 'D' Implementation ;;;; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ (require racket/date racket/match)   (define seasons '(Chao...
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...
#Ruby
Ruby
class Graph Vertex = Struct.new(:name, :neighbours, :dist, :prev)   def initialize(graph) @vertices = Hash.new{|h,k| h[k]=Vertex.new(k,[],Float::INFINITY)} @edges = {} graph.each do |(v1, v2, dist)| @vertices[v1].neighbours << v2 @vertices[v2].neighbours << v1 @edges[[v1, v2]] = @edges...
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...
#Phix
Phix
with javascript_semantics procedure digital_root(atom n, integer base=10) integer root, persistence = 1 atom work = n while true do root = 0 while work!=0 do root += remainder(work,base) work = floor(work/base) end while if root<base then exit end if ...
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...
#Sidef
Sidef
func dinesman(problem) { var lines = problem.split('.') var names = lines.first.scan(/\b[A-Z]\w*/) var re_names = Regex(names.join('|'))   # Later on, search for these keywords (the word "not" is handled separately). var words = %w(first second third fourth fifth sixth seventh eighth ninth tenth ...
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 ...
#Lua
Lua
function dotprod(a, b) local ret = 0 for i = 1, #a do ret = ret + a[i] * b[i] end return ret end   print(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...
#XPL0
XPL0
string 0; char C, I, J, Last;   proc Squeeze(Char, S); \Eliminate specified repeated characters from string char Char, S; [I:= 0; J:= 0; Last:= -1; loop [if S(I) # Last or Char # Last then [C(J):= S(I); if S(I) = 0 then quit; J:= J+1; ]; Last:= S(I); I:= I+1; ]; ];   int...
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...
#zkl
zkl
fcn squeeze(c,str){ // Works with UTF-8 s,cc,sz,n := Data(Void,str), String(c,c), c.len(), 0; // byte buffer in case of LOTs of deletes while(Void != (n=s.find(cc,n))){ str=s.del(n,sz) } // and searching is faster for big strings s.text }
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...
#Draco
Draco
proc main() void: byte police, sanitation, fire;   writeln("Police Sanitation Fire"); for police from 2 by 2 upto 7 do for sanitation from 1 upto 7 do for fire from 1 upto 7 do if police /= sanitation and police /= fire and sanitation ...
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...
#Elixir
Elixir
  IO.puts("P - F - S") for p <- [2,4,6], f <- 1..7, s <- 1..7, p != f and p != s and f != s and p + f + s == 12 do "#{p} - #{f} - #{s}" end |> Enum.each(&IO.puts/1)    
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 ...
#Oz
Oz
declare class Delegator from BaseObject attr delegate:unit   meth set(DG) {Object.is DG} = true %% assert: DG must be an object delegate := DG end   meth operation($) if @delegate == unit then {self default($)} else try {@delegate thing($)} catch error(object(lookup ...) .....
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 ...
#Pascal
Pascal
use strict;   package Delegator; sub new { bless {} } sub operation { my ($self) = @_; if (defined $self->{delegate} && $self->{delegate}->can('thing')) { $self->{delegate}->thing; } else { 'default implementation'; } } 1;   package Delegate; sub new { bless {}; } sub thing { 'delegate ...
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)...
#Phix
Phix
-- -- demo\rosetta\Determine_if_two_triangles_overlap.exw -- with javascript_semantics include pGUI.e Ihandle dlg, canvas cdCanvas cddbuffer, cdcanvas constant triangles = {{{{0,0},{5,0},{0,5}},{{0,0},{5,0},{0,6}}}, {{{0,0},{0,5},{5,0}},{{0,0},{0,5},{5,0}}}, {{{0,0},{5,0},{...
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.
#Haskell
Haskell
import System.IO import System.Directory   main = do removeFile "output.txt" removeDirectory "docs" removeFile "/output.txt" removeDirectory "/docs"
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.
#HicEst
HicEst
SYSTEM(DIR="docs") ! create docs in current directory (if not existent), make it current OPEN (FILE="input.txt", "NEW") ! in current directory = docs WRITE(FIle="input.txt", DELETE=1) ! no command to DELETE a DIRECTORY in HicEst   SYSTEM(DIR="C:\docs") ! create C:\docs (if not existent), make it curren...
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 ...
#Python
Python
from itertools import permutations from operator import mul from math import fsum from spermutations import spermutations   def prod(lst): return reduce(mul, lst, 1)   def perm(a): n = len(a) r = range(n) s = permutations(r) return fsum(prod(a[i][sigma[i]] for i in r) for sigma in s)   def det(a): ...
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.
#Jsish
Jsish
if (!isFinite(numerator/denominator)) puts("result is infinity or not a number");
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.
#Julia
Julia
isdefinite(n::Number) = !isnan(n) && !isinf(n)   for n in (1, 1//1, 1.0, 1im, 0) d = n / 0 println("Dividing $n by 0 ", isdefinite(d) ? "results in $d." : "yields an indefinite value ($d).") 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...
#Gambas
Gambas
Public Sub Form_Open() Dim sAnswer, sString As String   sString = Trim(InputBox("Enter as string", "String or Numeric"))   If IsNumber(sString) Then sAnswer = "'" & sString & "' is numeric" Else sAnswer = "'" & sString & "' is a string" Print sAnswer   End
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 ...
#Perl
Perl
use strict; use warnings; use feature 'say'; use utf8; binmode(STDOUT, ':utf8'); use List::AllUtils qw(uniq); use Unicode::UCD 'charinfo';   for my $str ( '', '.', 'abcABC', 'XYZ ZYX', '1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ', '01234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ0X', 'Δ👍👨👍Δ', 'ΔδΔ̂ΔΛ'...
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...
#Swift
Swift
let 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. ", " --- 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...
#Tcl
Tcl
set test { {} {"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_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...
#Prolog
Prolog
  :- system:set_prolog_flag(double_quotes,chars) .   main :- same_or_different("") , same_or_different(" ") , same_or_different("2") , same_or_different("333") , same_or_different(".55") , same_or_different("tttTTT") , same_or_different("4444 444k") .   %! same_or_different(INPUTz0)   same_or_different(INPUTz0) :- s...
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...
#Ruby
Ruby
require 'mutex_m'   class Philosopher def initialize(name, left_fork, right_fork) @name = name @left_fork = left_fork @right_fork = right_fork @meals = 0 end   def go while @meals < 5 think dine end puts "philosopher #@name is full!" end   def think puts "philosophe...
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#Raku
Raku
my @seasons = << Chaos Discord Confusion Bureaucracy 'The Aftermath' >>; my @days = << Sweetmorn Boomtime Pungenday Prickle-Prickle 'Setting Orange' >>; sub ordinal ( Int $n ) { $n ~ ( $n % 100 == 11|12|13 ?? 'th' !! < th st nd rd th th th th th th >[$n % 10] ) }   sub ddate ( Str $ymd ) { my $d = DateTime.new:...
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...
#Rust
Rust
use std::cmp::Ordering; use std::collections::BinaryHeap; use std::usize;     struct Grid<T> { nodes: Vec<Node<T>>, }   struct Node<T> { data: T, edges: Vec<(usize,usize)>, }   #[derive(Copy, Clone, Eq, PartialEq)] struct State { node: usize, cost: usize, }   // Manually implement Ord so we get a mi...
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...
#Picat
Picat
go => foreach(N in [627615,39390,588225,393900588225, 58142718981673030403681039458302204471300738980834668522257090844071443085937]) [Sum,Persistence] = digital_root(N), printf("%w har addititive persistence %d and digital root of %d\n", N,Persistence,Sum) end, nl.   % % (Reduced) digit ...
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...
#PicoLisp
PicoLisp
(for N (627615 39390 588225 393900588225) (for ((A . I) N T (sum format (chop I))) (T (> 10 I) (prinl N " has additive persistance " (dec A) " and digital root of " 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...
#Tailspin
Tailspin
  templates permutations when <=1> do [1] ! otherwise def n: $; templates expand def p: $; 1..$n -> \(def k: $; [$p(1..$k-1)..., $n, $p($k..last)...] !\) ! end expand $n - 1 -> permutations -> expand ! end permutations   templates index&{of:} $ -> \[i](<=$of> $i! \) ...! end in...
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 ...
#M2000_Interpreter
M2000 Interpreter
  Module dot_product { A=(1,3,-5) B=(4,-2,-1) Function Dot(a, b) { if len(a)<>len(b) Then Error "not same length" if len(a)=0 then Error "empty vectors" Let a1=each(a), b1=each(b), sum=0 While a1, b1 {sum+=array(a1)*array(b1)} =sum } ...
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 ...
#Maple
Maple
<1,2,3> . <4,5,6>
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...
#Excel
Excel
departmentNumbers =validRows( LAMBDA(ab, LET( x, INDEX(ab, 0, 1), y, INDEX(ab, 0, 2), z, 12 - (x + y),   IF(y <> z, IF(1 <= z, IF(7 >= z, CHOOSE({1, 2, 3}, x, y, z), NA() ...
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 ...
#Perl
Perl
use strict;   package Delegator; sub new { bless {} } sub operation { my ($self) = @_; if (defined $self->{delegate} && $self->{delegate}->can('thing')) { $self->{delegate}->thing; } else { 'default implementation'; } } 1;   package Delegate; sub new { bless {}; } sub thing { 'delegate ...
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 ...
#Phix
Phix
enum OTHER, OPERATION   function operation(object o) integer rid = o[OPERATION] if rid!=NULL then return call_func(rid,{}) end if return "no implementation" end function   function xthing() return "default implementation" end function   function newX() return {1,routine_id("xthing"),2} e...
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)...
#Python
Python
from __future__ import print_function import numpy as np   def CheckTriWinding(tri, allowReversed): trisq = np.ones((3,3)) trisq[:,0:2] = np.array(tri) detTri = np.linalg.det(trisq) if detTri < 0.0: if allowReversed: a = trisq[2,:].copy() trisq[2,:] = trisq[1,:] trisq[1,:] = a else: raise ValueError("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.
#Icon_and_Unicon
Icon and Unicon
every dir := !["./","/"] do { remove(f := dir || "input.txt") |stop("failure for file remove ",f) rmdir(f := dir || "docs") |stop("failure for directory remove ",f) }  
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.
#Io
Io
Directory fileNamed("input.txt") remove Directory directoryNamed("docs") remove RootDir := Directory clone setPath("/") RootDir fileNamed("input.txt") remove RootDir directoryNamed("docs") remove
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 ...
#R
R
library(combinat) perm <- function(A) { stopifnot(is.matrix(A)) n <- nrow(A) if(n != ncol(A)) stop("Matrix is not square.") if(n < 1) stop("Matrix has a dimension of size 0.") sum(sapply(combinat::permn(n), function(sigma) prod(sapply(1:n, function(i) A[i, sigma[i]])))) }   #We copy our test cases from the Py...
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.
#Kotlin
Kotlin
// version 1.1   fun divideByZero(x: Int, y:Int): Boolean = try { x / y false } catch(e: ArithmeticException) { true }   fun main(args: Array<String>) { val x = 1 val y = 0 if (divideByZero(x, y)) { println("Attempted to divide by zero") } else { @Supp...
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.
#Lambdatalk
Lambdatalk
  {def DivByZero? {lambda {:w} {W.equal? :w Infinity}}}   {DivByZero? {/ 3 2}} -> false {DivByZero? {/ 3 0}} -> 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...
#Go
Go
package main   import ( "fmt" "strconv" )   func isNumeric(s string) bool { _, err := strconv.ParseFloat(s, 64) return err == nil }   func main() { fmt.Println("Are these strings numeric?") strings := []string{"1", "3.14", "-100", "1e2", "NaN", "rose"} for _, s := range strings { fmt...
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 ...
#Phix
Phix
procedure all_uniq(sequence s) string chars = "" sequence posns = {}, multi = {} integer lm = 0 for i=1 to length(s) do integer si = s[i], k = find(si,chars) if k=0 then chars &= si posns &= {{i}} else posns[k] &= i...
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...
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Function Collapse(s As String) As String If String.IsNullOrEmpty(s) Then Return "" End If Return s(0) + New String(Enumerable.Range(1, s.Length - 1).Where(Function(i) s(i) <> s(i - 1)).Select(Function(i) s(i)).ToArray) End Function   Sub Main() Di...
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...
#VBA
VBA
Function Collapse(strIn As String) As String Dim i As Long, strOut As String If Len(strIn) > 0 Then strOut = Mid$(strIn, 1, 1) For i = 2 To Len(strIn) If Mid$(strIn, i, 1) <> Mid$(strIn, i - 1, 1) Then strOut = strOut & Mid$(strIn, i, 1) End If Next 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...
#Python
Python
'''Determine if a string has all the same characters'''   from itertools import groupby     # firstDifferingCharLR :: String -> Either String Dict def firstDifferingCharLR(s): '''Either a message reporting that no character changes were seen, or a dictionary with details of the first character (if an...
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...
#Rust
Rust
use std::thread; use std::sync::{Mutex, Arc};   struct Philosopher { name: String, left: usize, right: usize, }   impl Philosopher { fn new(name: &str, left: usize, right: usize) -> Philosopher { Philosopher { name: name.to_string(), left: left, right: right, ...
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#REXX
REXX
/*REXX program converts a mm/dd/yyyy Gregorian date ───► a Discordian date. */ @day.1= 'Sweetness' /*define the 1st day─of─Discordian─week*/ @day.2= 'Boomtime' /* " " 2nd " " " " */ @day.3= 'Pungenday' ...
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...
#SAS
SAS
/* create SAS data set */ data Edges; input Start $ End $ Cost; datalines; 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 ;   /* call OPTMODEL procedure in SAS/OR */ proc optmodel; /* declare sets and parameters, and read input data */ set <str,str> LINKS; ...
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...
#PL.2FI
PL/I
digrt: Proc Options(main); /* REXX *************************************************************** * Test digroot **********************************************************************/   Call digrtst('7'); Call digrtst('627615'); Call digrtst('39390'); Call digrtst('588225'); Call digrtst('393900588225');   ...
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...
#Tcl
Tcl
package require Tcl 8.5 package require struct::list   proc dinesmanSolve {floors people constraints} { # Search for a possible assignment that satisfies the constraints struct::list foreachperm p $floors { lassign $p {*}$people set found 1 foreach c $constraints { if {![expr $c]} { set found 0 brea...
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 ...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
{1,3,-5}.{4,-2,-1}
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot ...
#MATLAB
MATLAB
A = [1 3 -5] B = [4 -2 -1] C = dot(A,B)
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...
#F.23
F#
  // A function to generate department numbers. Nigel Galloway: May 2nd., 2018 type dNum = {Police:int; Fire:int; Sanitation:int} let fN n=n.Police%2=0&&n.Police+n.Fire+n.Sanitation=12&&n.Police<>n.Fire&&n.Police<>n.Sanitation&&n.Fire<>n.Sanitation List.init (7*7*7) (fun n->{Police=n%7+1;Fire=(n/7)%7+1;Sanitation=(n/49...
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 ...
#PHP
PHP
class Delegator { function __construct() { $this->delegate = NULL ; } function operation() { if(method_exists($this->delegate, "thing")) return $this->delegate->thing() ; return 'default implementation' ; } }   class Delegate { function thing() { return 'Delegate Implementation' ; } } ...
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 ...
#PicoLisp
PicoLisp
(class +Delegator) # delegate   (dm operation> () (if (: delegate) (thing> @) "default implementation" ) )     (class +Delegate) # thing   (dm T (Msg) (=: thing Msg) )   (dm thing> () (: thing) )     (let A (new '(+Delegator)) # Without a delegate (println (operation> A))   # With delegate...
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)...
#QB64
QB64
  DATA 0,0,5,0,0,5,0,0,5,0,0,6 DATA 0,0,0,5,5,0,0,0,0,5,5,0 DATA 0,0,5,0,0,5,-10,0,-5,0,-1,6 DATA 0,0,5,0,2.5,5,0,4,2.5,-1,5,4 DATA 0,0,1,1,0,2,2,1,3,0,3,2 DATA 0,0,1,1,0,2,2,1,3,-2,3,4   TYPE point x AS INTEGER y AS INTEGER END TYPE   DIM coord(12, 3) AS point   workscreen = _NEWIMAGE(800, 800, 32) backscreen ...
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.
#J
J
load 'files' ferase 'input.txt' ferase '\input.txt' ferase 'docs' ferase '\docs'   NB. Or all at once... ferase 'input.txt';'/input.txt';'docs';'/docs'
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.
#Java
Java
import java.io.File;   public class FileDeleteTest { public static boolean deleteFile(String filename) { boolean exists = new File(filename).delete(); return exists; }   public static void test(String type, String filename) { System.out.println("The following " + type + " called " + ...
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 ...
#Racket
Racket
  #lang racket (require math) (define determinant matrix-determinant)   (define (permanent M) (define n (matrix-num-rows M)) (for/sum ([σ (in-permutations (range n))]) (for/product ([i n] [σi σ]) (matrix-ref M i σi))))  
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 ...
#Raku
Raku
sub insert ($x, @xs) { ([flat @xs[0 ..^ $_], $x, @xs[$_ .. *]] for 0 .. @xs) } sub order ($sg, @xs) { $sg > 0 ?? @xs !! @xs.reverse }   multi σ_permutations ([]) { [] => 1 }   multi σ_permutations ([$x, *@xs]) { σ_permutations(@xs).map({ |order($_.value, insert($x, $_.key)) }) Z=> |(1,-1) xx * }   sub m_arith ( @a,...
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.
#LabVIEW
LabVIEW
define dividehandler(a,b) => { ( #a->isNotA(::integer) && #a->isNotA(::decimal) || #b->isNotA(::integer) && #b->isNotA(::decimal) ) ? return 'Error: Please supply all params as integers or decimals' protect => { handle_error => { return 'Error: Divide by zero' } local(x = #a / #b) return #x } }   divideh...
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.
#Lasso
Lasso
define dividehandler(a,b) => { ( #a->isNotA(::integer) && #a->isNotA(::decimal) || #b->isNotA(::integer) && #b->isNotA(::decimal) ) ? return 'Error: Please supply all params as integers or decimals' protect => { handle_error => { return 'Error: Divide by zero' } local(x = #a / #b) return #x } }   divideh...
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.
#Lingo
Lingo
on div (a, b) -- for simplicity type check of vars omitted res = value("float(a)/b") if voidP(res) then _player.alert("Division by zero!") else return res end if 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...
#Groovy
Groovy
def isNumeric = { def formatter = java.text.NumberFormat.instance def pos = [0] as java.text.ParsePosition formatter.parse(it, pos)   // if parse position index has moved to end of string // them the whole string was numeric pos.index == it.size() }
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...
#Haskell
Haskell
isInteger s = case reads s :: [(Integer, String)] of [(_, "")] -> True _ -> False   isDouble s = case reads s :: [(Double, String)] of [(_, "")] -> True _ -> False   isNumeric :: String -> Bool isNumeric s = isInteger s || isDouble s
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 ...
#PicoLisp
PicoLisp
(de burn (Lst) (let P 0 (by '((A) (set A (inc 'P)) (put A 'P (char A)) ) group Lst ) ) ) (de first (Lst) (mini '((L) (nand (cdr L) (apply min (mapcar val L)) ) ) Lst ) ) (de uniq? (Str) (let M (first (burn (ch...
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 ...
#Prolog
Prolog
report_duplicates(S) :- duplicates(S, Dups), format('For value "~w":~n', S), report(Dups), nl.   report(Dups) :- maplist(only_one_position, Dups), format(' All characters are unique~n').   report(Dups) :- exclude(only_one_position, Dups, [c(Char,Positions)|_]), reverse(Positions, PosInOrder), atomic_list_...
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...
#Vlang
Vlang
// Returns collapsed string, original and new lengths in // unicode code points (not normalized). fn collapse(s string) (string, int, int) { mut r := s.runes() le, mut del := r.len, 0 for i := le - 2; i >= 0; i-- { if r[i] == r[i+1] { r.delete(i) del++ } } if ...
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...
#Wren
Wren
import "/fmt" for Fmt   // Returns collapsed string, original and new lengths in // unicode code points (not normalized). var collapse = Fn.new { |s| var c = s.codePoints.toList var le = c.count if (le < 2) return [s, le, le] for (i in le-2..0) { if (c[i] == c[i+1]) c.removeAt(i) } var c...
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...
#Quackery
Quackery
  [ 0 swap dup size 0 = iff drop done behead swap witheach [ over != if [ drop i^ 1+ swap conclude ] ] drop ] is allsame ( [ --> n )   ( 0 indicates all items are the same, otherwise n is first different item )   [ say ' String: "' dup echo$ ...
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...
#R
R
isAllSame <- function(string) { strLength <- nchar(string) if(length(strLength) > 1) { #R has a distinction between the length of a string and that of a character vector. It is a common source #of problems when coming from another language. We will try to avoid the topic here. #For our purposes, let u...
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...
#Simula
Simula
COMMENT ! DEADLOCK IS PREVENTED BY REVERSING THE ORDER OF TAKING THE CHOPSTICKS FOR THE LAST PHILOSOPHER. ! THAT MEANS ALL PHILOSOPHERS FIRST TAKE THE LEFT CHOPSTICK, THEN THE RIGHT CHOPSTICK. ! BUT THE LAST PHILOSOPHER FIRST TAKES THE RIGHT CHOPSTICK, THEN THE LEFT. ! ! THE DETACH STATEMENT IN CLASS PHILOS...
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#Ruby
Ruby
require 'date'   class DiscordianDate SEASON_NAMES = ["Chaos","Discord","Confusion","Bureaucracy","The Aftermath"] DAY_NAMES = ["Sweetmorn","Boomtime","Pungenday","Prickle-Prickle","Setting Orange"] YEAR_OFFSET = 1166 DAYS_PER_SEASON = 73 DAYS_PER_WEEK = 5 ST_TIBS_DAY_OF_YEAR = 60   def initialize(year, m...
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...
#Scala
Scala
object Dijkstra {   type Path[Key] = (Double, List[Key])   def Dijkstra[Key](lookup: Map[Key, List[(Double, Key)]], fringe: List[Path[Key]], dest: Key, visited: Set[Key]): Path[Key] = fringe match { case (dist, path) :: fringe_rest => path match {case key :: path_rest => if (key == dest) (dist, path.rever...
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...
#PL.2FM
PL/M
100H: /* SHOW THE DIGITAL ROOT AND PERSISTENCE OF SOME NUMBERS */   /* BDOS SYSTEM CALL */ BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END; /* PRINTS A BYTE AS A CHARACTER */ PRINT$CHAR: PROCEDURE( CH ); DECLARE CH BYTE; CALL BDOS( 2, CH ); END; /* PRINTS A BYTE AS A NU...
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...
#Potion
Potion
digital = (x) : dr = x string # Digital Root. ap = 0 # Additive Persistence. while (dr length > 1) : sum = 0 dr length times (i): sum = sum + dr(i) number integer. dr = sum string ap++ . (x, " has additive persistence ", ap, " and digital root ", dr, ";\n") join print .   ...
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...
#UNIX_Shell
UNIX Shell
#!/bin/bash   # NAMES is a list of names. It can be changed as needed. It can be more than five names, or less. NAMES=(Baker Cooper Fletcher Miller Smith)   # CRITERIA are the rules imposed on who lives where. Each criterion must be a valid bash expression # that will be evaluated. TOP is the top floor; BOTTOM is t...
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 ...
#Maxima
Maxima
[1, 3, -5] . [4, -2, -1]; /* 3 */
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 ...
#Mercury
Mercury
:- module dot_product. :- interface.   :- import_module io. :- pred main(io::di, io::uo) is det.   :- implementation. :- import_module int, list.   main(!IO) :- io.write_int([1, 3, -5] `dot_product` [4, -2, -1], !IO), io.nl(!IO).   :- func dot_product(list(int), list(int)) = int.   dot_product(As, Bs) = lis...
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...
#Factor
Factor
USING: formatting io kernel math math.combinatorics math.ranges sequences sets ; IN: rosetta-code.department-numbers   7 [1,b] 3 <k-permutations> [ [ first even? ] [ sum 12 = ] bi and ] filter   "{ Police, Sanitation, Fire }" print nl [ "%[%d, %]\n" printf ] each
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...
#Fermat
Fermat
!!'Police Sanitation Fire'; !!'------|----------|----'; for p = 2 to 6 by 2 do for s = 1 to 7 do for f = 1 to 7 do if p+f+s=12 and f<>p and f<>s and s<>p then !!(' ',p,' ',s,' ',f); fi od od od;