task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Digital_root
Digital root
The digital root, X {\displaystyle X} , of a number, n {\displaystyle n} , is calculated: find X {\displaystyle X} as the sum of the digits of n {\displaystyle n} find a new X {\displaystyle X} by summing the digits of X {\displaystyle X} , repeating until X {\displ...
#Forth
Forth
: (Sdigit) 0 swap begin base @ /mod >r + r> dup 0= until drop ; : digiroot 0 swap begin (Sdigit) >r 1+ r> dup base @ < until ;
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...
#Fortran
Fortran
  program prec implicit none integer(kind=16) :: i i = 627615 call root_pers(i) i = 39390 call root_pers(i) i = 588225 call root_pers(i) i = 393900588225 call root_pers(i) end program   subroutine root_pers(i) implicit none integer(kind=16) :: N, s, a, i write(*,*) 'Number: ', i n = i a = 0 do while(n.ge.10) a = a + ...
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root
Digital root/Multiplicative digital root
The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i {\displaystyle i} to 0 ...
#Quackery
Quackery
[ abs 1 swap [ base share /mod rot * swap dup 0 = until ] drop ] is digitproduct ( n --> n )   [ 0 swap [ dup base share > while dip 1+ digitproduct again ] ] is mdr ( n --> n n )   [ dup mdr rot echo say ": " swap echo ...
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root
Digital root/Multiplicative digital root
The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i {\displaystyle i} to 0 ...
#Racket
Racket
#lang racket (define (digital-product n) (define (inr-d-p m rv) (cond [(zero? m) rv] [else (define-values (q r) (quotient/remainder m 10)) (if (zero? r) 0 (inr-d-p q (* rv r)))])) ; lazy on zero (inr-d-p n 1))   (define (mdr/mp n) (define (inr-mdr/mp m i) (if (< m 10) (values m 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...
#Kotlin
Kotlin
// version 1.1.3   typealias Predicate = (List<String>) -> Boolean   fun <T> permute(input: List<T>): List<List<T>> { if (input.size == 1) return listOf(input) val perms = mutableListOf<List<T>>() val toInsert = input[0] for (perm in permute(input.drop(1))) { for (i in 0..perm.size) { ...
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 ...
#FunL
FunL
import lists.zipWith   def dot( a, b ) | a.length() == b.length() = sum( zipWith((*), a, b) ) | otherwise = error( "Vector sizes must match" )   println( dot([1, 3, -5], [4, -2, -1]) )
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot ...
#FreeBASIC
FreeBASIC
#define NAN 0.0/0.0 'dot product of different-dimensioned vectors is no more defined than 0/0   function dot( a() as double, b() as double ) as double if ubound(a)<>ubound(b) then return NAN dim as uinteger i dim as double dp = 0.0 for i = 0 to ubound(a) dp += a(i)*b(i) next i retur...
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...
#FreeBASIC
FreeBASIC
  function squeeze(byval s as string,target as string) as string dim as string g dim as long n for n =0 to len(s)-2 if s[n]=asc(target) then if s[n]<>s[n+1] then g+=chr(s[n]) else g+=chr(s[n]) end if next n if len(s) then g+=chr(s...
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 ...
#Elixir
Elixir
defmodule Deming do def funnel(dxs, rule) do {_, rxs} = Enum.reduce(dxs, {0, []}, fn dx,{x,rxs} -> {rule.(x, dx), [x + dx | rxs]} end) rxs end   def mean(xs), do: Enum.sum(xs) / length(xs)   def stddev(xs) do m = mean(xs) Enum.reduce(xs, 0.0, fn x,sum -> sum + (x-m)*(x-m) / length(xs) ...
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 ...
#Factor
Factor
USING: combinators formatting generalizations grouping.extras io kernel math math.statistics sequences ;   : show ( seq1 seq2 -- ) [ [ mean ] bi@ ] [ [ population-std ] bi@ ] 2bi "Mean x, y : %.4f, %.4f\nStd dev x, y : %.4f, %.4f\n" printf ;   { -0.533 0.270 0.859 -0.043 -0.205 -0.127 -0.071 0.275...
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...
#8080_Assembly
8080 Assembly
org 100h lxi h,obuf ; HL = output buffer mvi b,2 ; B = police pol: mvi c,1 ; C = sanitation san: mvi d,1 ; D = fire fire: mov a,b ; Fire equal to police? cmp d jz next ; If so, invalid combination mov a,c ; Fire equal to sanitation? cmp d jz next ; If so, invalid combination mov a,b ; Total equal to 12? add c...
http://rosettacode.org/wiki/Descending_primes
Descending primes
Generate and show all primes with strictly descending decimal digits. See also OEIS:A052014 - Primes with distinct digits in descending order Related Ascending primes
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Sort[Select[FromDigits/@Subsets[Range[9,1,-1],{1,\[Infinity]}],PrimeQ]]
http://rosettacode.org/wiki/Descending_primes
Descending primes
Generate and show all primes with strictly descending decimal digits. See also OEIS:A052014 - Primes with distinct digits in descending order Related Ascending primes
#Perl
Perl
#!/usr/bin/perl   use strict; # https://rosettacode.org/wiki/Descending_primes use warnings; use ntheory qw( is_prime );   print join('', sort map { sprintf "%9d", $_ } grep /./ && is_prime($_), glob join '', map "{$_,}", reverse 1 .. 9) =~ s/.{45}\K/\n/gr;
http://rosettacode.org/wiki/Descending_primes
Descending primes
Generate and show all primes with strictly descending decimal digits. See also OEIS:A052014 - Primes with distinct digits in descending order Related Ascending primes
#Phix
Phix
with javascript_semantics function descending_primes(sequence res, atom p=0, max_digit=9) for d=1 to max_digit do atom np = p*10+d if odd(d) and is_prime(np) then res &= np end if res = descending_primes(res,np,d-1) end for return res end function sequence r = sort(descending_prime...
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 ...
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure Delegation is package Things is -- We need a common root for our stuff type Object is tagged null record; type Object_Ptr is access all Object'Class;   -- Objects that have operation thing type Substantial is new Object with null record; ...
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)...
#D
D
import std.stdio; import std.typecons;   alias Pair = Tuple!(real, real);   struct Triangle { Pair p1; Pair p2; Pair p3;   void toString(scope void delegate(const(char)[]) sink) const { import std.format; sink("Triangle: "); formattedWrite!"%s"(sink, p1); sink(", "); ...
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.
#Action.21
Action!
PROC Dir(CHAR ARRAY filter) CHAR ARRAY line(255) BYTE dev=[1]   Close(dev) Open(dev,filter,6) DO InputSD(dev,line) PrintE(line) IF line(0)=0 THEN EXIT FI OD Close(dev) RETURN   PROC DeleteFile(CHAR ARRAY fname) BYTE dev=[1]   Close(dev) Xio(dev,0,33,0,0,fname) RETURN   PROC Mai...
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.
#Ada
Ada
with Ada.Directories; use Ada.Directories;
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 ...
#EchoLisp
EchoLisp
  (lib 'list) (lib 'matrix)   ;; adapted from Racket (define (permanent M) (let (( n (matrix-row-num M))) (for/sum ([σ (in-permutations n)]) (for/product ([i n] [σi σ]) (array-ref M i σi)))))   ;; output (define A (list->array '(1 2 3 4) 2 2)) (array-print A) 1 2 3 4 (determinant 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.
#C
C
#include <limits.h> /* INT_MIN */ #include <setjmp.h> /* siglongjmp(), sigsetjmp() */ #include <stdio.h> /* perror(), printf() */ #include <stdlib.h> /* exit() */ #include <signal.h> /* sigaction(), sigemptyset() */   static sigjmp_buf fpe_env;   /* * This SIGFPE handler jumps to fpe_env. * * A SIGFPE handler must n...
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric
Determine if a string is numeric
Task Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings. Other tasks related to string operations: Metrics Array length String length Cop...
#AWK
AWK
  $ awk 'function isnum(x){return(x==x+0)} BEGIN{print isnum("hello"),isnum("-42")}'  
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 ...
#C.2B.2B
C++
#include <iostream> #include <string>   void string_has_repeated_character(const std::string& str) { size_t len = str.length(); std::cout << "input: \"" << str << "\", length: " << len << '\n'; for (size_t i = 0; i < len; ++i) { for (size_t j = i + 1; j < len; ++j) { if (str[i] == str[j]...
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...
#Factor
Factor
USING: formatting io kernel sbufs sequences strings ; IN: rosetta-code.string-collapse   : (collapse) ( str -- str ) unclip-slice 1string >sbuf [ over last over = [ drop ] [ suffix! ] if ] reduce >string ;   : collapse ( str -- str ) [ "" ] [ (collapse) ] if-empty ;   : .str ( str -- ) dup length "«««%s»»» (len...
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...
#FreeBASIC
FreeBASIC
Const numCad = 5 Data "" Data "'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln " Data "..1111111111111111111111111111111111111111111111111111111111111117777888" Data "I never give 'em hell, I just tell the truth, and they think it's hell. " Data " ...
http://rosettacode.org/wiki/Dice_game_probabilities
Dice game probabilities
Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six. They roll their dice and sum the totals of the faces. The player with the highest total wins (i...
#zkl
zkl
fcn combos(sides, n){ if(not n) return(T(1)); ret:=((0).max(sides)*n + 1).pump(List(),0); foreach i,v in (combos(sides, n - 1).enumerate()){ if(not v) continue; foreach s in (sides){ ret[i + s] += v } } ret }   fcn winning(sides1,n1, sides2,n2){ p1, p2 := combos(sides1, n1), combos(sides2,...
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...
#Delphi
Delphi
  program Determine_if_a_string_has_all_the_same_characters;   {$APPTYPE CONSOLE}   uses System.SysUtils;   procedure Analyze(s: string); var b, c: char; i: Integer; begin writeln(format('Examining [%s] which has a length of %d:', [s, s.Length])); if s.Length > 1 then begin b := s[1]; for i := 2 to ...
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...
#Kotlin
Kotlin
// Version 1.2.31   import java.util.Random import java.util.concurrent.locks.Lock import java.util.concurrent.locks.ReentrantLock   val rand = Random()   class Fork(val name: String) { val lock = ReentrantLock()   fun pickUp(philosopher: String) { lock.lock() println(" $philosopher picked up $...
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#JotaCode
JotaCode
@print( "Today is ", @let(1,@add(@switch(@time("mon"), 0,-1, 1,30, 2,58, 3,89, 4,119, 5,150, 6,180, 7,211, 8,242, 9,272, 10,303, 11,333) ,@time("mday")),@switch(@print(@time("mon"),"/",@time("mday")), "1/29","St. Tib's Day", @print(@switch(@mod("%1",5), 0,"S...
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...
#M2000_Interpreter
M2000 Interpreter
  Module Dijkstra`s_algorithm { const max_number=1.E+306 GetArr=lambda (n, val)->{ dim d(n)=val =d() } term=("",0) Edges=(("a", ("b",7),("c",9),("f",14)),("b",("c",10),("d",15)),("c",("d",11),("f",2)),("d",("e",6)),("e",("f", 9)),("f",term)) Document Doc$="Graph:"+{ } ShowGraph() Doc$="Paths"+{ } Print "...
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...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Function digitalRoot(n As UInteger, ByRef ap As Integer, base_ As Integer = 10) As Integer Dim dr As Integer ap = 0 Do dr = 0 While n > 0 dr += n Mod base_ n = n \ base_ Wend ap += 1 n = dr Loop until dr < base_ Return dr End Function   Dim As Integer dr, ...
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root
Digital root/Multiplicative digital root
The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i {\displaystyle i} to 0 ...
#Raku
Raku
sub multiplicative-digital-root(Int $n) { return .elems - 1, .[.end] given cache($n, {[*] .comb} ... *.chars == 1) }   for 123321, 7739, 893, 899998 { say "$_: ", .&multiplicative-digital-root; }   for ^10 -> $d { say "$d : ", .[^5] given (1..*).grep: *.&multiplicative-digital-root[1] == $d;...
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...
#Lua
Lua
local wrap, yield = coroutine.wrap, coroutine.yield local function perm(n) local r = {} for i=1,n do r[i]=i end return wrap(function() local function swap(m) if m==0 then yield(r) else for i=m,1,-1 do r[i],r[m]=r[m],r[i] swap(m-1) r[i],...
http://rosettacode.org/wiki/Dot_product
Dot product
Task Create a function/use an in-built function, to compute the   dot product,   also known as the   scalar product   of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors:   [1,  3, -5]     and   [4, -2, -1] If implementing the dot ...
#F.C5.8Drmul.C3.A6
Fōrmulæ
# Built-in   [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 ...
#GAP
GAP
# Built-in   [1, 3, -5]*[4, -2, -1]; # 3
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...
#Frink
Frink
squeeze[str, ch] := { println["Use: '$ch'"] println["old: " + length[str] + " <<<$str>>>"] str =~ subst["($ch)\\1+", "$$1", "g"] println["new: " + length[str] + " <<<$str>>>"] }   lines = [["", [""]], [""""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln """, ["-"]], ["..11111...
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...
#Go
Go
package main   import "fmt"   // Returns squeezed string, original and new lengths in // unicode code points (not normalized). func squeeze(s string, c rune) (string, int, int) { r := []rune(s) le, del := len(r), 0 for i := le - 2; i >= 0; i-- { if r[i] == c && r[i] == r[i+1] { copy(r[i:...
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 ...
#Go
Go
package main   import ( "fmt" "math" )   type rule func(float64, float64) float64   var dxs = []float64{ -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, ...
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...
#8086_Assembly
8086 Assembly
cpu 8086 bits 16 org 100h section .text mov di,obuf ; Output buffer mov bl,2 ; BL = police pol: mov cl,1 ; CL = sanitation san: mov dl,1 ; DL = fire fire: cmp bl,cl ; Police equal to sanitation? je next ; Invalid combination cmp bl,dl ; Police equal to fire? je next ; Invalid combination cmp cl,dl ; S...
http://rosettacode.org/wiki/Descending_primes
Descending primes
Generate and show all primes with strictly descending decimal digits. See also OEIS:A052014 - Primes with distinct digits in descending order Related Ascending primes
#Picat
Picat
import util.   main => DP = [N : S in power_set("987654321"), S != [], N = S.to_int, prime(N)].sort, foreach({P,I} in zip(DP,1..DP.len)) printf("%9d%s",P,cond(I mod 10 == 0,"\n","")) end, nl, println(len=DP.len).
http://rosettacode.org/wiki/Descending_primes
Descending primes
Generate and show all primes with strictly descending decimal digits. See also OEIS:A052014 - Primes with distinct digits in descending order Related Ascending primes
#Python
Python
from sympy import isprime   def descending(xs=range(10)): for x in xs: yield x yield from descending(x*10 + d for d in range(x%10))   for i, p in enumerate(sorted(filter(isprime, descending()))): print(f'{p:9d}', end=' ' if (1 + i)%8 else '\n')   print()
http://rosettacode.org/wiki/Descending_primes
Descending primes
Generate and show all primes with strictly descending decimal digits. See also OEIS:A052014 - Primes with distinct digits in descending order Related Ascending primes
#Raku
Raku
put (flat 2, 3, 5, 7, sort +*, gather (3..9).map: &recurse ).batch(10)».fmt("%8d").join: "\n";   sub recurse ($str) { .take for ($str X~ (1, 3, 7)).grep: { .is-prime && [>] .comb }; recurse $str × 10 + $_ for 2 ..^ $str % 10; }
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 ...
#Aikido
Aikido
  class Delegator { public generic delegate = none   public function operation { if (typeof(delegate) == "none") { return "default implementation" } return delegate() } }   function thing { return "delegate implementation" }   // default, no delegate var d = new Deleg...
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 ...
#Aime
Aime
text thing(void) { return "delegate implementation"; }   text operation(record delegator) { text s;   if (r_key(delegator, "delegate")) { if (r_key(delegator["delegate"], "thing")) { s = call(r_query(delegator["delegate"], "thing")); } else { s = "default implementati...
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 ...
#ALGOL_68
ALGOL 68
# An Algol 68 approximation of delegates #   # The delegate mode - the delegate is a STRUCT with a single field # # that is a REF PROC STRING. If this is NIL, it doesn't implement # # thing # MODE DELEGATE = STRUC...
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)...
#Delphi
Delphi
open System   type Point = double * double type Triangle = Point * Point * Point   let Det2D (t:Triangle) = let (p1, p2, p3) = t let (p1x, p1y) = p1 let (p2x, p2y) = p2 let (p3x, p3y) = p3   p1x * (p2y - p3y) + p2x * (p3y - p1y) + p3x * (p1y - p2y)   let CheckTriWinding allowReversed 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.
#Aikido
Aikido
  remove ("input.txt") remove ("/input.txt") remove ("docs") remove ("/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.
#Aime
Aime
remove("input.txt"); remove("/input.txt"); remove("docs"); remove("/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 ...
#Factor
Factor
USING: fry kernel math.combinatorics math.matrices sequences ;   : permanent ( matrix -- x ) dup square-matrix? [ "Matrix must be square." throw ] unless [ dim first <iota> ] keep '[ [ _ nth nth ] map-index product ] map-permutations sum ;
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 ...
#Forth
Forth
S" fsl-util.fs" REQUIRED S" fsl/dynmem.seq" REQUIRED [UNDEFINED] defines [IF] SYNONYM defines IS [THEN] S" fsl/structs.seq" REQUIRED S" fsl/lufact.seq" REQUIRED S" fsl/dets.seq" REQUIRED S" permute.fs" REQUIRED   VARIABLE the-mat : add-perm ( p0 p1 p2 ... pn n s -- ) DROP \ sign 1E 1 DO the-mat @ SWAP 1- I 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.
#C.23
C#
using System;   namespace RosettaCode { class Program { static void Main(string[] args) { int x = 1; int y = 0; try { int z = x / y; } catch (DivideByZeroException e) { Console.WriteLine(e); }   } } }
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.
#C.2B.2B
C++
  #include<iostream> #include<csignal> /* for signal */ #include<cstdlib>   using namespace std;   void fpe_handler(int signal) { cerr << "Floating Point Exception: division by zero" << endl; exit(signal); }   int main() { // Register floating-point exception handler. signal(SIGFPE, fpe_handler);   ...
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...
#BaCon
BaCon
INPUT "Your string: ", s$   IF REGEX(s$, "^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$") THEN PRINT "This is a number" ELSE PRINT "Not a number" ENDIF
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...
#BASIC
BASIC
10 INPUT "Enter a string";S$:GOSUB 1000 20 IF R THEN PRINT "Is num" ELSE PRINT"Not num" 99 END 1000 T1=VAL(S$):T1$=STR$(T1) 1010 R=T1$=S$ OR T1$=" "+S$ 1099 RETURN
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 ...
#Clojure
Clojure
  (defn uniq-char-string [s] (let [len (count s)] (if (= len (count (set s))) (println (format "All %d chars unique in: '%s'" len s)) (loop [prev-chars #{} idx 0 chars (vec s)] (let [c (first chars)] (if (contains? prev-chars c) (println (forma...
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...
#Frink
Frink
collapse[str] := str =~ %s/(.)\1+/$1/g   lines = ["", """"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln """, "..1111111111111111111111111111111111111111111111111111111111111117777888", "I never give 'em hell, I just tell the truth, and they think it's hell. ", " ...
http://rosettacode.org/wiki/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...
#Go
Go
package main   import "fmt"   // Returns collapsed string, original and new lengths in // unicode code points (not normalized). func collapse(s string) (string, int, int) { r := []rune(s) le, del := len(r), 0 for i := le - 2; i >= 0; i-- { if r[i] == r[i+1] { copy(r[i:], r[i+1:]) ...
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...
#Erlang
Erlang
  -module(string_examples). -export([examine_all_same/1, all_same_examples/0]).   all_same_characters([], _Offset) -> all_same; all_same_characters([_], _Offset) -> all_same; all_same_characters([X, X | Rest], Offset) -> all_same_characters([X | Rest], Offset + 1); all_same_characters([X, Y | _Rest], Offset...
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...
#Logtalk
Logtalk
:- category(chopstick).   % chopstick actions (picking up and putting down) are synchronized using a notification % such that a chopstick can only be handled by a single philosopher at a time:   :- public(pick_up/0). pick_up :- threaded_wait(available).   :- public(put_down/0). put_down ...
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#Julia
Julia
using Dates   function discordiandate(year::Integer, month::Integer, day::Integer) discordianseasons = ["Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"] holidays = Dict( "Chaos 5" => "Mungday", "Chaos 50" => "Chaoflux", "Discord 5" => "Mojoday", "Discord 50" => "D...
http://rosettacode.org/wiki/Dijkstra%27s_algorithm
Dijkstra's algorithm
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path pro...
#Maple
Maple
restart: with(GraphTheory): G:=Digraph([a,b,c,d,e,f],{[[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]}): DijkstrasAlgorithm(G,a); # [[[a], 0], [[a, b], 7], [[a, c], 9], [[a, c, d], 20], [[a, c, d, e], 26], [[a, c, f], 11]]
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...
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import ( "fmt" "log" "strconv" )   func Sum(i uint64, base int) (sum int) { b64 := uint64(base) for ; i > 0; i /= b64 { sum += int(i % b64) } return }   func DigitalRoot(n uint64, base int) (persistence, root int) { root = int(n) for x := n; x >= uint64(base); x = uint64(root) { root = Sum(x...
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root
Digital root/Multiplicative digital root
The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i {\displaystyle i} to 0 ...
#Red
Red
Red ["Multiplicative digital root"]   mdr: function [ "Returns a block containing the mdr and persistence of an integer" n [integer!] ][ persistence: 0 while [n > 10][ product: 1 m: n while [m > 0][ product: m % 10 * product m: to-integer m / 10 ] ...
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
  {Baker, Cooper, Fletcher, Miller, Smith}; (Unequal @@ %) && (And @@ (0 < # < 6 & /@ %)) && Baker < 5 && Cooper > 1 && 1 < Fletcher < 5 && Miller > Cooper && Abs[Smith - Fletcher] > 1 && Abs[Cooper - Fletcher] > 1 // Reduce[#, %, Integers] &  
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 ...
#GLSL
GLSL
  float dot_product = dot(vec3(1, 3, -5), vec3(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...
#Groovy
Groovy
class StringSqueezable { static void main(String[] args) { String[] testStrings = [ "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I...
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 ...
#Haskell
Haskell
import Data.List (mapAccumL, genericLength) import Text.Printf   funnel :: (Num a) => (a -> a -> a) -> [a] -> [a] funnel rule = snd . mapAccumL (\x dx -> (rule x dx, x + dx)) 0   mean :: (Fractional a) => [a] -> a mean xs = sum xs / genericLength xs   stddev :: (Floating a) => [a] -> a stddev xs = sqrt $ sum [(x-m)**2...
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...
#Action.21
Action!
PROC Main() BYTE p,s,f   PrintE("P S F") FOR p=2 TO 6 STEP 2 DO FOR s=1 TO 7 DO FOR f=1 TO 7 DO IF p#s AND p#f AND s#f AND p+s+f=12 THEN PrintF("%B %B %B%E",p,s,f) FI OD OD OD RETURN
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...
#Ada
Ada
with Ada.Text_IO;   procedure Department_Numbers is use Ada.Text_IO; begin Put_Line (" P S F"); for Police in 2 .. 6 loop for Sanitation in 1 .. 7 loop for Fire in 1 .. 7 loop if Police mod 2 = 0 and Police + Sanitation + Fire = 12 and ...
http://rosettacode.org/wiki/Descending_primes
Descending primes
Generate and show all primes with strictly descending decimal digits. See also OEIS:A052014 - Primes with distinct digits in descending order Related Ascending primes
#Ring
Ring
  load "stdlibcore.ring"   limit = 1000 row = 0   for n = 1 to limit flag = 0 strn = string(n) if isprime(n) = 1 for m = 1 to len(strn)-1 if number(substr(strn,m)) < number(substr(strn,m+1)) flag = 1 ok next if flag = 1 row++ see "...
http://rosettacode.org/wiki/Descending_primes
Descending primes
Generate and show all primes with strictly descending decimal digits. See also OEIS:A052014 - Primes with distinct digits in descending order Related Ascending primes
#Sidef
Sidef
func primes_with_descending_digits(base = 10) {   var list = [] var digits = @(1..^base)   var end_digits = digits.grep { .is_coprime(base) } list << digits.grep { .is_prime && !.is_coprime(base) }...   for k in (0 .. digits.end) { digits.combinations(k, {|*a| var v = a.digits2nu...
http://rosettacode.org/wiki/Descending_primes
Descending primes
Generate and show all primes with strictly descending decimal digits. See also OEIS:A052014 - Primes with distinct digits in descending order Related Ascending primes
#Wren
Wren
import "./perm" for Powerset import "./math" for Int import "./seq" for Lst import "./fmt" for Fmt   var ps = Powerset.list((9..1).toList) var descPrimes = ps.skip(1).map { |s| Num.fromString(s.join()) } .where { |p| Int.isPrime(p) } .toList ...
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 ...
#Atari_Basic
Atari Basic
  10 REM DELEGATION CODE AND EXAMPLE . ATARI BASIC 2020 A. KRESS andreas.kress@hood-group.com 14 REM 15 GOTO 100:REM MAINLOOP 16 REM 20 REM DELEGATOR OBJECT 21 REM 30 IF DELEGATE THEN GOSUB DELEGATE:GOTO 56 35 REM 50 REM DELEGATOR HAS TO DO THE JOB 55 PRINT "DEFAULT IMPLEMENTATION - DONE BY DELEGATOR" 56 RETURN 60...
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 ...
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h>   typedef const char * (*Responder)( int p1);   typedef struct sDelegate { Responder operation; } *Delegate;   /* Delegate class constructor */ Delegate NewDelegate( Responder rspndr ) { Delegate dl = malloc(sizeof(struct sDelegate)); dl->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)...
#F.23
F#
open System   type Point = double * double type Triangle = Point * Point * Point   let Det2D (t:Triangle) = let (p1, p2, p3) = t let (p1x, p1y) = p1 let (p2x, p2y) = p2 let (p3x, p3y) = p3   p1x * (p2y - p3y) + p2x * (p3y - p1y) + p3x * (p1y - p2y)   let CheckTriWinding allowReversed 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.
#ALGOL_68
ALGOL 68
main:( PROC remove = (STRING file name)INT: BEGIN FILE actual file; INT errno = open(actual file, file name, stand back channel); IF errno NE 0 THEN stop remove FI; scratch(actual file); # detach the book and burn it # errno EXIT stop remove: errno END; remove("input.txt"); remo...
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.
#ARM_Assembly
ARM Assembly
  /* ARM assembly Raspberry PI */ /* program deleteFic.s */   /* REMARK 1 : this program use routines in a include file see task Include a file language arm assembly for the routine affichageMess conversion10 see at end of this program the instruction include */ /****************************************...
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 ...
#Fortran
Fortran
  !-*- mode: compilation; default-directory: "/tmp/" -*- !Compilation started at Sat May 18 23:25:42 ! !a=./F && make $a && $a < unixdict.txt !f95 -Wall -ffree-form F.F -o F ! j example, determinant: 7.00000000 ! j example, permanent: 5.00000000 ! maxima, determinant: -360.000000 ! maxima, perm...
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.
#Ceylon
Ceylon
shared void run() {   //integers divided by zero throw an exception try { value a = 1 / 0; } catch (Exception e) { e.printStackTrace(); }   //floats divided by zero produce infinity print(1.0 / 0 == infinity then "division by zero!" else "not division 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.
#Clojure
Clojure
(defn safe-/ [x y] (try (/ x y) (catch ArithmeticException _ (println "Division by zero caught!") (cond (> x 0) Double/POSITIVE_INFINITY (zero? x) Double/NaN :else Double/NEGATIVE_INFINITY) )))
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...
#Batch_File
Batch File
set /a a=%arg%+0 >nul if %a% == 0 ( if not "%arg%"=="0" ( echo Non Numeric. ) else ( echo Numeric. ) ) else ( echo 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...
#BBC_BASIC
BBC BASIC
REPEAT READ N$ IF FN_isanumber(N$) THEN PRINT "'" N$ "' is a number" ELSE PRINT "'" N$ "' is NOT a number" ENDIF UNTIL N$ = "end" END   DATA "PI", "0123", "-0123", "12.30", "-12.30", "123!", "0" DATA "0.0", ".123", "-.123", "12E3", "12E-3...
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 ...
#Common_Lisp
Common Lisp
;; * Loading the iterate library (eval-when (:compile-toplevel :load-toplevel) (ql:quickload '("iterate")))   ;; * The package definition (defpackage :unique-string (:use :common-lisp :iterate)) (in-package :unique-string)   ;; * The test strings (defparameter test-strings '("" "." "abcABC" "XYZ ZYX" "1234567890A...
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...
#Groovy
Groovy
class StringCollapsible { static void main(String[] args) { for ( String s : [ "", "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", "..1111111111111111111111111111111111111111111111111111111111111117777888", "I neve...
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...
#F.23
F#
  // Determine if a string has all the same characters. Nigel Galloway: June 9th., 2020 let fN n=if String.length n=0 then None else n.ToCharArray()|>Array.tryFindIndex(fun g->g<>n.[0])   let allSame n=match fN n with Some g->printfn "First different character in <<<%s>>> (length %d) is hex %x at positio...
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...
#Factor
Factor
USING: formatting io kernel math.parser sequences ;   : find-diff ( str -- i elt ) dup ?first [ = not ] curry find ; : len. ( str -- ) dup length "%u — length %d — " printf ; : same. ( -- ) "contains all the same character." print ; : diff. ( -- ) "contains a different character at " write ;   : not-same. ( i elt -- ) ...
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...
#M2000_Interpreter
M2000 Interpreter
  Module Dining_philosophers (whichplan) { Form 80, 32 Const MayChangePick=Random(True, False) dim energy(1 to 5)=50 Document Doc$ const nl$={ } Print $(,12), ' set column width to 12 Pen 14 Pen 15 { Doc$="Dining Philosophers"+nl$ \\ we can change thread plan only if no threads defined if whichplan=1 th...
http://rosettacode.org/wiki/Discordian_date
Discordian date
Task Convert a given date from the   Gregorian calendar   to the   Discordian calendar.
#Kotlin
Kotlin
import java.util.Calendar import java.util.GregorianCalendar   enum class Season { Chaos, Discord, Confusion, Bureaucracy, Aftermath; companion object { fun from(i: Int) = values()[i / 73] } } enum class Weekday { Sweetmorn, Boomtime, Pungenday, Prickle_Prickle, Setting_Orange; companion object { fun fr...
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...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
bd = Graph[{"a" \[DirectedEdge] "b", "a" \[DirectedEdge] "c", "b" \[DirectedEdge] "c", "b" \[DirectedEdge] "d", "c" \[DirectedEdge] "d", "d" \[DirectedEdge] "e", "a" \[DirectedEdge] "f", "c" \[DirectedEdge] "f", "e" \[DirectedEdge] "f"}, EdgeWeight -> {7, 9, 10, 15, 11, 6, 14, 2, 9}, VertexLabels ...
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...
#Go
Go
package main   import ( "fmt" "log" "strconv" )   func Sum(i uint64, base int) (sum int) { b64 := uint64(base) for ; i > 0; i /= b64 { sum += int(i % b64) } return }   func DigitalRoot(n uint64, base int) (persistence, root int) { root = int(n) for x := n; x >= uint64(base); x = uint64(root) { root = Sum(x...
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root
Digital root/Multiplicative digital root
The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number, n {\displaystyle n} , is calculated rather like the Digital root except digits are multiplied instead of being added: Set m {\displaystyle m} to n {\displaystyle n} and i {\displaystyle i} to 0 ...
#REXX
REXX
/*REXX program finds the persistence and multiplicative digital root of some numbers.*/ numeric digits 100 /*increase the number of decimal digits*/ parse arg x /*obtain optional arguments from the CL*/ if x='' | x="," then x=123321 7739 893 899998 ...
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...
#MiniZinc
MiniZinc
  %Dinesman's multiple-dwelling problem. Nigel Galloway, September 25th., 2020 include "alldifferent.mzn"; enum names={Baker,Cooper,Miller,Smith,Fletcher}; array[names] of var 1..5: res; constraint alldifferent([res[n] | n in names]); constraint res[Baker]  !=5; constraint res[Cooper]  !=1; constraint res[Fletcher] ...
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 ...
#Go
Go
package main   import ( "errors" "fmt" "log" )   var ( v1 = []int{1, 3, -5} v2 = []int{4, -2, -1} )   func dot(x, y []int) (r int, err error) { if len(x) != len(y) { return 0, errors.New("incompatible lengths") } for i, xi := range x { r += xi * y[i] } return }   ...
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...
#Haskell
Haskell
import Text.Printf (printf)   input :: [(String, Char)] input = [ ("", ' ') , ("The better the 4-wheel drive, the further you'll be from help when ya get stuck!", 'e') , ("headmistressship", 's') , ("\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ", '-') , (".....
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 ...
#J
J
  dx=:".0 :0-.LF _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 _0.182 0.287 0.213 _0.423 _0.021 _0.134 1.798 0.021 _1.099 _0.361 1.636 ...
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...
#Aime
Aime
integer p, s, f;   p = 0; while ((p += 2) <= 7) { s = 0; while ((s += 1) <= 7) { f = 0; while ((f += 1) <= 7) { if (p + s + f == 12 && p != s && p != f && s != f) { o_form(" ~ ~ ~\n", p, s, f); } } } }
http://rosettacode.org/wiki/Descending_primes
Descending primes
Generate and show all primes with strictly descending decimal digits. See also OEIS:A052014 - Primes with distinct digits in descending order Related Ascending primes
#XPL0
XPL0
include xpllib; \provides IsPrime and Sort   int I, N, Mask, Digit, A(512), Cnt; [for I:= 0 to 511 do [N:= 0; Mask:= I; Digit:= 9; while Mask do [if Mask&1 then N:= N*10 + Digit; Mask:= Mask>>1; Digit:= Digit-1; ]; A(I):= N; ]; Sort(A, 512); Cnt:= 0...
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 ...
#C.23
C#
using System;   interface IOperable { string Operate(); }   class Inoperable { }   class Operable : IOperable { public string Operate() { return "Delegate implementation."; } }   class Delegator : IOperable { object Delegate;   public string Operate() { var operable = Delegat...
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)...
#FreeBASIC
FreeBASIC
#macro min(x,y) Iif(x>y,y,x) #endmacro #macro max(x,y) Iif(x>y,x,y) #endmacro   type pnt 'typedef for a point x as double y as double end type   type edg 'typedef for an edge p1 as pnt p2 as pnt end type   function point_in_tri( r as pnt, a as pnt, b as pnt, c as pnt ) as boolean 'uses baryc...
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.
#Arturo
Arturo
file: "input.txt" docs: "docs"   delete file delete.directory file   delete join.path ["/" file] delete.directory join.path ["/" 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.
#AutoHotkey
AutoHotkey
FileDelete, input.txt FileDelete, \input.txt FileRemoveDir, docs, 1 FileRemoveDir, \docs, 1