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/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... | #Lambdatalk | Lambdatalk |
{def firstDifferingChar
{def firstDifferingChar.r
{lambda {:w :i :n}
{if {or {> :i :n} {= {+ :i 1} {W.length :w}}}
then all characters are the same
else {if {not {W.equal? {W.get :i :w} {W.get {+ :i 1} :w}}}
then at position {+ :i 1} {W.get :i :w} becomes {W.get {+ :i 1} :w}
else {firstDifferingCh... |
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... | #Phix | Phix | without js -- threads
integer fork1 = init_cs(),
fork2 = init_cs(),
fork3 = init_cs(),
fork4 = init_cs(),
fork5 = init_cs()
integer terminate = 0 -- control flag
procedure person(sequence name, atom left_fork, atom right_fork)
-- (except Russell, who gets left and rig... |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #PHP | PHP |
<?php
$Anerisia = array(31,28,31,30,31,30,31,31,30,31,30,31);
$MONTHS = array("Choas","Discord","Confusion","Bureacracy","The Aftermath");
$DAYS = array("Setting Orange","Sweetmorn","BoomTime","Pungenday","Prickle-Prickle");
$Dsuff = array('th','st','nd','rd','th','th','th','th','th','th');
$Holy5... |
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... | #PHP | PHP |
<?php
function dijkstra($graph_array, $source, $target) {
$vertices = array();
$neighbours = array();
foreach ($graph_array as $edge) {
array_push($vertices, $edge[0], $edge[1]);
$neighbours[$edge[0]][] = array("end" => $edge[1], "cost" => $edge[2]);
$neighbours[$edge[1]][] = array... |
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... | #Lua | Lua | function digital_root(n, base)
p = 0
while n > 9.5 do
n = sum_digits(n, base)
p = p + 1
end
return n, p
end
print(digital_root(627615, 10))
print(digital_root(39390, 10))
print(digital_root(588225, 10))
print(digital_root(393900588225, 10)) |
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... | #MAD | MAD | NORMAL MODE IS INTEGER
VECTOR VALUES INP = $I12*$
VECTOR VALUES OUTP = $I12,S1,I12*$
BASE = 10
R READ NUMBERS UNTIL 0 INPUT
RDNUM READ FORMAT INP,NUMBER
WHENEVER NUMBER.NE.0
SUMMAT PERS = 0
DSUM = 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... | #Python | Python | import re
from itertools import product
problem_re = re.compile(r"""(?msx)(?:
# Multiple names of form n1, n2, n3, ... , and nK
(?P<namelist> [a-zA-Z]+ (?: , \s+ [a-zA-Z]+)* (?: ,? \s+ and) \s+ [a-zA-Z]+ )
# Flexible floor count (2 to 10 floors)
| (?: .* house \s+ that \s+ contains \s+ only \s+
(?P<floorcount>... |
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 ... | #JavaScript | JavaScript | function dot_product(ary1, ary2) {
if (ary1.length != ary2.length)
throw "can't find dot product: arrays have different lengths";
var dotprod = 0;
for (var i = 0; i < ary1.length; i++)
dotprod += ary1[i] * ary2[i];
return dotprod;
}
print(dot_product([1,3,-5],[4,-2,-1])); // ==> 3
prin... |
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... | #PHP | PHP | <?php
function squeezeString($string, $squeezeChar) {
$previousChar = null;
$squeeze = '';
$charArray = preg_split('//u', $string, -1, PREG_SPLIT_NO_EMPTY);
for ($i = 0 ; $i < count($charArray) ; $i++) {
$currentChar = $charArray[$i];
if ($previousChar !== $currentChar || $currentChar ... |
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 ... | #Python | Python | import math
dxs = [-0.533, 0.27, 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.15, 0.001, -0.382, 0.161, 0.915,
2.08, -2.337, 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193,
0.02, -0.051, 0.047, -0.095, 0.695, 0.34, -0.182, 0.287, 0.213,... |
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... | #BCPL | BCPL | get "libhdr"
let start() be
for p=2 to 6 by 2
for s=1 to 7
for f=1 to 7
if p~=s & s~=f & p~=f & p+s+f=12 then
writef("%N %N %N*N", p, s, f) |
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... | #BASIC | BASIC | print "--police-- --sanitation-- --fire--"
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 or sanitation = police then continue for
if sanitation >= 1 and sanitation <= 7 then
print r... |
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 ... | #J | J | coclass 'delegator'
operation=:3 :'thing__delegate ::thing y'
thing=: 'default implementation'"_
setDelegate=:3 :'delegate=:y' NB. result is the reference to our new delegate
delegate=:<'delegator'
coclass 'delegatee1'
coclass 'delegatee2'
thing=: 'delegate implementation'"_
NB. set context in case thi... |
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 ... | #Java | Java | interface Thingable {
String thing();
}
class Delegator {
public Thingable delegate;
public String operation() {
if (delegate == null)
return "default implementation";
else
return delegate.thing();
}
}
class Delegate implements Thingable {
public String ... |
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)... | #Lambdatalk | Lambdatalk |
Here we present a rasterized version based on a single function "isInside".
1) isInside
Given A, B, C, P is in the triangle ABC if the three cross-products
PA^PB, PB^PC and PC^PA are of equal sign.
{def isInside
{lambda {:a :b :c :p}
{let { {:ax {car :a}} {:ay {cdr :a}}
{:bx {car :b}} {:by {cdr :b... |
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.
| #Elena | Elena | import system'io;
public program()
{
File.assign("output.txt").delete();
File.assign("\output.txt").delete();
Directory.assign("docs").delete();
Directory.assign("\docs").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.
| #Elixir | Elixir | File.rm!("input.txt")
File.rmdir!("docs")
File.rm!("/input.txt")
File.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
... | #Lambdatalk | Lambdatalk |
{require lib_matrix}
{M.determinant
{M.new [[1,2,3],
[4,5,6],
[7,8,9]]}}
-> 0
{M.permanent
{M.new [[1,2,3],
[4,5,6],
[7,8,9]]}}
-> 450
{M.determinant
{M.new [[1,2,3],
[4,5,6],
[7,8,-9]]}}
-> 54
{M.permanent
{M.new [[1,2,3],
[4,5,6],
[7,8,... |
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.
| #Forth | Forth | : safe-/ ( x y -- x/y )
['] / catch -55 = if cr ." divide by zero!" 2drop 0 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.
| #Fortran | Fortran |
program rosetta_divbyzero
implicit none
integer, parameter :: rdp = kind(1.d0)
real(rdp) :: normal,zero
normal = 1.d0
zero = 0.d0
call div_by_zero_check(normal,zero)
contains
subroutine div_by_zero_check(x,y)
use, intrinsic :: ieee_exceptions
use, intrinsic :: ieee_arithm... |
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.C3.A9j.C3.A0_Vu | Déjà Vu | is-numeric s:
true
try:
drop to-num s
catch value-error:
not
for v in [ "1" "0" "3.14" "hello" "12e3" "12ef" "-3" ]:
!.( v is-numeric v ) |
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... | #E | E | def isNumeric(specimen :String) {
try {
<import:java.lang.makeDouble>.valueOf(specimen)
return true
} catch _ {
return 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 ... | #Haskell | Haskell | import Data.List (groupBy, intersperse, sort, transpose)
import Data.Char (ord, toUpper)
import Data.Function(on)
import Numeric (showHex)
hexFromChar :: Char -> String
hexFromChar c = map toUpper $ showHex (ord c) ""
string :: String -> String
string xs = ('\"' : xs) <> "\""
char :: Char -> String
char c = ['... |
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... | #Phix | Phix | with javascript_semantics
constant tests = {"",
`"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln `,
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's... |
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible | Determine if a string is collapsible | Determine if a character string is collapsible.
And if so, collapse the string (by removing immediately repeated characters).
If a character string has immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An immediatel... | #PHP | PHP | <?php
function collapseString($string) {
$previousChar = null;
$collapse = '';
$charArray = preg_split('//u', $string, -1, PREG_SPLIT_NO_EMPTY);
for ($i = 0 ; $i < count($charArray) ; $i++) {
$currentChar = $charArray[$i];
if ($previousChar !== $currentChar) {
$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... | #Lua | Lua | function analyze(s)
print(string.format("Examining [%s] which has a length of %d:", s, string.len(s)))
if string.len(s) > 1 then
local last = string.byte(string.sub(s,1,1))
for i=1,string.len(s) do
local c = string.byte(string.sub(s,i,i))
if last ~= c then
... |
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... | #PicoLisp | PicoLisp | (de dining (Name State)
(loop
(prinl Name ": " State)
(state 'State # Dispatch according to state
(thinking 'hungry) # If thinking, get hungry
(hungry # If hungry, grab random fork
(if (rand T)
(and ... |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #PicoLisp | PicoLisp | (de disdate (Year Month Day)
(let? Date (date Year Month Day)
(let (Leap (date Year 2 29) D (- Date (date Year 1 1)))
(if (and Leap (= 2 Month) (= 29 Day))
(pack "St. Tib's Day, YOLD " (+ Year 1166))
(and Leap (>= D 60) (dec 'D))
(pack
(get
... |
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... | #PicoLisp | PicoLisp | (de neighbor (X Y Cost)
(push (prop X 'neighbors) (cons Y Cost))
(push (prop Y 'neighbors) (cons X Cost)) )
(de dijkstra (Curr Dest)
(let Cost 0
(until (== Curr Dest)
(let (Min T Next)
(for N (; Curr neighbors)
(with (car N)
(let D (+ Cost (cdr N))... |
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... | #Malbolge | Malbolge | seq[n_, b_] := FixedPointList[Total[IntegerDigits[#, b]] &, n];
root[n_Integer, base_: 10] := If[base == 10, #, BaseForm[#, base]] &[Last[seq[n, base]]]
persistance[n_Integer, base_: 10] := Length[seq[n, base]] - 2; |
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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | seq[n_, b_] := FixedPointList[Total[IntegerDigits[#, b]] &, n];
root[n_Integer, base_: 10] := If[base == 10, #, BaseForm[#, base]] &[Last[seq[n, base]]]
persistance[n_Integer, base_: 10] := Length[seq[n, 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... | #R | R |
names = unlist(strsplit("baker cooper fletcher miller smith", " "))
test <- function(floors) {
f <- function(name) which(name == floors)
if ((f('baker') != 5) &&
(f('cooper') != 1) &&
(any(f('fletcher') == 2:4)) &&
(f('miller') > f('cooper')) &&
(abs(f('fletcher') - f('cooper')) > 1) &&
... |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot ... | #jq | jq |
def dot(x; y):
reduce range(0;x|length) as $i (0; . + x[$i] * y[$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 ... | #Jsish | Jsish | /* Dot product, in Jsish */
function dot_product(ary1, ary2) {
if (ary1.length != ary2.length) throw "can't find dot product: arrays have different lengths";
var dotprod = 0;
for (var i = 0; i < ary1.length; i++) dotprod += ary1[i] * ary2[i];
return dotprod;
}
;dot_product([1,3,-5],[4,-2,-1]);
;//dot_... |
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... | #Prolog | Prolog | squeeze_( [], _, [] ).
squeeze_( [A], _, [A] ).
squeeze_( [A,A|T], A, R ) :- squeeze_( [A|T], A, R ).
squeeze_( [A,A|T], B, [A|R] ) :- dif( A, B ), squeeze_( [A|T], B, R ).
squeeze_( [A,B|T], S, [A|R] ) :- dif( A, B ), squeeze_( [B|T], S, R ).
squeeze( Str, SqueezeChar, Collapsed ) :-
string_chars( Str, Chars ),
... |
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... | #Python | Python | from itertools import groupby
def squeezer(s, txt):
return ''.join(item if item == s else ''.join(grp)
for item, grp in groupby(txt))
if __name__ == '__main__':
strings = [
"",
'"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ',
... |
http://rosettacode.org/wiki/Deming%27s_Funnel | Deming's Funnel | W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to ... | #Racket | Racket | #lang racket
(require math/distributions math/statistics plot)
(define dxs '(-0.533 0.270 0.859 -0.043 -0.205 -0.127 -0.071 0.275 1.251 -0.231
-0.401 0.269 0.491 0.951 1.150 0.001 -0.382 0.161 0.915 2.080 -2.337
0.034 -0.126 0.014 0.709 0.129 -1.093 -0.483 -1.193 0.020 -0.051
... |
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 ... | #Raku | Raku | sub mean { @_ R/ [+] @_ }
sub stddev {
# <(x - <x>)²> = <x²> - <x>²
sqrt( mean(@_ »**» 2) - mean(@_)**2 )
}
constant @dz = <
-0.533 0.270 0.859 -0.043 -0.205 -0.127 -0.071 0.275
1.251 -0.231 -0.401 0.269 0.491 0.951 1.150 0.001
-0.382 0.161 0.915 2.080 -2.337 0.034 -0.126 0.014
... |
http://rosettacode.org/wiki/Department_numbers | Department numbers | There is a highly organized city that has decided to assign a number to each of their departments:
police department
sanitation department
fire department
Each department can have a number between 1 and 7 (inclusive).
The three department numbers are to be unique (different from each other) and mu... | #C | C |
#include<stdio.h>
int main()
{
int police,sanitation,fire;
printf("Police Sanitation Fire\n");
printf("----------------------------------");
for(police=2;police<=6;police+=2){
for(sanitation=1;sanitation<=7;sanitation++){
for(fire=1;fire<=7;fire++){
if(police!=sanitation && 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 ... | #JavaScript | JavaScript | function Delegator() {
this.delegate = null ;
this.operation = function(){
if(this.delegate && typeof(this.delegate.thing) == 'function')
return this.delegate.thing() ;
return 'default implementation' ;
}
}
function Delegate() {
this.thing = function(){
return 'Delegate Implementation' ;
}... |
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects ... | #Julia | Julia | module Delegates
export Delegator, Delegate
struct Delegator{T}
delegate::T
end
struct Delegate end
operation(x::Delegator) = thing(x.delegate)
thing(::Any) = "default implementation"
thing(::Delegate) = "delegate implementation"
end # module Delegates |
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)... | #Lua | Lua | function det2D(p1,p2,p3)
return p1.x * (p2.y - p3.y)
+ p2.x * (p3.y - p1.y)
+ p3.x * (p1.y - p2.y)
end
function checkTriWinding(p1,p2,p3,allowReversed)
local detTri = det2D(p1,p2,p3)
if detTri < 0.0 then
if allowReversed then
local t = p3
p3 = p2
... |
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.
| #Emacs_Lisp | Emacs Lisp | (delete-file "input.txt")
(delete-directory "docs")
(delete-file "/input.txt")
(delete-directory "/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.
| #Erlang | Erlang |
-module(delete).
-export([main/0]).
main() ->
% current directory
ok = file:del_dir( "docs" ),
ok = file:delete( "input.txt" ),
% root directory
ok = file:del_dir( "/docs" ),
ok = file:delete( "/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
... | #Lua | Lua | -- Johnson–Trotter permutations generator
_JT={}
function JT(dim)
local n={ values={}, positions={}, directions={}, sign=1 }
setmetatable(n,{__index=_JT})
for i=1,dim do
n.values[i]=i
n.positions[i]=i
n.directions[i]=-1
end
return n
end
function _JT:largestMobile()
for i=#self.values,1,-1 do
... |
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.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Const divByZeroResult As Integer = -9223372036854775808
Sub CheckForDivByZero(result As Integer)
If result = divByZeroResult Then
Print "Division by Zero"
Else
Print "Division by Non-Zero"
End If
End Sub
Dim As Integer x, y
x = 0 : y = 0
CheckForDivByZero(x/y) ' automatic conv... |
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.
| #FutureBasic | FutureBasic |
include "ConsoleWindow"
on error stop
dim as long a
print a / 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.
| #Gambas | Gambas | Public Sub Main()
Try Print 1 / 0
If Error Then Print Error.Text
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... | #EasyLang | EasyLang | func is_numeric a$ . r .
h = number a$
r = 1 - error
# because every variable must be used
h = h
.
for s$ in [ "abc" "21a" "1234" "-13" "7.65" ]
call is_numeric s$ r
if r = 1
print s$ & " is numeric"
else
print s$ & " is not numeric"
.
. |
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Cop... | #EchoLisp | EchoLisp |
(string->number "albert")
→ #f
(string->number -666)
→ -666
(if (string->number 666) 'YES 'NO)
→ YES
|
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 ... | #J | J |
rc_unique=: monad define
string=. '"' , y , '"'
self_classification=. = y NB. deprecated- consumes space proportional to the squared tally of y (*: # y)
is_unique=. self_classification =&# y
if. is_unique do.
(# y) ; string ; 'unique'
else.
duplicate_masks=. (#~ (1 < +/"1)) self_classification
duplicate_... |
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 ... | #Java | Java |
import java.util.HashMap;
import java.util.Map;
// Title: Determine if a string has all unique characters
public class StringUniqueCharacters {
public static void main(String[] args) {
System.out.printf("%-40s %2s %10s %8s %s %s%n", "String", "Length", "All Unique", "1st Diff", "Hex", "Positi... |
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... | #PL.2FM | PL/M | 100H:
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9, S); END PRINT;
/* PRINT NUMBER */
PRINT$NUMBER: PROCEDURE (N);
DECLARE S (6) BYTE INITIAL ('.....$');
DECLARE (N, P) ADDRESS, C BAS... |
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... | #Prolog | Prolog | collapse_( [], [] ).
collapse_( [A], [A] ).
collapse_( [A,A|T], R ) :- collapse_( [A|T], R ).
collapse_( [A,B|T], [A|R] ) :- dif( A, B ), collapse_( [B|T], R ).
collapse( Str, Collapsed ) :-
string_chars( Str, Chars ),
collapse_( Chars, Result ),
string_chars( Collapsed, Result ). |
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... | #Maple | Maple | CheckSame:=proc(s)
local i, index;
printf("input: \"%s\", length: %a\n", s, StringTools:-Length(s));
for i from 2 to StringTools:-Length(s) do
if (s[i - 1] <> s[i]) then
printf("The given string has different characters.\n");
printf("The first different character is %a (0x%x) which appears at index %a.\n\n",... |
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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[AllSameCharacters]
AllSameCharacters[s_String] := Module[{c = Characters[s], i = 0, tf},
If[Length[c] > 1,
tf = AllTrue[Rest[c], (i++; # == First[c]) &];
If[tf,
Print["input = \"", s, "\", Length = ", StringLength[s],
", All the same!"]
,
Print["input = \"", s, "\", 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... | #Pike | Pike | class Philosopher
{
string name;
object left;
object right;
void create(string _name, object _left, object _right)
{
name = _name;
left = _left;
right = _right;
}
void take_forks()
{
if (left->take(this) && right->take(this))
{
wr... |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Pike | Pike | > Calendar.Discordian.now()->format_ext_ymd();
Result: "Pungenday, 59 Bureaucracy 3177"
> Calendar.Discordian.Day(Calendar.Day(2011,11,11))->format_ext_ymd();
Result: "Setting Orange, 23 The Aftermath 3177"
> Calendar.Discordian.Day(Calendar.Badi.Day(168,13,9))->format_ext_ymd();
Result: "Setting Orange, 23 The Af... |
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... | #Prolog | Prolog | rpath([target|reversed_path], distance) |
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... | #Modula-2 | Modula-2 | MODULE DigitalRoot;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
TYPE Root =
RECORD
persistence,root : LONGINT;
END;
PROCEDURE digitalRoot(inRoot,base : LONGINT) : Root;
VAR root,persistence,num : LONGINT;
BEGIN
root := ABS(inRoot);
persistence :=... |
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... | #Racket | Racket |
#lang racket
;; A quick `amb' implementation
(define fails '())
(define (fail) (if (pair? fails) ((car fails)) (error "no more choices!")))
(define (amb xs)
(let/cc k (set! fails (cons k fails)))
(if (pair? xs) (begin0 (car xs) (set! xs (cdr xs)))
(begin (set! fails (cdr fails)) (fail))))
(define (assert ... |
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 ... | #Julia | Julia | x = [1, 3, -5]
y = [4, -2, -1]
z = dot(x, y)
z = x'*y
z = x ⋅ y |
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 ... | #K | K | +/1 3 -5 * 4 -2 -1
3
1 3 -5 _dot 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... | #R | R | squeeze_string <- function(string, character){
str_iterable <- strsplit(string, "")[[1]]
message(paste0("Original String: ", "<<<", string, ">>>\n",
"Length: ", length(str_iterable), "\n",
"Character: ", character))
detect <- rep(TRUE, length(str_iterable))
... |
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... | #Racket | Racket | #lang racket/base
(define (squeeze-string s c)
(let loop ((cs (string->list s)) (squeezing? #f) (l 0) (acc null))
(cond [(null? cs) (values l (list->string (reverse acc)))]
[(and squeezing? (char=? (car cs) c)) (loop (cdr cs) #t l acc)]
[else (loop (cdr cs) (char=? (car cs) c) (add1 l) (cons... |
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 ... | #Ruby | Ruby | def funnel(dxs, &rule)
x, rxs = 0, []
for dx in dxs
rxs << (x + dx)
x = rule[x, dx]
end
rxs
end
def mean(xs) xs.inject(:+) / xs.size end
def stddev(xs)
m = mean(xs)
Math.sqrt(xs.inject(0.0){|sum,x| sum + (x-m)**2} / xs.size)
end
def experiment(label, dxs, dys, &rule)
rxs, rys = funnel(dxs, &... |
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... | #C.23 | C# | using System;
public class Program
{
public static void Main() {
for (int p = 2; p <= 7; p+=2) {
for (int s = 1; s <= 7; s++) {
int f = 12 - p - s;
if (s >= f) break;
if (f > 7) continue;
if (s == p || f == p) continue; //not even n... |
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 ... | #Kotlin | Kotlin | // version 1.1.51
interface Thingable {
fun thing(): String?
}
class Delegate(val responds: Boolean) : Thingable {
override fun thing() = if (responds) "delegate implementation" else null
}
class Delegator(d: Delegate) : Thingable by d {
fun operation() = thing() ?: "default implementation"
}
fun ma... |
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 ... | #Latitude | Latitude | Delegator ::= Object clone tap {
self delegate := Nil.
self clone := {
Parents above (parent self, 'clone) call tap {
self delegate := #'(self delegate).
}.
}.
self operation := {
localize.
if { this delegate slot? 'thing. } then {
this delegate thing.
} else {
"default imp... |
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)... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | p1 = Polygon@{{0, 0}, {5, 0}, {0, 5}};
p2 = Polygon@{{0, 0}, {5, 0}, {0, 6}};
! RegionDisjoint[p1, p2]
p1 = Polygon@{{0, 0}, {0, 5}, {5, 0}};
p2 = Polygon@{{0, 0}, {0, 5}, {5, 0}};
! RegionDisjoint[p1, p2]
p1 = Polygon@{{0, 0}, {5, 0}, {0, 5}};
p2 = Polygon@{{-10, 0}, {-5, 0}, {-1, 6}};
! RegionDisjoint[p1, p2]
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.
| #F.23 | F# | open System.IO
[<EntryPoint>]
let main argv =
let fileName = "input.txt"
let dirName = "docs"
for path in ["."; "/"] do
ignore (File.Delete(Path.Combine(path, fileName)))
ignore (Directory.Delete(Path.Combine(path, dirName)))
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.
| #Factor | Factor | "docs" "/docs" [ delete-tree ] bi@
"input.txt" "/input.txt" [ delete-file ] bi@ |
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
... | #Maple | Maple | M:=<<2|9|4>,<7|5|3>,<6|1|8>>:
with(LinearAlgebra):
Determinant(M);
Permanent(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
... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Permanent[m_List] :=
With[{v = Array[x, Length[m]]},
Coefficient[Times @@ (m.v), Times @@ v]
] |
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.
| #Go | Go | package main
import "fmt"
func divCheck(x, y int) (q int, ok bool) {
defer func() {
recover()
}()
q = x / y
return q, true
}
func main() {
fmt.Println(divCheck(3, 2))
fmt.Println(divCheck(3, 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.
| #Groovy | Groovy | def dividesByZero = { double n, double d ->
assert ! n.infinite : 'Algorithm fails if the numerator is already infinite.'
(n/d).infinite || (n/d).naN
} |
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... | #Elixir | Elixir | defmodule RC do
def is_numeric(str) do
case Float.parse(str) do
{_num, ""} -> true
_ -> false
end
end
end
["123", "-12.3", "123.", ".05", "-12e5", "+123", " 123", "abc", "123a", "12.3e", "1 2"] |> Enum.filter(&RC.is_numeric/1) |
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... | #Erlang | Erlang | is_numeric(L) ->
Float = (catch erlang:list_to_float(L)),
Int = (catch erlang:list_to_integer(L)),
is_number(Float) orelse is_number(Int). |
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 ... | #JavaScript | JavaScript | (() => {
'use strict';
// duplicatedCharIndices :: String -> Maybe (Char, [Int])
const duplicatedCharIndices = s => {
const
duplicates = filter(g => 1 < g.length)(
groupBy(on(eq)(snd))(
sortOn(snd)(
zip(enumFrom(0))(chars(s))
... |
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible | Determine if a string is collapsible | Determine if a character string is collapsible.
And if so, collapse the string (by removing immediately repeated characters).
If a character string has immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An immediatel... | #PureBasic | PureBasic | EnableExplicit
DataSection
STR1:
Data.s ""
STR2:
Data.s "'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln "
STR3:
Data.s "..1111111111111111111111111111111111111111111111111111111111111117777888"
STR4:
Data.s "I never give 'em hell, I just tell the truth, and they think it's hell.... |
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible | Determine if a string is collapsible | Determine if a character string is collapsible.
And if so, collapse the string (by removing immediately repeated characters).
If a character string has immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An immediatel... | #Python | Python | from itertools import groupby
def collapser(txt):
return ''.join(item for item, grp in groupby(txt))
if __name__ == '__main__':
strings = [
"",
'"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ',
"..1111111111111111111111111111111111111111111111111... |
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... | #Nanoquery | Nanoquery | def analyze(s)
s = str(s)
println "Examining [" + s + "] which has a length of " + str(len(s)) + ":"
if len(s) < 2
println "\tAll characters in the string are the same."
return
end
for i in range(0, len(s) - 2)
if s[i] != s[i + 1]
println "\tNot all characters... |
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... | #Nim | Nim | import strformat
proc analyze(str: string) =
if str.len() > 1:
var first = str[0]
for i, c in str:
if c != first:
echo "'", str, "': [len: ", str.len(), "] not all characters are the same. starts to differ at index ",
i, ": '", first, "' != '", c, "'... |
http://rosettacode.org/wiki/Dining_philosophers | Dining philosophers | The dining philosophers problem illustrates non-composability of low-level synchronization primitives like semaphores. It is a modification of a problem posed by Edsger Dijkstra.
Five philosophers, Aristotle, Kant, Spinoza, Marx, and Russell (the tasks) spend their time thinking and eating spaghetti. They eat at a rou... | #Prolog | Prolog | dining_philosophers :-
new(D, window('Dining philosophers')),
new(S, window('Dining philosophers : statistics')),
send(D, size, new(_, size(800,800))),
new(E, ellipse(400,400)),
send(E, center, point(400,400)),
send(D, display, E),
new(F1, fork(0)),
new(F2, fork(1)),
new(F3, fork(2)),
new(F4, fork(3)),
n... |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #PowerBASIC | PowerBASIC | #COMPILE EXE
#DIM ALL
'change this for systems that use a different character
$DATESEP = "-"
FUNCTION day(date AS STRING) AS LONG
'date is same format as date$
DIM tmpdash1 AS LONG, tmpdash2 AS LONG
tmpdash1 = INSTR(date, $DATESEP)
tmpdash2 = INSTR(-1, date, $DATESEP)
FUNCTION = VAL(MID$(date, t... |
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... | #Python | Python | from collections import namedtuple, deque
from pprint import pprint as pp
inf = float('inf')
Edge = namedtuple('Edge', ['start', 'end', 'cost'])
class Graph():
def __init__(self, edges):
self.edges = [Edge(*edge) for edge in edges]
# print(dir(self.edges[0]))
self.vertices = {e.start f... |
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... | #Nanoquery | Nanoquery | def digital_root(n)
ap = 0
n = +(int(n))
while n >= 10
sum = 0
for digit in str(n)
sum += int(digit)
end
n = sum
ap += 1
end
return {ap, n}
end
println "here"
if main
values = {627615, 39390, 588825, 393900588225, 55}
for n in values
aproot = digital_root(n)
println format("%12d has additive... |
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... | #NetRexx | NetRexx | /* NetRexx ************************************************************
* Test digroot
**********************************************************************/
Say 'number -> digital_root persistence'
test_digroot(7 ,7, 0)
test_digroot(627615 ,9, 2)
test_digroot(39390 ,6, 2)
test_digroot(588225 ... |
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... | #Raku | Raku | use MONKEY-SEE-NO-EVAL;
sub parse_and_solve ($text) {
my %ids;
my $expr = (grammar {
state $c = 0;
rule TOP { <fact>+ { make join ' && ', $<fact>>>.made } }
rule fact { <name> (not)? <position>
{ make sprintf $<position>.made.fmt($0 ?? "!(%s)" !! "%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 ... | #Klingphix | Klingphix | :sq_mul
%c %i
( ) !c
len [
!i
$i get rot $i get rot * $c swap 0 put !c
] for
$c
;
:sq_sum
0 swap
len [
get rot + swap
] for
swap
;
( 1 3 -5 ) ( 4 -2 -1 )
sq_mul
sq_sum
pstack
" " input |
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 ... | #Kotlin | Kotlin | fun dot(v1: Array<Double>, v2: Array<Double>) =
v1.zip(v2).map { it.first * it.second }.reduce { a, b -> a + b }
fun main(args: Array<String>) {
dot(arrayOf(1.0, 3.0, -5.0), arrayOf(4.0, -2.0, -1.0)).let { println(it) }
} |
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... | #Raku | Raku | map {
my $squeeze = $^phrase;
sink $^reg;
$squeeze ~~ s:g/($reg)$0+/$0/;
printf "\nOriginal length: %d <<<%s>>>\nSqueezable on \"%s\": %s\nSqueezed length: %d <<<%s>>>\n",
$phrase.chars, $phrase, $reg.uniname, $phrase ne $squeeze, $squeeze.chars, $squeeze
},
'', ' ',
'"If I were two-faced, ... |
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... | #REXX | REXX | /*REXX program "squeezes" all immediately repeated characters in a string (or strings). */
@.= /*define a default for the @. array. */
#.1= ' '; @.1=
#.2= '-'; @.2= '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln '
#.3= '7'; @.3= ..111111111111111... |
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 ... | #Sidef | Sidef | func x̄(a) {
a.sum / a.len
}
func σ(a) {
sqrt(x̄(a.map{.**2}) - x̄(a)**2)
}
const Δ = (%n<
-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.19... |
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... | #C.2B.2B | C++ |
#include <iostream>
#include <iomanip>
int main( int argc, char* argv[] ) {
int sol = 1;
std::cout << "\t\tFIRE\t\tPOLICE\t\tSANITATION\n";
for( int f = 1; f < 8; f++ ) {
for( int p = 1; p < 8; p++ ) {
for( int s = 1; s < 8; s++ ) {
if( f != p && f != s && p != s && !... |
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 ... | #Logtalk | Logtalk | % define a category for holding the interface
% and implementation for delegator objects
:- category(delegator).
:- public(delegate/1).
:- public(set_delegate/1).
:- private(delegate_/1).
:- dynamic(delegate_/1).
delegate(Delegate) :-
::delegate_(Delegate).
set_delegate(Delegat... |
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 ... | #Lua | Lua | local function Delegator()
return {
operation = function(self)
if (type(self.delegate)=="table") and (type(self.delegate.thing)=="function") then
return self.delegate:thing()
else
return "default implementation"
end
end
}
end
local function Delegate()
return {
thing... |
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)... | #Modula-2 | Modula-2 | MODULE Overlap;
FROM EXCEPTIONS IMPORT AllocateSource,ExceptionSource,GetMessage,RAISE;
FROM LongStr IMPORT RealToFixed;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
TYPE
Point = RECORD
x,y : LONGREAL;
END;
Triangle = RECORD
p1,p2,p3 : Point;
END;
VAR
TextWinExSrc : Excepti... |
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.
| #Forth | Forth | s" input.txt" delete-file throw
s" /input.txt" delete-file throw |
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.
| #Fortran | Fortran | OPEN (UNIT=5, FILE="input.txt", STATUS="OLD") ! Current directory
CLOSE (UNIT=5, STATUS="DELETE")
OPEN (UNIT=5, FILE="/input.txt", STATUS="OLD") ! Root directory
CLOSE (UNIT=5, STATUS="DELETE") |
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.