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/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 ... | #Stretch_2 | Stretch 2 |
ListPlot[MarblePositions[#][Transpose[{dxs,dys}]]&/@Range[4],PlotLegends->PointLegend[{1,2,3,4}],AspectRatio->Automatic,ImageSize->600]
|
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 ... | #Nim | Nim | import stats, strformat
type Rule = proc(x, y: float): float
const Dxs = [-0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,
1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,
-0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,
0.709, 0.... |
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... | #Arturo | Arturo | loop 1..7 'x [
loop 1..7 'y [
loop 1..7 'z [
if all? @[
even? x
12 = sum @[x y z]
3 = size unique @[x y z]
] -> print [x y z]
]
]
] |
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 ... | #Dart | Dart | class Delegator {
var delegate;
String operation() {
if (delegate == null)
return "default implementation";
else
return delegate.thing();
}
}
class Delegate {
String thing() => "delegate implementation";
}
main() {
// Without a delegate:
Delegator a = new Delegator();
Expect.equa... |
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 ... | #Delphi | Delphi | unit Printer;
interface
type
// the "delegate"
TRealPrinter = class
public
procedure Print;
end;
// the "delegator"
TPrinter = class
private
FPrinter: TRealPrinter;
public
constructor Create;
destructor Destroy; override;
procedure Print;
end;
implementation
{ TRealPrinte... |
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)... | #Java | Java | import java.util.function.BiFunction;
public class TriangleOverlap {
private static class Pair {
double first;
double second;
Pair(double first, double second) {
this.first = first;
this.second = second;
}
@Override
public String toString... |
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.
| #C.2B.2B | C++ | #include <cstdio>
#include <direct.h>
int main() {
remove( "input.txt" );
remove( "/input.txt" );
_rmdir( "docs" );
_rmdir( "/docs" );
return 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.
| #Clojure | Clojure | (import '(java.io File))
(.delete (File. "output.txt"))
(.delete (File. "docs"))
(.delete (new File (str (File/separator) "output.txt")))
(.delete (new File (str (File/separator) "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
... | #J | J | i. 5 5
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24 |
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
... | #Java | Java | import java.util.Scanner;
public class MatrixArithmetic {
public static double[][] minor(double[][] a, int x, int y){
int length = a.length-1;
double[][] result = new double[length][length];
for(int i=0;i<length;i++) for(int j=0;j<length;j++){
if(i<x && j<y){
result[i][j] = a[i][j];
}else if(i>=x && ... |
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.
| #Eiffel | Eiffel | class MAIN
creation main
feature main is
local
x, y: INTEGER;
retried: BOOLEAN;
do
x := 42;
y := 0;
if not retried then
io.put_real(x / y);
else
print("NaN%N");
end
rescu... |
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.
| #Ela | Ela | open core number
x /. y = try Some (x `div` y) with
_ = None
(12 /. 2, 12 /. 0) |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Cop... | #COBOL | COBOL | program-id. is-numeric.
procedure division.
display function test-numval-f("abc") end-display
display function test-numval-f("-123.01E+3") end-display
if function test-numval-f("+123.123") equal zero then
display "is numeric" end-display
else
displ... |
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... | #CoffeeScript | CoffeeScript |
console.log (isFinite(s) for s in [5, "5", "-5", "5", "5e5", 0]) # all true
console.log (isFinite(s) for s in [NaN, "fred", "###"]) # all false
|
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 ... | #Factor | Factor | USING: formatting fry generalizations io kernel math.parser
sequences sets ;
: repeated ( elt seq -- )
[ dup >hex over ] dip indices first2
" '%c' (0x%s) at indices %d and %d.\n" printf ;
: uniqueness-report ( str -- )
dup dup length "%u — length %d — contains " printf
[ duplicates ] keep over empt... |
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 ... | #Fortran | Fortran |
program demo_verify
implicit none
call nodup('')
call nodup('.')
call nodup('abcABC')
call nodup('XYZ ZYX')
call nodup('1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ')
contains
subroutine nodup(str)
character(len=*),intent(in) :: str
character(len=*),parameter :: g='(*(g0))'
character(len=:),allocatab... |
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... | #Ksh | Ksh |
#!/bin/ksh
# Determine if a string is collapsible (repeated letters)
# # Variables:
#
typeset -a strings
strings[0]=""
strings[1]='"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln'
strings[2]="..1111111111111111111111111111111111111111111111111111111111111117777888"
strings[3]="I never ... |
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... | #Lua | Lua | function collapse(s)
local ns = ""
local last = nil
for c in s:gmatch"." do
if last then
if last ~= c then
ns = ns .. c
end
last = c
else
ns = ns .. c
last = c
end
end
return ns
end
function test(s)... |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_the_same_characters | Determine if a string has all the same characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are the same
indicate if or which character is different from the previous character
display each string and its length (as the... | #J | J |
Doc=: 2 : 'u :: (n"_)'
task=: monad define
common=. (; #) y NB. the string and its length
if. same y do.
common , <'same'
else.
i =. differ y
c =. i { y
common , <((, (' (' , ') ' ,~ hex))c),'differs at index ',":i
end.
)
hex=: ((Num_j_,26}.Alpha_j_) {~ 16 16 #: a.&i.)&> Doc 'convert ASCII literals t... |
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... | #Java | Java | public class Main{
public static void main(String[] args){
String[] tests = {"", " ", "2", "333", ".55", "tttTTT", "4444 444k"};
for(String s:tests)
analyze(s);
}
public static void analyze(String s){
System.out.printf("Examining [%s] which has a length of %d:\n", s, s.length());
if(s.length() > 1){
... |
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... | #Oz | Oz | declare
Philosophers = [aristotle kant spinoza marx russell]
proc {Start}
Forks = {MakeList {Length Philosophers}}
in
{ForAll Forks NewFork}
for
Name in Philosophers
LeftFork in Forks
RightFork in {RightShift Forks}
do
thread
{Philosopher Name LeftF... |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Pascal | Pascal |
program ddate;
{
This program is free software, it's done it's time
and paid for it's crime. You can copy, edit and use this
software under the terms of the GNU GPL v3 or later.
Copyright Pope Englebert Finklestien,
On this day Boomtime, the 71st day of Confusion in the YOLD 3183
This program will print out the c... |
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... | #Pascal | Pascal | program dijkstra(output);
type
{ We dynamically build the list of vertices from the edge list,
just to avoid repeating ourselves in the graph input. Vertices are linked
together via their `next` pointers to form a list of all vertices (sorted by
name), while the `previous` pointer indicates the previous... |
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... | #JavaScript | JavaScript | /// Digital root of 'x' in base 'b'.
/// @return {addpers, digrt}
function digitalRootBase(x,b) {
if (x < b)
return {addpers:0, digrt:x};
var fauxroot = 0;
while (b <= x) {
x = (x / b) | 0;
fauxroot += x % b;
}
var rootobj = digitalRootBase(fauxroot,b);
rootobj.addpers += 1;
r... |
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
... | #Tcl | Tcl | proc mdr {n} {
if {$n < 0 || ![string is integer $n]} {
error "must be an integer"
}
for {set i 0} {$n > 9} {incr i} {
set n [tcl::mathop::* {*}[split $n ""]]
}
return [list $i $n]
} |
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem | Dinesman's multiple-dwelling problem | Task
Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below.
Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of... | #PicoLisp | PicoLisp | # Problem statement
(be dwelling (@Tenants)
(permute (Baker Cooper Fletcher Miller Smith) @Tenants)
(not (topFloor Baker @Tenants))
(not (bottomFloor Cooper @Tenants))
(not (or ((topFloor Fletcher @Tenants)) ((bottomFloor Fletcher @Tenants))))
(higherFloor Miller Cooper @Tenants)
(not (adjacentFloor S... |
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 ... | #IDL | IDL |
a = [1, 3, -5]
b = [4, -2, -1]
c = a#TRANSPOSE(b)
c = TOTAL(a*b,/PRESERVE_TYPE)
|
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... | #MATLAB_.2F_Octave | MATLAB / Octave |
function r = squeezee(s,c)
ix = [];
c = unique(c);
for k=1:length(c)
ix=[ix; find((s(1:end-1)==s(2:end)) & (s(1:end-1)==c(k)))+1];
end
r=s;
r(ix)=[];
fprintf(1,'Character to be squeezed: "%s"\n',c);
fprintf(1,'Input: <<<%s>>> length: %d\n',s,length(s));
fprintf(1,'Output: <<<%s>>> len... |
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... | #NetLogo | NetLogo |
to-report split [ string ]
;; utility reporter to split a string into a list
report n-values length string [ [ n ] -> item n string ]
end
to-report squeeze [ character string ]
;; reporter that actually does the squeeze function
;; remote immeadiately repeating instances of character from string
ifelse ... |
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 ... | #PARI.2FGP | PARI/GP | drop(drops, rule, rnd)={
my(v=vector(drops),target=0);
v[1]=rule(target, 0);
for(i=2,drops,
target=rule(target, v[i-1]);
v[i]=rnd(n)+target
);
v
};
R=[-.533-.136*I,.27-.717*I,.859-.459*I,-.043+.225*I,-.205-1.39*I,-.127-.385*I,-.071-.121*I,.275+.395*I,1.25-.490*I,-.231+.682*I,-.401+.0650*I,.269-.242*I,... |
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... | #Asymptote | Asymptote | write("--police-- --sanitation-- --fire--");
for(int police = 2; police < 6; police += 2) {
for(int sanitation = 1; sanitation < 7; ++sanitation) {
for(int fire = 1; fire < 7; ++fire) {
if(police != sanitation && sanitation != fire && fire != police && police+fire+sanitation == 12){
write(" "... |
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 ... | #E | E | def makeDelegator {
/** construct without an explicit delegate */
to run() {
return makeDelegator(null)
}
/** construct with a delegate */
to run(delegateO) { # suffix because "delegate" is a reserved keyword
def delegator {
to operation() {
return if (d... |
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 ... | #Elena | Elena | import extensions;
import system'routines;
interface IOperable
{
abstract operate() {}
}
class Operable : IOperable
{
constructor() {}
operate()
= "delegate implementation";
}
class Delegator
{
object theDelegate;
set Delegate(object)
{
theDelegate := object
}
... |
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)... | #jq | jq | # Points are realized as arrays of two numbers [x, y]
# Triangles are realized as triples of Points [p1, p2, p3]
# Input: a Triangle
def det2D:
. as [ [$p1x, $p1y], [$p2x, $p2y], [$p3x, $p3y]]
| $p1x * ($p2y - $p3y) +
$p2x * ($p3y - $p1y) +
$p3x * ($p1y - $p2y) ;
# Input: a Triangle
def checkTriWi... |
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.
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. Delete-Files.
PROCEDURE DIVISION.
CALL "CBL_DELETE_FILE" USING "input.txt"
CALL "CBL_DELETE_DIR" USING "docs"
CALL "CBL_DELETE_FILE" USING "/input.txt"
CALL "CBL_DELETE_DIR" USING "/docs"
GOBACK
... |
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.
| #Common_Lisp | Common Lisp | (delete-file (make-pathname :name "input.txt"))
(delete-file (make-pathname :directory '(:absolute "") :name "input.txt")) |
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
... | #JavaScript | JavaScript | const determinant = arr =>
arr.length === 1 ? (
arr[0][0]
) : arr[0].reduce(
(sum, v, i) => sum + v * (-1) ** i * determinant(
arr.slice(1)
.map(x => x.filter((_, j) => i !== j))
), 0
);
const permanent = arr =>
arr.length === 1 ? (
arr[0][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.
| #Elixir | Elixir | defmodule Division do
def by_zero?(x,y) do
try do
_ = x / y
false
rescue
ArithmeticError -> true
end
end
end
[{2, 3}, {3, 0}, {0, 5}, {0, 0}, {2.0, 3.0}, {3.0, 0.0}, {0.0, 5.0}, {0.0, 0.0}]
|> Enum.each(fn {x,y} ->
IO.puts "#{x} / #{y}\tdivision by zero #{Division.by_zero?(x,y)}"
... |
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.
| #Emacs_Lisp | Emacs Lisp | (condition-case nil
(/ 1 0)
(arith-error
(message "Divide by zero (either integer or float)"))) |
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.
| #Erlang | Erlang | div_check(X,Y) ->
case catch X/Y of
{'EXIT',_} -> true;
_ -> false
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... | #ColdFusion | ColdFusion | <cfset TestValue=34>
TestValue: <cfoutput>#TestValue#</cfoutput><br>
<cfif isNumeric(TestValue)>
is Numeric.
<cfelse>
is NOT Numeric.
</cfif>
<cfset TestValue="NAS">
TestValue: <cfoutput>#TestValue#</cfoutput><br>
<cfif isNumeric(TestValue)>
is Numeric.
<cfelse>
is NOT Numeric.
</cfif> |
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 ... | #FreeBASIC | FreeBASIC | Sub CaracteresUnicos (cad As String)
Dim As Integer lngt = Len(cad)
Print "Cadena = """; cad; """, longitud = "; lngt
For i As Integer = 1 To lngt
For j As Integer = i + 1 To lngt
If Mid(cad,i,1) = Mid(cad,j,1) Then
Print " Primer duplicado en las posiciones " & 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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[StringCollapse]
StringCollapse[s_String] := FixedPoint[StringReplace[y_ ~~ y_ :> y], s]
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 t... |
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... | #MATLAB_.2F_Octave | MATLAB / Octave |
function r = collapse(s)
ix=find((s(1:end-1)==s(2:end))+1;
r=s;
r(ix)=[];
fprintf(1,'Input: <<<%s>>> length: %d\n',s,length(s));
fprintf(1,'Output: <<<%s>>> length: %d\n',r,length(r));
fprintf(1,'Character to be squeezed: "%s"\n',c);
end
collapse('', ' ')
collapse('║╚════════════════════... |
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... | #JavaScript | JavaScript | const check = s => {
const arr = [...s];
const at = arr.findIndex(
(v, i) => i === 0 ? false : v !== arr[i - 1]
)
const l = arr.length;
const ok = at === -1;
const p = ok ? "" : at + 1;
const v = ok ? "" : arr[at];
const vs = v === "" ? v : `"${v}"`
const h = ok ? "" : `0x${v.codePointAt(0).toSt... |
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... | #Pascal | Pascal |
program dining_philosophers;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}
cthreads,
{$ENDIF}
Classes, SysUtils, SyncObjs;
const
PHIL_COUNT = 5;
LIFESPAN = 7;
DELAY_RANGE = 950;
DELAY_LOW = 50;
PHIL_NAMES: array[1..PHIL_COUNT] of string = ('Aristotle', 'Kant', 'Spinoza', 'Marx', 'Russell');
type
... |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Perl | Perl | use 5.010;
use strict;
use warnings;
use Time::Piece ();
my @seasons = (qw< Chaos Discord Confusion Bureaucracy >, 'The Aftermath');
my @week_days = (qw< Sweetmorn Boomtime Pungenday Prickle-Prickle >, 'Setting Orange');
sub ordinal {
my ($n) = @_;
return $n . "th" if int($n/10) == 1;
return $n . ((qw< th st nd ... |
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... | #Perl | Perl | use strict;
use warnings;
use constant True => 1;
sub add_edge {
my ($g, $a, $b, $weight) = @_;
$g->{$a} ||= {name => $a};
$g->{$b} ||= {name => $b};
push @{$g->{$a}{edges}}, {weight => $weight, vertex => $g->{$b}};
}
sub push_priority {
my ($a, $v) = @_;
my $i = 0;
my $j = $#{$a};
w... |
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... | #jq | jq | def do_until(condition; next):
def u: if condition then . else (next|u) end;
u;
# n may be a decimal number or a string representing a decimal number
def digital_root(n):
# string-only version
def dr:
# state: [mdr, persist]
do_until( .[0] | length == 1;
[ (.[0] | explode | map(.-48) | a... |
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... | #Julia | Julia | function digitalroot(n::Integer, bs::Integer=10)
if n < 0 || bs < 2 throw(DomainError()) end
ds, pers = n, 0
while bs ≤ ds
ds = sum(digits(ds, bs))
pers += 1
end
return pers, ds
end
for i in [627615, 39390, 588225, 393900588225, big(2) ^ 100]
pers, ds = digitalroot(i)
print... |
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
... | #Vlang | Vlang | // Only valid for n > 0 && base >= 2
fn mult(nn u64, base int) u64 {
mut n := nn
mut mult := u64(0)
for mult = 1; mult > 0 && n > 0; n /= u64(base) {
mult *= n % u64(base)
}
return mult
}
// Only valid for n >= 0 && base >= 2
fn multi_digital_root(n u64, base int) (int, int) {
mut m := u64(0)
mut mp := 0
fo... |
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
... | #Wren | Wren | import "/big" for BigInt
import "/fmt" for Fmt
// Only valid for n > 0 && base >= 2
var mult = Fn.new { |n, base|
var m = BigInt.one
while (m > BigInt.zero && n > BigInt.zero) {
var dm = n.divMod(base)
m = m * dm[1]
n = dm[0]
}
return m
}
// Only valid for n >= 0 && base >= 2... |
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... | #PowerShell | PowerShell |
# Floors are numbered 1 (ground) to 5 (top)
# Baker, Cooper, Fletcher, Miller, and Smith live on different floors:
$statement1 = '$baker -ne $cooper -and $baker -ne $fletcher -and $baker -ne $miller -and
$baker -ne $smith -and $cooper -ne $fletcher -and $cooper -ne $miller -and
... |
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 ... | #Idris | Idris | module Main
import Data.Vect
dotProduct : (Num a) => Vect n a -> Vect n a -> a
dotProduct = (sum .) . zipWith (*)
main : IO ()
main = printLn $ dotProduct [1,2,3] [1,2,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 ... | #J | J | 1 3 _5 +/ . * 4 _2 _1
3
dotp=: +/ . * NB. Or defined as a verb (function)
1 3 _5 dotp 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... | #Nim | Nim | import unicode, strformat
proc squeeze(s: string; ch: Rune) =
echo fmt"Specified character: '{ch}'"
let original = s.toRunes
echo fmt"Original: length = {original.len}, string = «««{s}»»»"
var previous = Rune(0)
var squeezed: seq[Rune]
for rune in original:
if rune != previous:
squeezed.add(rune... |
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... | #Perl | Perl | use strict;
use warnings;
use Unicode::UCD 'charinfo';
for (
['', ' '],
['"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ', '-'],
['..1111111111111111111111111111111111111111111111111111111111111117777888', '7'],
["I never give 'em hell, I just tell the truth, and they think it's hell... |
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 ... | #Perl | Perl | @dx = qw<
-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... |
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... | #AutoHotkey | AutoHotkey | perm(elements, n, opt:="", Delim:="", str:="", res:="", j:=0, dup:="") {
res := IsObject(res) ? res : [], dup := IsObject(dup) ? dup : []
if (n > j)
Loop, parse, elements, % Delim
res := !(InStr(str, A_LoopField) && !(InStr(opt, "rep"))) ? perm(elements, n, opt, Delim, trim(str Delim A_LoopField, Delim), res, ... |
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 ... | #F.23 | F# | type Delegator() =
let defaultOperation() = "default implementation"
let mutable del = null
// write-only property "Delegate"
member x.Delegate with set(d:obj) = del <- d
member x.operation() =
if del = null then
defaultOperation()
else
match del.GetType().GetMethod("thing", [||]) with... |
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 ... | #Forth | Forth | include FMS-SI.f
:class delegate
:m thing ." delegate implementation" ;m
;class
delegate slave
:class delegator
ivar del \ object container
:m !: ( n -- ) del ! ;m
:m init: 0 del ! ;m
:m default ." default implementation" ;m
:m operation
del @ 0= if self default exit then
del @ has-meth th... |
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)... | #Julia | Julia | module Triangles
using LinearAlgebra
export AntiClockwise, Both, StrictCheck, MildCheck
abstract type Widing end
struct AntiClockwise <: Widing end
struct Both <: Widing end
function _check_triangle_winding(t, widing::AntiClockwise)
trisq = fill!(Matrix{eltype(t)}(undef, 3, 3), 1)
trisq[:, 1:2]... |
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.
| #Component_Pascal | Component Pascal |
VAR
l: Files.Locator;
BEGIN
(* Locator is the directory *)
l := Files.dir.This("proof");
(* delete 'xx.txt' file, in directory 'proof' *)
Files.dir.Delete(l,"xx.txt");
END ...
|
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #D | D | import std.file: remove;
void main() {
remove("data.txt");
} |
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
... | #jq | jq | # Eliminate row i and row j
def except(i;j):
reduce del(.[i])[] as $row ([]; . + [$row | del(.[j]) ] );
def det:
def parity(i): if i % 2 == 0 then 1 else -1 end;
if length == 1 and (.[0] | length) == 1 then .[0][0]
else . as $m
| reduce range(0; length) as $i
(0; . + parity($i) * $m[0][$i] * ( $m ... |
http://rosettacode.org/wiki/Determinant_and_permanent | Determinant and permanent | For a given matrix, return the determinant and the permanent of the matrix.
The determinant is given by
det
(
A
)
=
∑
σ
sgn
(
σ
)
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}}
while the permanent is given by
... | #Julia | Julia | using LinearAlgebra |
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.
| #ERRE | ERRE |
PROGRAM DIV_BY_ZERO
EXCEPTION
IF ERR=11 THEN PRINT("Division by Zero") END IF
END EXCEPTION
BEGIN
PRINT(0/3)
PRINT(3/0)
END PROGRAM
|
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.
| #F.23 | F# | let detectDivideZero (x : int) (y : int):int option =
try
Some(x / y)
with
| :? System.ArithmeticException -> None
printfn "12 divided by 3 is %A" (detectDivideZero 12 3)
printfn "1 divided by 0 is %A" (detectDivideZero 1 0) |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Cop... | #Common_Lisp | Common Lisp | (defun numeric-string-p (string)
(let ((*read-eval* nil))
(ignore-errors (numberp (read-from-string string))))) |
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... | #D | D | import std.stdio, std.string, std.array;
void main() {
foreach (const s; ["12", " 12\t", "hello12", "-12", "02",
"0-12", "+12", "1.5", "1,000", "1_000",
"0x10", "0b10101111_11110000_11110000_00110011",
"-0b10101", "0x10.5"])
writefln(`isNumeric("%s"): %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 ... | #Go | Go | package main
import "fmt"
func analyze(s string) {
chars := []rune(s)
le := len(chars)
fmt.Printf("Analyzing %q which has a length of %d:\n", s, le)
if le > 1 {
for i := 0; i < le-1; i++ {
for j := i + 1; j < le; j++ {
if chars[j] == chars[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... | #Modula-2 | Modula-2 | MODULE StrCollapse;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;
FROM Strings IMPORT Length;
(* Collapse a string *)
PROCEDURE Collapse(in: ARRAY OF CHAR; VAR out: ARRAY OF CHAR);
VAR i, o: CARDINAL;
BEGIN
i := 0;
o := 0;
WHILE (i < HIGH(in)) AND (in[i] # CHR(0)) DO
IF (o = 0) O... |
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... | #jq | jq | jq -rn '
def firstdifferent:
label $out
| foreach explode[] as $i ({index:-1};
.prev = .i | .i = $i | .index +=1;
if .prev and $i != .prev then .index, break $out else empty end)
// null ;
def lpad($n): " "*($n-length) + "\"\(.)\"" ;
[" "*10, "length", "same", "index", "char"],... |
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... | #Julia | Julia | firstdifferent(s) = isempty(s) ? nothing : findfirst(x -> x != s[1], s)
function testfunction(strings)
println("String | Length | All Same | First Different(Hex) | Position\n" *
"-----------------------------------------------------------------------------")
for s in strings
... |
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... | #Perl | Perl |
use threads;
use threads::shared;
my @names = qw(Aristotle Kant Spinoza Marx Russell);
my @forks = ('On Table') x @names;
share $forks[$_] for 0 .. $#forks;
sub pick_up_forks {
my $philosopher = shift;
my ($first, $second) = ($philosopher, $philosopher-1);
($first, $second) = ($second, $first) if $philos... |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Phix | Phix | with javascript_semantics
constant seasons = {"Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"},
weekday = {"Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange"},
apostle = {"Mungday", "Mojoday", "Syaday", "Zaraday", "Maladay"},
holiday = {"Chaoflux", "Disc... |
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... | #Phix | Phix | with javascript_semantics
--requires("1.0.2") -- (builtin E renamed as EULER)
--enum A,B,C,D,E,F
constant A=1, B=2, C=3, D=4, E=5, F=6 -- (or use this)
constant edges = {{A,B,7},
{A,C,9},
{A,F,14},
{B,C,10},
{B,D,15},
{C,D,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... | #K | K |
/ print digital root and additive persistence
prt: {`"Digital root = ", x, `"Additive persistence = ",y}
/ sum of digits of an integer
sumdig: {d::(); (0<){d::d,x!10; x%:10}/x; +/d}
/ compute digital root and additive persistence
digroot: {sm::sumdig x; ap::0; (9<){sm::sumdig x;ap::ap+1; x:sm}/x; prt[sm;ap]}
|
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... | #Kotlin | Kotlin | // version 1.0.6
fun sumDigits(n: Long): Int = when {
n < 0L -> throw IllegalArgumentException("Negative numbers not allowed")
else -> {
var sum = 0
var nn = n
while (nn > 0L) {
sum += (nn % 10).toInt()
nn /= 10
}
... |
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root | Digital root/Multiplicative digital root | The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number,
n
{\displaystyle n}
, is calculated rather like the Digital root except digits are multiplied instead of being added:
Set
m
{\displaystyle m}
to
n
{\displaystyle n}
and
i
{\displaystyle i}
to
0
... | #zkl | zkl | fcn mdroot(n){ // Multiplicative digital root
mdr := List(n);
while (mdr[-1] > 9){
mdr.append(mdr[-1].split().reduce('*,1));
}
return(mdr.len() - 1, mdr[-1]);
} |
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... | #Prolog | Prolog | :- use_module(library(clpfd)).
:- dynamic top/1, bottom/1.
% Baker does not live on the top floor
rule1(L) :-
member((baker, F), L),
top(Top),
F #\= Top.
% Cooper does not live on the bottom floor.
rule2(L) :-
member((cooper, F), L),
bottom(Bottom),
F #\= Bottom.
% Fletcher does not live on either the top... |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot ... | #Java | Java | public class DotProduct {
public static void main(String[] args) {
double[] a = {1, 3, -5};
double[] b = {4, -2, -1};
System.out.println(dotProd(a,b));
}
public static double dotProd(double[] a, double[] b){
if(a.length != b.length){
throw new IllegalArgumentException("The dimensions have to be equa... |
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... | #Phix | Phix | with javascript_semantics
constant tests = {"", " ",
`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `,"-",
"..1111111111111111111111111111111111111111111111111111111111111117777888","7",... |
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 ... | #Phix | Phix | with javascript_semantics
function funnel(sequence dxs, integer rule)
atom x = 0.0
sequence rxs = {}
for i=1 to length(dxs) do
atom dx = dxs[i]
rxs = append(rxs,x + dx)
switch rule
case 2: x = -dx
case 3: x = -(x+dx)
case 4: x = x+dx
end sw... |
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... | #AWK | AWK |
# syntax: GAWK -f DEPARTMENT_NUMBERS.AWK
BEGIN {
print(" # FD PD SD")
for (fire=1; fire<=7; fire++) {
for (police=1; police<=7; police++) {
for (sanitation=1; sanitation<=7; sanitation++) {
if (rules() ~ /^1+$/) {
printf("%2d %2d %2d %2d\n",++count,fire,police,sanitation)
... |
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 ... | #Go | Go | package main
import "fmt"
type Delegator struct {
delegate interface{} // the delegate may be any type
}
// interface that represents anything that supports thing()
type Thingable interface {
thing() string
}
func (self Delegator) operation() string {
if v, ok := self.delegate.(Thingable); ok {
... |
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 ... | #Io | Io | Delegator := Object clone do(
delegate ::= nil
operation := method(
if((delegate != nil) and (delegate hasSlot("thing")),
delegate thing,
"default implementation"
)
)
)
Delegate := Object clone do(
thing := method("delegate implementation")
)
a := clone Delega... |
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)... | #Kotlin | Kotlin | // version 1.1.0
typealias Point = Pair<Double, Double>
data class Triangle(var p1: Point, var p2: Point, var p3: Point) {
override fun toString() = "Triangle: $p1, $p2, $p3"
}
fun det2D(t: Triangle): Double {
val (p1, p2, p3) = t
return p1.first * (p2.second - p3.second) +
p2.first * (p3... |
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.
| #Delphi | Delphi | procedure TMain.btnDeleteClick(Sender: TObject);
var
CurrentDirectory : String;
begin
CurrentDirectory := GetCurrentDir;
DeleteFile(CurrentDirectory + '\input.txt');
RmDir(PChar(CurrentDirectory + '\docs'));
DeleteFile('c:\input.txt');
RmDir(PChar('c:\docs'));
end;
|
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #E | E | <file:input.txt>.delete(null)
<file:docs>.delete(null)
<file:///input.txt>.delete(null)
<file:///docs>.delete(null) |
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
... | #Kotlin | Kotlin | // version 1.1.2
typealias Matrix = Array<DoubleArray>
fun johnsonTrotter(n: Int): Pair<List<IntArray>, List<Int>> {
val p = IntArray(n) { it } // permutation
val q = IntArray(n) { it } // inverse permutation
val d = IntArray(n) { -1 } // direction = 1 or -1
var sign = 1
val perms = mutableLi... |
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.
| #Factor | Factor | USE: math.floats.env
: try-div ( a b -- )
'[ { +fp-zero-divide+ } [ _ _ /f . ] with-fp-traps ] try ; |
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.
| #Fancy | Fancy | def divide: x by: y {
try {
x / y
} catch DivisionByZeroError => e {
e message println # prints error message
}
}
|
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... | #Delphi | Delphi |
function IsNumericString(const inStr: string): Boolean;
var
i: extended;
begin
Result := TryStrToFloat(inStr,i);
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... | #Dyalect | Dyalect | func String.IsNumeric() {
try {
parse(this) is Integer or Float
} catch _ {
false
}
}
var str = "1234567"
print(str.IsNumeric()) |
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 ... | #Groovy | Groovy | class StringUniqueCharacters {
static void main(String[] args) {
printf("%-40s %2s %10s %8s %s %s%n", "String", "Length", "All Unique", "1st Diff", "Hex", "Positions")
printf("%-40s %2s %10s %8s %s %s%n", "------------------------", "------", "----------", "--------", "---", "---------")
... |
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... | #NetLogo | NetLogo |
to-report split [ string ]
;; utility reporter to split a string into a list
report n-values length string [ [ n ] -> item n string ]
end
to-report collapse [ string ]
;; reporter that actually does the collapse function
ifelse ( string = "" )
[ report "" ]
[ report reduce [ [ a b ] -> (word a ifelse-v... |
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... | #Nim | Nim | import unicode, strformat
proc collapse(s: string) =
let original = s.toRunes
echo fmt"Original: length = {original.len}, string = «««{s}»»»"
var previous = Rune(0)
var collapsed: seq[Rune]
for rune in original:
if rune != previous:
collapsed.add(rune)
previous = rune
echo fmt"Collapsed: ... |
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... | #Perl | Perl | use strict;
use warnings;
use utf8;
binmode STDOUT, ":utf8";
my @lines = split "\n", <<~'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... |
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... | #Kotlin | Kotlin | fun analyze(s: String) {
println("Examining [$s] which has a length of ${s.length}:")
if (s.length > 1) {
val b = s[0]
for ((i, c) in s.withIndex()) {
if (c != b) {
println(" Not all characters in the string are the same.")
println(" '$c' (0x${In... |
Subsets and Splits
Rosetta Code COBOL Python Hard Tasks
Identifies and retrieves challenging tasks that exist in both COBOL and Python, revealing cross-language programming patterns and difficulty levels for comparative analysis.
Rosetta Code Task Comparisons
Identifies tasks common to both COBOL and Python languages that are described as having difficulty levels, revealing cross-language task similarities and providing useful comparative programming examples.
SQL Code Examples from Training Data
Retrieves raw SQL code examples for the SQL language, which is basic data retrieval without meaningful analysis or patterns.
SQL Code Examples from Training Data
Retrieves raw SQL code examples for the SQL language, which is basic filtering that shows what data looks like but doesn't provide meaningful analysis or patterns.
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.