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/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 ... | #Pop11 | Pop11 | uses objectclass;
define :class Delegator;
slot delegate = false;
enddefine;
define :class Delegate;
enddefine;
define :method thing(x : Delegate);
'delegate implementation'
enddefine;
define :method operation(x : Delegator);
if delegate(x) and fail_safe(delegate(x), thing) then
;;; Return value is on t... |
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 ... | #Python | Python | class Delegator:
def __init__(self):
self.delegate = None
def operation(self):
if hasattr(self.delegate, 'thing') and callable(self.delegate.thing):
return self.delegate.thing()
return 'default implementation'
class Delegate:
def thing(self):
return 'delegate implementatio... |
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 ... | #Racket | Racket | #lang racket
;; Delegates. Tim Brown 2014-10-16
(define delegator%
(class object%
(init-field [delegate #f])
(define/public (operation)
(cond [(and (object? delegate) (object-method-arity-includes? delegate 'thing 0))
(send delegate thing)]
[else "default implementation"]))
... |
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)... | #Racket | Racket | #lang racket
;; A triangle is a list of three pairs of points: '((x . y) (x . y) (x . y))
(define (to-tri x1 y1 x2 y2 x3 y3) `((,x1 . ,y1) (,x2 . ,y2) (,x3 . ,y3)))
(define det-2D
(match-lambda
[`((,x1 . ,y1) (,x2 . ,y2) (,x3 . ,y3)) (+ (* x1 (- y2 y3)) (* x2 (- y3 y1)) (* x3 (- y1 y2)))]))
(define (assert-... |
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.
| #JavaScript | JavaScript | var fso = new ActiveXObject("Scripting.FileSystemObject");
fso.DeleteFile('input.txt');
fso.DeleteFile('c:/input.txt');
fso.DeleteFolder('docs');
fso.DeleteFolder('c:/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.
| #Julia | Julia |
# Delete a file
rm("input.txt")
# Delete a directory
rm("docs", recursive = true)
|
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
... | #REXX | REXX | /* REXX ***************************************************************
* Test the two functions determinant and permanent
* using the matrix specifications shown for other languages
* 21.05.2013 Walter Pachl
**********************************************************************/
Call test ' 1 2',
' 3 4',2
... |
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
... | #Ruby | Ruby | require 'matrix'
class Matrix
# Add "permanent" method to Matrix class
def permanent
r = (0...row_count).to_a # [0,1] (first example), [0,1,2,3] (second example)
r.permutation.inject(0) do |sum, sigma|
sum += sigma.zip(r).inject(1){|prod, (row, col)| prod *= self[row, col] }
end
end
end
m1 ... |
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.
| #Lua | Lua | local function div(a,b)
if b == 0 then error() end
return a/b
end |
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.
| #M2000_Interpreter | M2000 Interpreter |
Print function("{Read x : =x**2}", 2)=4
|
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.
| #M4 | M4 | ifelse(eval(2/0),`',`detected divide by zero or some other error of some kind') |
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... | #Haxe | Haxe |
static function isNumeric(n:String):Bool
{
if (Std.parseInt(n) != null) //Std.parseInt converts a string to an int
{
return true; //as long as it results in an integer, the function will return true
}
else
{
return false;
}
}
|
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... | #HicEst | HicEst | ! = bin + 2*int + 4*flt + 8*oct +16*hex + 32*sci
isNumeric("1001") ! 27 = 1 1 0 1 1 0
isNumeric("123") ! 26 = 0 1 0 1 1 0
isNumeric("1E78") ! 48 = 0 0 0 0 1 ... |
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 ... | #Python | Python | '''Determine if a string has all unique characters'''
from itertools import groupby
# duplicatedCharIndices :: String -> Maybe (Char, [Int])
def duplicatedCharIndices(s):
'''Just the first duplicated character, and
the indices of its occurrence, or
Nothing if there are no duplications.
'''
... |
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... | #XPL0 | XPL0 | string 0;
char C, I, J, Last;
proc Collapse(S); \Eliminate immediately repeated characters from string
char S;
[I:= 0; J:= 0; Last:= -1;
loop [if S(I) # Last then
[C(J):= S(I);
if S(I) = 0 then quit;
J:= J+1;
];
Last:= S(I);
I:= I+1;
];
];
int String, K;
[Strin... |
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... | #zkl | zkl | fcn collapsible(str){ // no Unicode
sink:=Sink(String);
str.reduce('wrap(c1,c2){ if(c1!=c2) sink.write(c2); c2 },""); // prime with \0
cstr:=sink.close();
return(str.len()!=cstr.len(), cstr);
} |
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... | #Racket | Racket | #lang racket
(define (first-non-matching-index l =)
(and (not (null? l)) (index-where l (curry (negate =) (car l)))))
(define (report-string-sameness s)
(printf "~s (length: ~a): ~a~%"
s
(string-length s)
(cond [(first-non-matching-index (string->list s) 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... | #Raku | Raku | -> $str {
my $i = 0;
print "\n{$str.raku} (length: {$str.chars}), has ";
my %m;
%m{$_}.push: ++$i for $str.comb;
if %m > 1 {
say "different characters:";
say "'{.key}' ({.key.uninames}; hex ordinal: {(.key.ords).fmt: "0x%X"})" ~
" in positions: {.value.join: ', '}" for %m... |
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... | #Smalltalk | Smalltalk | 'From Squeak3.7 of ''4 September 2004'' [latest update: #5989] on 13 October 2011 at 2:44:42 pm'!
Object subclass: #Philosopher
instanceVariableNames: 'table random name seat forks running'
classVariableNames: ''
poolDictionaries: ''
category: 'rosettacode'!
!Philosopher methodsFor: 'private'!
createfork
^ Semap... |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Rust | Rust | extern crate chrono;
use chrono::NaiveDate;
use std::str::FromStr;
fn main() {
let date = std::env::args().nth(1).expect("Please provide a YYYY-MM-DD date.");
println!("{} is {}", date, NaiveDate::from_str(&date).unwrap().to_poee());
}
// The necessary constants for the seasons, weekdays, and holydays.
co... |
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... | #Sidef | Sidef | class Graph(*args) {
struct Node {
String name,
Array edges = [],
Number dist = Inf,
prev = nil,
Bool visited = false,
}
struct Edge {
Number weight,
Node vertex,
}
has g = Hash()
method init {
args.each { |a|
se... |
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... | #PowerShell | PowerShell | function Get-DigitalRoot ($n)
{
function Get-Digitalsum ($n)
{
if ($n -lt 10) {$n}
else {
($n % 10) + (Get-DigitalSum ([math]::Floor($n / 10)))
}
}
$ap = 0
do {$n = Get-DigitalSum $n; $ap++}
until ($n -lt 10)
$DigitalRoot = [pscustomobject]@{
'Su... |
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... | #UTFool | UTFool |
···
http://rosettacode.org/wiki/Dinesman's_multiple-dwelling_problem
···
import java.util.HashSet
■ Dinesman
§ static
houses⦂ HashSet⟨String⟩°
▶ main
• args⦂ String[]
· Baker, Cooper, Fletcher, Miller, and Smith …
build *StringBuilder°, *StringBuilder "BCFMS"
∀ house ∈ houses⦂ St... |
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 ... | #.D0.9C.D0.9A-61.2F52 | МК-61/52 | С/П * ИП0 + П0 С/П БП 00 |
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 ... | #Modula-2 | Modula-2 | MODULE DotProduct;
FROM RealStr IMPORT RealToStr;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
TYPE Vector =
RECORD
x,y,z : REAL
END;
PROCEDURE DotProduct(u,v : Vector) : REAL;
BEGIN
RETURN u.x*v.x + u.y*v.y + u.z*v.z
END DotProduct;
VAR
buf : ARRAY[0..63] OF CHAR;
dp : REAL;
BEG... |
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... | #FOCAL | FOCAL | 01.10 F P=2,2,6;F S=1,7;F G=1,7;D 2
01.20 Q
02.10 I (P-S)2.2,2.6,2.2
02.20 I (P-G)2.3,2.6,2.3
02.30 I (S-G)2.4,2.6,2.4
02.40 I (P+S+G-12)2.6,2.5,2.6
02.50 T %1,P,S,G,!
02.60 R |
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... | #Forth | Forth | \ if department numbers are valid, print them on a single line
: fire ( pol san fir -- )
2dup = if 2drop drop exit then
2 pick over = if 2drop drop exit then
rot . swap . . cr ;
\ tries to assign numbers with given policeno and sanitationno
\ and fire = 12 - policeno - sanitationno
: sanitation ( pol san ... |
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 ... | #Raku | Raku | class Non-Delegate { }
class Delegate {
method thing {
return "delegate implementation"
}
}
class Delegator {
has $.delegate is rw;
method operation {
$.delegate.^can( 'thing' ) ?? $.delegate.thing
!! "default implementation"
}
}
my Delegator $d .= new;
say "empty: "~$d.operation;
$d.delegate = ... |
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects ... | #Ruby | Ruby | class Delegator
attr_accessor :delegate
def operation
if @delegate.respond_to?(:thing)
@delegate.thing
else
'default implementation'
end
end
end
class Delegate
def thing
'delegate implementation'
end
end
if __FILE__ == $PROGRAM_NAME
# No delegate
a = ... |
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)... | #Raku | Raku | # Reference:
# https://stackoverflow.com/questions/2049582/how-to-determine-if-a-point-is-in-a-2d-triangle
# https://www.geeksforgeeks.org/check-if-two-given-line-segments-intersect/
sub if-overlap ($triangle-pair) {
my (\A,\B) = $triangle-pair;
my Bool $result = False;
sub sign (\T) {
return (T[0;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.
| #Kotlin | Kotlin | // version 1.0.6
/* testing on Windows 10 which needs administrative privileges
to delete files from the root */
import java.io.File
fun main(args: Array<String>) {
val paths = arrayOf("input.txt", "docs", "c:\\input.txt", "c:\\docs")
var f: File
for (path in paths) {
f = File(path)
... |
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.
| #LabVIEW | LabVIEW | // delete file
local(f = file('input.txt'))
#f->delete
// delete directory
// directory must be empty before it can be successfully deleted. A failure is generated if the operation fails.
local(d = dir('docs'))
#d->delete
// delete file in root file system (requires permissions at user OS level)
local(f = file('//i... |
http://rosettacode.org/wiki/Determinant_and_permanent | Determinant and permanent | For a given matrix, return the determinant and the permanent of the matrix.
The determinant is given by
det
(
A
)
=
∑
σ
sgn
(
σ
)
∏
i
=
1
n
M
i
,
σ
i
{\displaystyle \det(A)=\sum _{\sigma }\operatorname {sgn}(\sigma )\prod _{i=1}^{n}M_{i,\sigma _{i}}}
while the permanent is given by
... | #Rust | Rust |
fn main() {
let mut m1: Vec<Vec<f64>> = vec![vec![1.0,2.0],vec![3.0,4.0]];
let mut r_m1 = &mut m1;
let rr_m1 = &mut r_m1;
let mut m2: Vec<Vec<f64>> = vec![vec![1.0, 2.0, 3.0, 4.0], vec![4.0, 5.0, 6.0, 7.0], vec![7.0, 8.0, 9.0, 10.0], vec![10.0, 11.0, 12.0, 13.0]];
let mut r_m2 = &mut m2;
let rr_m2... |
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
... | #Scala | Scala |
def permutationsSgn[T]: List[T] => List[(Int,List[T])] = {
case Nil => List((1,Nil))
case xs => {
for {
(x, i) <- xs.zipWithIndex
(sgn,ys) <- permutationsSgn(xs.take(i) ++ xs.drop(1 + i))
} yield {
val sgni = sgn * (2 * (i%2) - 1)
(sgni, (x :: ys))
}
}
}
def det(m:List[List... |
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.
| #Maple | Maple | 1/0; # Here is the default behavior. |
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.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | Check[2/0, Print["division by 0"], Power::infy] |
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.
| #MATLAB | MATLAB | function [isDividedByZero] = dividebyzero(numerator, denomenator)
isDividedByZero = isinf( numerator/denomenator );
% If isDividedByZero equals 1, divide by zero occured. |
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... | #i | i | concept numeric(n) {
number(n)
errors {
print(n, " is not numeric!")
return
}
print(n, " is numeric :)")
}
software {
numeric("1200")
numeric("3.14")
numeric("3/4")
numeric("abcdefg")
numeric("1234test")
} |
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... | #Icon_and_Unicon | Icon and Unicon |
write(image(x), if numeric(x) then " is numeric." else " is not numeric")
|
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 ... | #R | R | isAllUnique <- function(string)
{
strLength <- nchar(string)
if(length(strLength) > 1)
{
#R has a distinction between the length of a string and that of a character vector. It is a common source
#of problems when coming from another language. We will try to avoid the topic here.
#For our purposes, let... |
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... | #REXX | REXX | /*REXX program verifies that all characters in a string are all the same (character). */
@chr= ' [character' /* define a literal used for SAY.*/
@all= 'all the same character for string (length' /* " " " " " " */
@.= ... |
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... | #Tcl | Tcl | package require Thread
foreach name {Aristotle Kant Spinoza Marx Russel} {
lappend forks [thread::mutex create]
lappend tasks [set t [thread::create -preserved {
# Implement each task as a coroutine internally for simplicity of presentation
# This is because we want to remain able to receive m... |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Scala | Scala | package rosetta
import java.util.GregorianCalendar
import java.util.Calendar
object DDate extends App {
private val DISCORDIAN_SEASONS = Array("Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath")
// month from 1-12; day from 1-31
def ddate(year: Int, month: Int, day: Int): String = {
val dat... |
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... | #Swift | Swift | typealias WeightedEdge = (Int, Int, Int)
struct Grid<T> {
var nodes: [Node<T>]
mutating func addNode(data: T) -> Int {
nodes.append(Node(data: data, edges: []))
return nodes.count - 1
}
mutating func createEdges(weights: [WeightedEdge]) {
for (start, end, weight) in weights {
nodes[sta... |
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... | #Prolog | Prolog | digit_sum(N, Base, Sum):-
digit_sum(N, Base, Sum, 0).
digit_sum(N, Base, Sum, S1):-
N < Base,
!,
Sum is S1 + N.
digit_sum(N, Base, Sum, S1):-
divmod(N, Base, M, Digit),
S2 is S1 + Digit,
digit_sum(M, Base, Sum, S2).
digital_root(N, Base, AP, DR):-
digital_root(N, Base, AP, DR, 0).
... |
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... | #Wren | Wren | import "/seq" for Lst
var permute // recursive
permute = Fn.new { |input|
if (input.count == 1) return [input]
var perms = []
var toInsert = input[0]
for (perm in permute.call(input.skip(1).toList)) {
for (i in 0..perm.count) {
var newPerm = perm.toList
newPerm.insert(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 ... | #MUMPS | MUMPS | DOTPROD(A,B)
;Returns the dot product of two vectors. Vectors are assumed to be stored as caret-delimited strings of numbers.
;If the vectors are not of equal length, a null string is returned.
QUIT:$LENGTH(A,"^")'=$LENGTH(B,"^") ""
NEW I,SUM
SET SUM=0
FOR I=1:1:$LENGTH(A,"^") SET SUM=SUM+($PIECE(A,"^",I)*$PIECE(... |
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 ... | #Nemerle | Nemerle | using System;
using System.Console;
using Nemerle.Collections.NCollectionsExtensions;
module DotProduct
{
DotProduct(x : array[int], y : array[int]) : int
{
$[(a * b)|(a, b) in ZipLazy(x, y)].FoldLeft(0, _+_);
}
Main() : void
{
def arr1 = array[1, 3, -5]; def arr2 = array[4, ... |
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... | #Fortran | Fortran | INTEGER P,S,F !Department codes for Police, Sanitation, and Fire. Values 1 to 7 only.
1 PP:DO P = 2,7,2 !The police demand an even number. They're special and use violence.
2 SS:DO S = 1,7 !The sanitation department accepts any value.
3 IF (P.EQ.S) CYCLE SS !But it must differ from the othe... |
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 ... | #Rust | Rust | trait Thingable {
fn thing(&self) -> &str;
}
struct Delegator<T>(Option<T>);
struct Delegate {}
impl Thingable for Delegate {
fn thing(&self) -> &'static str {
"Delegate implementation"
}
}
impl<T: Thingable> Thingable for Delegator<T> {
fn thing(&self) -> &str {
self.0.as_ref().... |
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 ... | #Scala | Scala | trait Thingable {
def thing: String
}
class Delegator {
var delegate: Thingable = _
def operation: String = if (delegate == null) "default implementation"
else delegate.thing
}
class Delegate extends Thingable {
override def thing = "delegate implementation"
}
// Example usage
// Memory management ign... |
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)... | #REXX | REXX | /* REXX */
Signal On Halt
Signal On Novalue
Signal On Syntax
fid='trio.in'
oid='trio.txt'; 'erase' oid
Call trio_test '0 0 5 0 0 5 0 0 5 0 0 6'
Call trio_test '0 0 0 5 5 0 0 0 0 5 5 0'
Call trio_test '0 0 5 0 0 5 -10 0 -5 0 -1 6'
Call trio_test '0 0 5 0 2.5 5 0 4 2.5 -1 5 4'
Cal... |
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.
| #Lasso | Lasso | // delete file
local(f = file('input.txt'))
#f->delete
// delete directory
// directory must be empty before it can be successfully deleted. A failure is generated if the operation fails.
local(d = dir('docs'))
#d->delete
// delete file in root file system (requires permissions at user OS level)
local(f = file('//i... |
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.
| #Liberty_BASIC | Liberty BASIC | ' show where we are
print DefaultDir$
' in here
kill "input.txt"
result=rmdir("Docs")
' from root
kill "\input.txt"
result=rmdir("\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
... | #Sidef | Sidef | class Array {
method permanent {
var r = @^self.len
var sum = 0
r.permutations { |*a|
var prod = 1
[a,r].zip {|row,col| prod *= self[row][col] }
sum += prod
}
return sum
}
}
var m1 = [[1,2],[3,4]]
var m2 = [[1, 2, 3, 4],
... |
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.
| #Maxima | Maxima | f(a, b) := block([q: errcatch(a / b)], if emptyp(q) then 'error else q[1]);
f(5, 6);
5 / 6
f(5, 0;)
'error |
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.
| #MAXScript | MAXScript | if not bit.isFinite (<i>expression</i>) then... |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #min | min | (/ inf ==) :div-zero? |
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... | #IDL | IDL | function isnumeric,input
on_ioerror, false
test = double(input)
return, 1
false: return, 0
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... | #J | J | isNumeric=: _ ~: _ ". ]
isNumericScalar=: 1 -: isNumeric
TXT=: ,&' a scalar numeric value.' &.> ' is not';' represents'
sayIsNumericScalar=: , TXT {::~ isNumericScalar |
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 ... | #Racket | Racket | #lang racket
(define (first-non-unique-element.index seq)
(let/ec ret
(for/fold ((es (hash))) ((e seq) (i (in-naturals)))
(if (hash-has-key? es e) (ret (list e (hash-ref es e) i)) (hash-set es e i)))
#f))
(define (report-if-a-string-has-all-unique-characters str)
(printf "~s (length ~a): ~a~%" str... |
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 ... | #Raku | Raku | -> $str {
my $i = 0;
print "\n{$str.raku} (length: {$str.chars}), has ";
my %m;
%m{$_}.push: ++$i for $str.comb;
if any(%m.values) > 1 {
say "duplicated characters:";
say "'{.key}' ({.key.uninames}; hex ordinal: {(.key.ords).fmt: "0x%X"})" ~
" in positions: {.value.join: ',... |
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... | #Ring | Ring |
nputStr = [""," ","2","333",".55","tttTTT","4444 444k"]
for word in inputStr
for x = 1 to len(word)
for y = x + 1 to len(word)
if word[x] != word[y]
char = word[y]
? "Input = " + "'" + word + "'" + ", length = " + len(word)
? " First difference ... |
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... | #Ruby | Ruby | strings = ["", " ", "2", "333", ".55", "tttTTT", "4444 444k", "pépé", "🐶🐶🐺🐶", "🎄🎄🎄🎄"]
strings.each do |str|
pos = str.empty? ? nil : str =~ /[^#{str[0]}]/
print "#{str.inspect} (size #{str.size}): "
puts pos ? "first different char #{str[pos].inspect} (#{'%#x' % str[pos].ord}) at position #{pos}." ... |
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... | #VBA | VBA | 'The combination of holding to the second fork
'(HOLDON=True) and all philosophers start
'with same hand (DIJKSTRASOLUTION=False) leads
'to a deadlock. To prevent deadlock
'set HOLDON=False, and DIJKSTRASOLUTION=True.
Public Const HOLDON = False
Public Const DIJKSTRASOLUTION = True
Public Const X = 10 'chance to contin... |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "time.s7i";
const array string: seasons is [0] ("Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath");
const array string: weekday is [0] ("Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange");
const array string: apostle is [0] ("Mungday", "Mojoday"... |
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... | #Tailspin | Tailspin |
data vertex <'a'..'f'>, to <vertex>
templates shortestPaths&{graph:}
@: [];
[ {to: $, distance: 0"1", path:[]} ] -> #
when <[](0)> do $@ !
otherwise
def closest: $ ... -> ..=Min&{by: :(distance:), select: :()};
$closest -> ..|@: $;
def path: [ $closest.path..., $closest.to ];
[ $... -> \(<?(... |
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... | #PureBasic | PureBasic | ; if you just want the DigitalRoot
; Procedure.q DigitalRoot(N.q) apparently will do
; i must have missed something because it seems too simple
; http://en.wikipedia.org/wiki/Digital_root#Congruence_formula
Procedure.q DigitalRoot(N.q)
Protected M.q=N%9
if M=0:ProcedureReturn 9
Else :ProcedureReturn M:EndIf
EndProc... |
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... | #XPL0 | XPL0 | include c:\cxpl\codes;
int B, C, F, M, S;
for B:= 1 to 4 do \Baker does not live on top (5th) floor
for C:= 2 to 5 do \Cooper does not live on bottom floor
if C#B then \Cooper & Baker live on different floors
for F:= 2 to 4 do ... |
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 ... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref savelog symbols binary
whatsTheVectorVictor = [[double 1.0, 3.0, -5.0], [double 4.0, -2.0, -1.0]]
dotProduct = Rexx dotProduct(whatsTheVectorVictor)
say dotProduct.format(null, 2)
return
method dotProduct(vec1 = double[], vec2 = double[]) public constant... |
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... | #FreeBASIC | FreeBASIC | ' version 15-08-2017
' compile with: fbc -s console
Dim As Integer fire, police, sanitation
Print "police fire sanitation"
Print "----------------------"
For police = 2 To 7 Step 2
For fire = 1 To 7
If fire = police Then Continue For
sanitation = 12 - police - fire
If sanitation = fire... |
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects ... | #Sidef | Sidef | class NonDelegate { }
class Delegate {
method thing {
return "delegate implementation"
}
}
class Delegator (delegate = null) {
method operation {
if (delegate.respond_to(:thing)) {
return delegate.thing
}
return "default implementation"
}
}
var d = 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 ... | #Smalltalk | Smalltalk | Object
subclass:#Thingy
instanceVariableNames:''
thing
^ 'thingy implementation' |
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects ... | #Swift | Swift | import Foundation
protocol Thingable { // prior to Swift 1.2, needs to be declared @objc
func thing() -> String
}
class Delegator {
weak var delegate: AnyObject?
func operation() -> String {
if let f = self.delegate?.thing {
return f()
} else {
return "default implementation"
}
}
}
... |
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)... | #Ruby | Ruby | require "matrix"
def det2D(p1, p2, p3)
return p1[0] * (p2[1] - p3[1]) + p2[0] * (p3[1] - p1[1]) + p3[0] * (p1[1] - p2[1])
end
def checkTriWinding(p1, p2, p3, allowReversed)
detTri = det2D(p1, p2, p3)
if detTri < 0.0 then
if allowReversed then
p2[0], p3[0] = p3[0], p2[0]
p... |
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.
| #Lingo | Lingo | -- note: fileIO xtra is shipped with Director, i.e. an "internal"
fp = xtra("fileIO").new()
fp.openFile("input.txt", 0)
fp.delete() |
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.
| #Locomotive_Basic | Locomotive Basic | |era,"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
... | #Simula | Simula | ! MATRIX ARITHMETIC ;
BEGIN
INTEGER PROCEDURE LENGTH(A); ARRAY A;
LENGTH := UPPERBOUND(A, 1) - LOWERBOUND(A, 1) + 1;
! Set MAT to the first minor of A dropping row X and column Y ;
PROCEDURE MINOR(A, X, Y, MAT); ARRAY A, MAT; INTEGER X, Y;
BEGIN
INTEGER I, J, rowA, M; M := LENGTH(A) ... |
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
... | #SPAD | SPAD | (1) -> M:=matrix [[2, 9, 4], [7, 5, 3], [6, 1, 8]]
+2 9 4+
| |
(1) |7 5 3|
| |
+6 1 8+
Type: Matrix(Integer)
(2) -> determinant M
(2) - 360
... |
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.
| #mIRC_Scripting_Language | mIRC Scripting Language | var %n = $rand(0,1)
if ($calc(1/ %n) == $calc((1/ %n)+1)) {
echo -ag Divides By Zero
}
else {
echo -ag Does Not Divide By Zero
} |
http://rosettacode.org/wiki/Detect_division_by_zero | Detect division by zero | Task
Write a function to detect a divide by zero error without checking if the denominator is zero.
| #MUMPS | MUMPS | DIV(A,B) ;Divide A by B, and watch for division by zero
;The ANSI error code for division by zero is "M9".
;$ECODE errors are surrounded by commas when set.
NEW $ETRAP
SET $ETRAP="GOTO DIVFIX^ROSETTA"
SET D=(A/B)
SET $ETRAP=""
QUIT D
DIVFIX
IF $FIND($ECODE,",M9,")>1 WRITE !,"Error: Division by zero" SET $ECODE=... |
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... | #Java | Java | public boolean isNumeric(String input) {
try {
Integer.parseInt(input);
return true;
}
catch (NumberFormatException e) {
// s is not numeric
return false;
}
} |
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... | #JavaScript | JavaScript | function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
var value = "123.45e7"; // Assign string literal to value
if (isNumeric(value)) {
// value is a number
}
//Or, in web browser in address field:
// javascript:function isNumeric(n) {return !isNaN(parseFloat(n)) && isFinite(n);}; value="123.45e4"... |
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 ... | #REXX | REXX | /*REXX pgm determines if a string is comprised of all unique characters (no duplicates).*/
@.= /*assign a default for the @. array. */
parse arg @.1 /*obtain optional argument from the CL.*/
if @.1='' then do; @.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... | #Rust | Rust | fn test_string(input: &str) {
println!("Checking string {:?} of length {}:", input, input.chars().count());
let mut chars = input.chars();
match chars.next() {
Some(first) => {
if let Some((character, pos)) = chars.zip(2..).filter(|(c, _)| *c != first).next() {
printl... |
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... | #Scala | Scala | import scala.collection.immutable.ListMap
object StringAllSameCharacters {
/**Transform an input String into an HashMap of its characters and its first occurrence index*/
def countChar( s : String) : Map[Char, Int] = {
val mapChar = s.toSeq.groupBy(identity).map{ case (a,b) => a->s.indexOf(a) }
val orde... |
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... | #Visual_Basic_.NET | Visual Basic .NET | Imports System.Threading
Module Module1
Public rnd As New Random
Sub Main()
'Aristotle, Kant, Spinoza, Marx, and Russel
Dim f1 As New Fork(1)
Dim f2 As New Fork(2)
Dim f3 As New Fork(3)
Dim f4 As New Fork(4)
Dim f5 As New Fork(5)
Console.WriteLine("1: Deadlock... |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Sidef | Sidef | require('Time::Piece');
var seasons = %w(Chaos Discord Confusion Bureaucracy The\ Aftermath);
var week_days = %w(Sweetmorn Boomtime Pungenday Prickle-Prickle Setting\ Orange);
func ordinal (n) {
"#{n}" + (n % 100 ~~ [11,12,13] ? 'th'
: <th st nd rd th th th th th th>[n % 10])... |
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... | #Tcl | Tcl | proc dijkstra {graph origin} {
# Initialize
dict for {vertex distmap} $graph {
dict set dist $vertex Inf
dict set path $vertex {}
}
dict set dist $origin 0
dict set path $origin [list $origin]
while {[dict size $graph]} {
# Find unhandled node with least weight
set d Inf
dict for {uu -} $... |
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... | #Python | Python | def digital_root (n):
ap = 0
n = abs(int(n))
while n >= 10:
n = sum(int(digit) for digit in str(n))
ap += 1
return ap, n
if __name__ == '__main__':
for n in [627615, 39390, 588225, 393900588225, 55]:
persistance, root = digital_root(n)
print("%12i has additive persi... |
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... | #zkl | zkl | var Baker, Cooper, Fletcher, Miller, Smith; // value == floor
const bottom=1,top=5; // floors: 1..5
// All live on different floors, enforced by using permutations of floors
//fcn c0{ (Baker!=Cooper!=Fletcher) and (Fletcher!=Miller!=Smith) }
fcn c1{ Baker!=top }
fcn c2{ Cooper!=bottom }
fcn c3{ bottom!=Fletcher!=top }... |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot ... | #newLISP | newLISP | (define (dot-product x y)
(apply + (map * x y)))
(println (dot-product '(1 3 -5) '(4 -2 -1))) |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and mu... | #Gambas | Gambas | Public Sub Main()
Dim siC0, siC1, siC2 As Short
Dim sOut As New String[]
Dim sTemp As String
For siC0 = 2 To 6 Step 2
For siC1 = 1 To 7
For siC2 = 1 To 7
If sic0 + siC1 + siC2 = 12 Then
If siC0 <> siC1 And siC1 <> siC2 And siC0 <> siC2 Then sOut.Add(Str(siC0) & Str(siC1) & Str(siC2))
End If
... |
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 ... | #Tcl | Tcl | package require TclOO
oo::class create Delegate {
method thing {} {
return "delegate impl."
}
export thing
}
oo::class create Delegator {
variable delegate
constructor args {
my delegate {*}$args
}
method delegate args {
if {[llength $args] == 0} {
i... |
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)... | #Scala | Scala | object Overlap {
type Point = (Double, Double)
class Triangle(var p1: Point, var p2: Point, var p3: Point) {
override def toString: String = s"Triangle: $p1, $p2, $p3"
}
def det2D(t: Triangle): Double = {
val (p1, p2, p3) = (t.p1, t.p2, t.p3)
p1._1 * (p2._2 - p3._2) +
p2._1 * (p3._2 - p1._... |
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.
| #Logo | Logo | erasefile "input.txt
erasefile "/input.txt |
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.
| #Lua | Lua | os.remove("input.txt")
os.remove("/input.txt")
os.remove("docs")
os.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
... | #Stata | Stata | real vector range1(real scalar n, real scalar i) {
if (i < 1 | i > n) {
return(1::n)
} else if (i == 1) {
return(2::n)
} else if (i == n) {
return(1::n-1)
} else {
return(1::i-1\i+1::n)
}
}
real matrix submat(real matrix a, real scalar i, real scalar j) {
return(a[range1(rows(a), i), range1(cols(a), j)]... |
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
... | #Tcl | Tcl | package require math::linearalgebra
package require struct::list
proc permanent {matrix} {
for {set plist {};set i 0} {$i<[llength $matrix]} {incr i} {
lappend plist $i
}
foreach p [::struct::list permutations $plist] {
foreach i $plist j $p {
lappend prod [lindex $matrix $i $j]
}
lappend sum [::... |
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.
| #Nanoquery | Nanoquery | def div_check(x, y)
try
(x / y)
return false
catch
return true
end
end |
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.