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/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
... | #FreeBASIC | FreeBASIC | sub make_S( M() as double, S() as double, i as uinteger, j as uinteger )
'removes row j, column i from the matrix, stores result in S()
dim as uinteger ii, jj, size=ubound(M), ix, jx
for ii = 1 to size-1
if ii<i then ix = ii else ix = ii + 1
for jj = 1 to size-1
if jj<j then jx =... |
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.
| #CLU | CLU | % This will catch a divide-by-zero exception and
% return a oneof instead, with either the result or div_by_zero.
% Overflow and underflow are resignaled.
check_div = proc [T: type] (a, b: T) returns (otype)
signals (overflow, underflow)
where T has div: proctype (T,T) returns (T)
... |
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.
| #COBOL | COBOL | DIVIDE foo BY bar GIVING foobar
ON SIZE ERROR
DISPLAY "Division by zero detected!"
END-DIVIDE |
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... | #Befunge | Befunge | ~:0\`#v_:"+"-!#v_:"-"-!#v_::"E"-\"e"-*#v_ v
v _v# < < 0<
>~:0\`#v_>::"0"-0\`\"9"-0`+!#v_:"."-!#v_::"E"-\"e"-*!#v_ v
^ $< > > $ v
>~:0\`#v_>::"0"-0\`\"9"-0`+!#v_:"."-!#v_::"E"-\"e"-*... |
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... | #Bracmat | Bracmat | 43257349578692:/
F
260780243875083/35587980:/
S
247/30:~/#
F
80000000000:~/#
S |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters | Determine if a string has all unique characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are unique
indicate if or which character is duplicated and where
display each string and its length (as the strings are being ... | #D | D | import std.stdio;
void uniqueCharacters(string str) {
writefln("input: `%s`, length: %d", str, str.length);
foreach (i; 0 .. str.length) {
foreach (j; i + 1 .. str.length) {
if (str[i] == str[j]) {
writeln("String contains a repeated character.");
writefln("... |
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... | #Haskell | Haskell | import Text.Printf (printf)
import Data.Maybe (catMaybes)
import Control.Monad (guard)
input :: [String]
input = [ ""
, "The better the 4-wheel drive, the further you'll be from help when ya get stuck!"
, "headmistressship"
, "\"If I were two-faced, would I be wearing this one?\" --- Abraham L... |
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... | #J | J | STRINGS =: <;._2]0 :0
"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln
..1111111111111111111111111111111111111111111111111111111111111117777888
I never give 'em hell, I just tell the truth, and they think it's hell.
--- Harry S Truman
)
... |
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... | #Fortran | Fortran |
program demo_verify
implicit none
call homogeneous('')
call homogeneous('2')
call homogeneous('333')
call homogeneous('.55')
call homogeneous('tttTTT')
call homogeneous('4444 444k')
contains
subroutine homogeneous(str)
character(len=*),intent(in) :: str
character(len=:),allocatable :: ch
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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | names = <|1 -> "Aristotle", 2 -> "Kant", 3 -> "Spinoza", 4 -> "Marx", 5 -> "Russell"|>;
n = Length[names];
rp := Pause[RandomReal[4]];
PrintTemporary[Dynamic[Array[forks, n]]];
Clear[forks]; forks[_] := Null;
With[{nf = n},
ParallelDo[
With[{i1 = i, i2 = Mod[i + 1, nf, 1]},
Do[Print[names[i], " thinking"]; rp;... |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #MAD | MAD | R DISCORDIAN DATE CALCULATION
R
R PUNCH CARD SHOULD CONTAIN -
R MM/DD/YYYY
R IN GREGORIAN CALENDAR
NORMAL MODE IS INTEGER
VECTOR VALUES MLENGT =
0 0,0,31,59,90,120,151,181,212,243,273,304,334
VECTOR VALUES TI... |
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... | #Maxima | Maxima | load(graphs)$
g: create_graph([[1, "a"], [2, "b"], [3, "c"], [4, "d"], [5, "e"], [6, "f"]],
[[[1, 2], 7],
[[1, 3], 9],
[[1, 6], 14],
[[2, 3], 10],
[[2, 4], 15],
[[3, 4], 11],
[[3, 6], 2],
[[4, 5], 6],
[[5, 6], 9]], directed)$
shortest_weighted_path(1, 5, g);
/* [26, [1, 3, 4, 5]] */ |
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... | #Groovy | Groovy | class DigitalRoot {
static int[] calcDigitalRoot(String number, int base) {
BigInteger bi = new BigInteger(number, base)
int additivePersistence = 0
if (bi.signum() < 0) {
bi = bi.negate()
}
BigInteger biBase = BigInteger.valueOf(base)
while (bi >= biBase)... |
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root | Digital root/Multiplicative digital root | The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number,
n
{\displaystyle n}
, is calculated rather like the Digital root except digits are multiplied instead of being added:
Set
m
{\displaystyle m}
to
n
{\displaystyle n}
and
i
{\displaystyle i}
to
0
... | #Ring | Ring |
# Project : Digital root/Multiplicative digital root
load "stdlib.ring"
root = newlist(10, 5)
for r = 1 to 10
for x = 1 to 5
root[r][x] = 0
next
next
root2 = list(10)
for y = 1 to 10
root2[y] = 0
next
see "Number MDR MP" + nl
num = [123321, 7739, 893, 899998]
digroot(num)
see nl
num = 0:... |
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root | Digital root/Multiplicative digital root | The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number,
n
{\displaystyle n}
, is calculated rather like the Digital root except digits are multiplied instead of being added:
Set
m
{\displaystyle m}
to
n
{\displaystyle n}
and
i
{\displaystyle i}
to
0
... | #Ruby | Ruby | def mdroot(n)
mdr, persist = n, 0
until mdr < 10 do
mdr = mdr.digits.inject(:*)
persist += 1
end
[mdr, persist]
end
puts "Number: MDR MP", "====== === =="
[123321, 7739, 893, 899998].each{|n| puts "%6d: %d %2d" % [n, *mdroot(n)]}
counter = Hash.new{|h,k| h[k]=[]}
0.step do |i|
counter[mdroot... |
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... | #Nim | Nim | import algorithm
type
Person {.pure.} = enum Baker, Cooper, Fletcher, Miller, Smith
Floor = range[1..5]
var floors: array[Person, Floor] = [Floor 1, 2, 3, 4, 5]
while true:
if floors[Baker] != 5 and
floors[Cooper] != 1 and
floors[Fletcher] notin [1, 5] and
floors[Miller] > floors[Cooper] an... |
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 ... | #Groovy | Groovy | def dotProduct = { x, y ->
assert x && y && x.size() == y.size()
[x, y].transpose().collect{ xx, yy -> xx * yy }.sum()
} |
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable | Determine if a string is squeezable | Determine if a character string is squeezable.
And if so, squeeze the string (by removing any number of
a specified immediately repeated character).
This task is very similar to the task Determine if a character string is collapsible except
that only a specified character is squeezed instead... | #J | J |
dlb
}.~ (=&' ' (i.) 0:)
dtb
#~ ([: +./\. ' '&~:)
deb
#~ ((+.) (1: |. (> </\)))@(' '&~:)
|
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable | Determine if a string is squeezable | Determine if a character string is squeezable.
And if so, squeeze the string (by removing any number of
a specified immediately repeated character).
This task is very similar to the task Determine if a character string is collapsible except
that only a specified character is squeezed instead... | #Java | Java |
// Title: Determine if a string is squeezable
public class StringSqueezable {
public static void main(String[] args) {
String[] testStrings = new String[] {
"",
"\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ",
"..111111... |
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 ... | #Java | Java | import static java.lang.Math.*;
import java.util.Arrays;
import java.util.function.BiFunction;
public class DemingsFunnel {
public static void main(String[] args) {
double[] 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, ... |
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... | #ALGOL_68 | ALGOL 68 | BEGIN
# show possible department number allocations for police, sanitation and fire departments #
# the police department number must be even, all department numbers in the range 1 .. 7 #
# the sum of the department numbers must be 12 #
INT max department num... |
http://rosettacode.org/wiki/Delegates | Delegates | A delegate is a helper object used by another object. The delegator may send the delegate certain messages, and provide a default implementation when there is no delegate or the delegate does not respond to a message. This pattern is heavily used in Cocoa framework on Mac OS X. See also wp:Delegation pattern.
Objects ... | #C.2B.2B | C++ |
#include <tr1/memory>
#include <string>
#include <iostream>
#include <tr1/functional>
using namespace std;
using namespace std::tr1;
using std::tr1::function;
// interface for all delegates
class IDelegate
{
public:
virtual ~IDelegate() {}
};
//interface for delegates supporting thing
class IThing
{
public... |
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)... | #Go | Go | package main
import "fmt"
type point struct {
x, y float64
}
func (p point) String() string {
return fmt.Sprintf("(%.1f, %.1f)", p.x, p.y)
}
type triangle struct {
p1, p2, p3 point
}
func (t *triangle) String() string {
return fmt.Sprintf("Triangle %s, %s, %s", t.p1, t.p2, t.p3)
}
func (t *t... |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #AWK | AWK | system("rm input.txt")
system("rm /input.txt")
system("rm -rf docs")
system("rm -rf /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.
| #Axe | Axe | DelVar "appvINPUT" |
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
... | #FunL | FunL | def sgn( p ) = product( (if s(0) < s(1) xor i(0) < i(1) then -1 else 1) | (s, i) <- p.combinations(2).zip( (0:p.length()).combinations(2) ) )
def perm( m ) = sum( product(m(i, sigma(i)) | i <- 0:m.length()) | sigma <- (0:m.length()).permutations() )
def det( m ) = sum( sgn(sigma)*product(m(i, sigma(i)) | i <- 0:m.l... |
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
... | #GLSL | GLSL |
mat4 m1 = mat3(1, 2, 3, 4,
5, 6, 7, 8
9,10,11,12,
13,14,15,16);
float d = det(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.
| #Common_Lisp | Common Lisp | (handler-case (/ x y)
(division-by-zero () (format t "division by zero caught!~%"))) |
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.
| #D | D | import std.stdio, std.string, std.math, std.traits;
string divCheck(T)(in T numer, in T denom)
if (isIntegral!T || isFloatingPoint!T) {
Unqual!(typeof(numer / denom)) result;
string msg;
static if (isIntegral!T) {
try {
result = numer / denom;
} catch(Error e) {
m... |
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... | #Burlesque | Burlesque |
ps^^-]to{"Int""Double"}\/~[\/L[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... | #C | C | #include <ctype.h>
#include <stdlib.h>
int isNumeric (const char * s)
{
if (s == NULL || *s == '\0' || isspace(*s))
return 0;
char * p;
strtod (s, &p);
return *p == '\0';
} |
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 ... | #Delphi | Delphi |
program Determine_if_a_string_has_all_unique_characters;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
procedure string_has_repeated_character(str: string);
var
len, i, j: Integer;
begin
len := length(str);
Writeln('input: \', str, '\, length: ', len);
for i := 1 to len - 1 do
begin
for j := i + 1 to... |
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... | #Java | Java |
// Title: Determine if a string is collapsible
public class StringCollapsible {
public static void main(String[] args) {
for ( String s : new String[] {
"",
"\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ",
"..111111111111111111... |
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... | #FreeBASIC | FreeBASIC | dim as string s, nxt
input "Enter string: ", s
if len(s)<2 then 'A string with one or zero characters passes by default
print "All characters are the same."
end
end if
dim as ubyte i
for i = 1 to len(s)-1
nxt = mid(s, i+1, 1)
if mid(s, i, 1)<>nxt then 'if any character differs from the prev... |
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... | #Go | Go | package main
import "fmt"
func analyze(s string) {
chars := []rune(s)
le := len(chars)
fmt.Printf("Analyzing %q which has a length of %d:\n", s, le)
if le > 1 {
for i := 1; i < le; i++ {
if chars[i] != chars[i-1] {
fmt.Println(" Not all characters in the string a... |
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... | #Modula-3 | Modula-3 | MODULE DiningPhilosophers EXPORTS Main;
IMPORT IO, Random, Thread;
CONST
PartySize = 5; (* modify for more/fewer philosophers *)
TYPE
Closure = Thread.Closure OBJECT
(* thread information *)
which: [1..PartySize]; (* identifies the thread *)
OVERRIDES
apply := Live; (* procedure to execute *)
... |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Maple | Maple | convertDiscordian := proc(year, month, day)
local days31, days30, daysThisYear, i, dYear, dMonth, dDay, seasons, week, dayOfWeek;
days31 := [1, 3, 5, 7, 8, 10, 12];
days30 := [4, 6, 9, 11];
if month < 1 or month >12 then
error "Invalid month: %1", month;
end if;
if (member(month, days31) and day > 31) or (membe... |
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... | #Nim | Nim |
# Dijkstra algorithm.
from algorithm import reverse
import sets
import strformat
import tables
type
Edge = tuple[src, dst: string; cost: int]
Graph = object
vertices: HashSet[string]
neighbours: Table[string, seq[tuple[dst: string, cost: float]]]
#----------------------------------------------------... |
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... | #Haskell | Haskell | import Data.Bifunctor (bimap)
import Data.List (unfoldr)
import Data.Tuple (swap)
digSum :: Int -> Int -> Int
digSum base = sum . unfoldr f
where
f 0 = Nothing
f n = Just (swap (quotRem n base))
digRoot :: Int -> Int -> (Int, Int)
digRoot base =
head .
dropWhile ((>= base) . snd) . iterate (bimap succ... |
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root | Digital root/Multiplicative digital root | The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number,
n
{\displaystyle n}
, is calculated rather like the Digital root except digits are multiplied instead of being added:
Set
m
{\displaystyle m}
to
n
{\displaystyle n}
and
i
{\displaystyle i}
to
0
... | #Scala | Scala | import Stream._
object MDR extends App {
def mdr(x: BigInt, base: Int = 10): (BigInt, Long) = {
def multiplyDigits(x: BigInt): BigInt = ((x.toString(base) map (_.asDigit)) :\ BigInt(1))(_*_)
def loop(p: BigInt, c: Long): (BigInt, Long) = if (p < base) (p, c) else loop(multiplyDigits(p), c+1)
loop(mult... |
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... | #Perl | Perl | use strict;
use warnings;
use feature <state say>;
use List::Util 1.33 qw(pairmap);
use Algorithm::Permute qw(permute);
our %predicates = (
# | object | sprintf format for Perl expression |
# --------------------+-----------+------------------------------------+
'on bottom' => [ ''... |
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 ... | #Haskell | Haskell | dotp :: Num a => [a] -> [a] -> a
dotp a b | length a == length b = sum (zipWith (*) a b)
| otherwise = error "Vector sizes must match"
main = print $ dotp [1, 3, -5] [4, -2, -1] -- prints 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... | #jq | jq | # Assume $c is specified as a single character correctly
def squeeze($c): gsub("[\($c)]+"; $c);
def Guillemets: "«««\(.)»»»";
def Squeeze(s; $c):
"Squeeze character: \($c)",
(s | "Original: \(Guillemets) has length \(length)",
(squeeze($c) | "result is \(Guillemets) with length \(length)")),
""; |
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... | #J_2 | J | NB. Note |.!.1 here instead of the APL version's 1 , }. to more elegantly handle the null case in J
sq =: ] #~ ~: +. _1 |.!.1 ] ~: 1 |. ] |
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 ... | #Julia | Julia | # Run from Julia REPL to see the plots.
using Statistics, Distributions, Plots
const racket_xdata = [-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, ... |
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 ... | #Kotlin | Kotlin | // version 1.1.3
typealias Rule = (Double, Double) -> Double
val dxs = doubleArrayOf(
-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... |
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... | #ALGOL_W | ALGOL W | begin
% show possible department number allocations for police, sanitation and fire departments %
% the police department number must be even, all department numbers in the range 1 .. 7 %
% the sum of the department numbers must be 12 %
integer MAX_DEPARTMENT... |
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... | #APL | APL | 'PSF'⍪(⊢(⌿⍨)((∪≡⊢)¨↓∧(0=2|1⌷[2]⊢)∧12=+/))↑,⍳3/7 |
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 ... | #Clojure | Clojure | (defprotocol Thing
(thing [_]))
(defprotocol Operation
(operation [_]))
(defrecord Delegator [delegate]
Operation
(operation [_] (try (thing delegate) (catch IllegalArgumentException e "default implementation"))))
(defrecord Delegate []
Thing
(thing [_] "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 ... | #CoffeeScript | CoffeeScript |
class Delegator
operation: ->
if @delegate and typeof (@delegate.thing) is "function"
return @delegate.thing()
"default implementation"
class Delegate
thing: ->
"Delegate Implementation"
testDelegator = ->
# Delegator with no delegate.
a = new Delegator()
console.log a.operation()
... |
http://rosettacode.org/wiki/Determine_if_two_triangles_overlap | Determine if two triangles overlap | Determining if two triangles in the same plane overlap is an important topic in collision detection.
Task
Determine which of these pairs of triangles overlap in 2D:
(0,0),(5,0),(0,5) and (0,0),(5,0),(0,6)
(0,0),(0,5),(5,0) and (0,0),(0,5),(5,0)
(0,0),(5,0),(0,5) and (-10,0),(-5,0),(-1,6)... | #Groovy | Groovy | import java.util.function.BiFunction
class TriangleOverlap {
private static class Pair {
double first
double second
Pair(double first, double second) {
this.first = first
this.second = second
}
@Override
String toString() {
re... |
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.
| #BASIC | BASIC |
KILL "INPUT.TXT"
KILL "C:\INPUT.TXT"
SHELL "RMDIR /S /Q DIR"
SHELL "RMDIR /S /Q C:\DIR"
|
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.
| #Batch_File | Batch File | del input.txt
rd /s /q docs
del \input.txt
rd /s /q \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
... | #Go | Go | package main
import (
"fmt"
"permute"
)
func determinant(m [][]float64) (d float64) {
p := make([]int, len(m))
for i := range p {
p[i] = i
}
it := permute.Iter(p)
for s := it(); s != 0; s = it() {
pr := 1.
for i, σ := range p {
pr *= m[i][σ]
}
... |
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.
| #Delphi | Delphi | program DivideByZero;
{$APPTYPE CONSOLE}
uses SysUtils;
var
a, b: Integer;
begin
a := 1;
b := 0;
try
WriteLn(a / b);
except
on e: EZeroDivide do
Writeln(e.Message);
end;
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.
| #D.C3.A9j.C3.A0_Vu | Déjà Vu | divcheck x y:
true
try:
drop / x y
catch value-error:
not
if divcheck 1 0:
!print "Okay"
else:
!print "Division by 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... | #C.23 | C# | public static bool IsNumeric(string s)
{
double Result;
return double.TryParse(s, out Result); // TryParse routines were added in Framework version 2.0.
}
string value = "123";
if (IsNumeric(value))
{
// do something
} |
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... | #C.2B.2B | C++ | #include <sstream> // for istringstream
using namespace std;
bool isNumeric( const char* pszInput, int nNumberBase )
{
istringstream iss( pszInput );
if ( nNumberBase == 10 )
{
double dTestSink;
iss >> dTestSink;
}
else if ( nNumberBase == 8 || nNumberBase == 16 )
{
int nTestSink;
iss >> ( ( nNumber... |
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 ... | #Erlang | Erlang |
-module(string_examples).
-export([all_unique/1, all_unique_examples/0]).
all_unique(String) ->
CharPosPairs = lists:zip(String, lists:seq(1, length(String))),
Duplicates = [{Char1, Pos1, Pos2} || {Char1, Pos1} <- CharPosPairs,
{Char2, Pos2} <- CharPosPairs,
... |
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... | #JavaScript | JavaScript |
String.prototype.collapse = function() {
let str = this;
for (let i = 0; i < str.length; i++) {
while (str[i] == str[i+1]) str = str.substr(0,i) + str.substr(i+1);
}
return str;
}
// testing
let strings = [
'',
'"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ',
'..11111111... |
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... | #jq | jq | # Input: an array
# Output: a stream
def uniq: foreach .[] as $x ({x:nan, y:.[0]}; {x:$x, y:.x}; select(.x != .y) | .x);
def collapse: explode | [uniq] | implode; |
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... | #Groovy | Groovy | class Main {
static void main(String[] args) {
String[] tests = ["", " ", "2", "333", ".55", "tttTTT", "4444 444k"]
for (String s : tests) {
analyze(s)
}
}
static void analyze(String s) {
println("Examining [$s] which has a length of ${s.length()}")
if... |
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... | #Nim | Nim | import threadpool, locks, math, os, random
# to call randomize() as a seed, need to import random module
randomize()
type Philosopher = ref object
name: string
food: string
forkLeft, forkRight: int
const
n = 5
names = ["Aristotle", "Kant", "Spinoza", "Marx", "Russell"]
foods = [" rat poison", " cockroac... |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | DiscordianDate[y_, m_, d_] := Module[{year = ToString[y + 1166], month = m, day = d},
DMONTHS = {"Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"};
DDAYS = {"Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange"};
DayOfYear = DateDifference[{y} ,{y, m, d}] + 1;
LeapYearQ = (M... |
http://rosettacode.org/wiki/Dijkstra%27s_algorithm | Dijkstra's algorithm | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path pro... | #OCaml | OCaml | let list_vertices graph =
List.fold_left (fun acc ((a, b), _) ->
let acc = if List.mem b acc then acc else b::acc in
let acc = if List.mem a acc then acc else a::acc in
acc
) [] graph
let neighbors v =
List.fold_left (fun acc ((a, b), d) ->
if a = v then (b, d)::acc else acc
) []
let remove_... |
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... | #Huginn | Huginn | main( argv_ ) {
if ( size( argv_ ) < 2 ) {
throw Exception( "usage: digital-root {NUM}" );
}
n = argv_[1];
if ( ( size( n ) == 0 ) || ( n.find_other_than( "0123456789" ) >= 0 ) ) {
throw Exception( "{} is not a number".format( n ) );
}
shift = integer( '0' ) + 1;
acc = 0;
for ( d : n ) {
acc = 1 + ( acc +... |
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... | #Icon_and_Unicon | Icon and Unicon | procedure main(A)
every m := n := integer(!A) do {
ap := 0
while (*n > 1) do (ap +:= 1, n := sumdigits(n))
write(m," has additive persistence of ",ap," and digital root of ",n)
}
end
procedure sumdigits(n)
s := 0
n ? while s +:= move(1)
return s
end |
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root | Digital root/Multiplicative digital root | The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number,
n
{\displaystyle n}
, is calculated rather like the Digital root except digits are multiplied instead of being added:
Set
m
{\displaystyle m}
to
n
{\displaystyle n}
and
i
{\displaystyle i}
to
0
... | #Scheme | Scheme | ; Convert an integer into a list of its digits.
(define integer->list
(lambda (integer)
(let loop ((list '()) (int integer))
(if (< int 10)
(cons int list)
(loop (cons (remainder int 10) list) (quotient int 10))))))
; Return the product of the digits of an integer.
(define integer-prod... |
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... | #Phix | Phix | with javascript_semantics
enum Baker, Cooper, Fletcher, Miller, Smith
constant names={"Baker","Cooper","Fletcher","Miller","Smith"}
procedure test(sequence flats)
if flats[Baker]!=5
and flats[Cooper]!=1
and not find(flats[Fletcher],{1,5})
and flats[Miller]>flats[Cooper]
and abs(flats[Smith]-flats[... |
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 ... | #Hoon | Hoon | |= [a=(list @sd) b=(list @sd)]
=| sum=@sd
|-
?: |(?=(~ a) ?=(~ b)) sum
$(a t.a, b t.b, sum (sum:si sum (pro:si i.a i.b))) |
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 ... | #Hy | Hy | (defn dotp [a b]
(assert (= (len a) (len b)))
(sum (genexpr (* aterm bterm)
[(, aterm bterm) (zip a b)])))
(assert (= 3 (dotp [1 3 -5] [4 -2 -1]))) |
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable | Determine if a string is squeezable | Determine if a character string is squeezable.
And if so, squeeze the string (by removing any number of
a specified immediately repeated character).
This task is very similar to the task Determine if a character string is collapsible except
that only a specified character is squeezed instead... | #Julia | Julia | const teststringpairs = [
("", ' '),
(""""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln """, '-'),
("..1111111111111111111111111111111111111111111111111111111111111117777888", '7'),
("""I never give 'em hell, I just tell the truth, and they think it's hell. """, '.'),
(" ... |
http://rosettacode.org/wiki/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... | #Kotlin | Kotlin | fun main() {
val testStrings = arrayOf(
"",
"\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ",
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" ... |
http://rosettacode.org/wiki/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 ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | 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, -0.423, -0.021, -0.1... |
http://rosettacode.org/wiki/Deming%27s_Funnel | Deming's Funnel | W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of "rules" to try to ... | #Stretch_1 | Stretch 1 |
RadiusDistribution = NormalDistribution[0, 1];
AngleDistribution = UniformDistribution[{0, Pi}];
(*Mathematica has built in transformation functions, but this seems clearer given the way the instructions were written.*)
ToCartesian[{r_, a_}] := ToCartesian[{Abs@r, a - Pi}] /; Negative[r];
ToCartesian[{r_, a_}] := 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... | #AppleScript | AppleScript | on run
script
on |λ|(x)
script
on |λ|(y)
script
on |λ|(z)
if y ≠ z and 1 ≤ z and z ≤ 7 then
{{x, y, z} as string}
else
... |
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 ... | #Common_Lisp | Common Lisp | (defgeneric thing (object)
(:documentation "Thing the object."))
(defmethod thing (object)
"default implementation")
(defclass delegator ()
((delegate
:initarg :delegate
:reader delegator-delegate)))
(defmethod thing ((delegator delegator))
"If delegator has a delegate, invoke thing on the 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 ... | #D | D | class Delegator {
string delegate() hasDelegate;
string operation() {
if (hasDelegate is null)
return "Default implementation";
return hasDelegate();
}
typeof(this) setDg(string delegate() dg) {
hasDelegate = dg;
return this;
}
}
void main() {
im... |
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)... | #Haskell | Haskell | isOverlapping :: Triangle Double -> Triangle Double -> Bool
isOverlapping t1 t2 = vertexInside || midLineInside
where
vertexInside =
any (isInside t1) (vertices t2) ||
any (isInside t2) (vertices t1)
isInside t = (Outside /=) . overlapping t
midLineInside =
any (\p -> isInside t1 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.
| #C | C | #include <stdio.h>
int main() {
remove("input.txt");
remove("/input.txt");
remove("docs");
remove("/docs");
return 0;
} |
http://rosettacode.org/wiki/Delete_a_file | Delete a file | Task
Delete a file called "input.txt" and delete a directory called "docs".
This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root.
| #C.23 | C# | using System;
using System.IO;
namespace RosettaCode {
class Program {
static void Main() {
try {
File.Delete("input.txt");
Directory.Delete("docs");
File.Delete(@"\input.txt");
Directory.Delete(@"\docs");
} catch (Exc... |
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
... | #Haskell | Haskell | sPermutations :: [a] -> [([a], Int)]
sPermutations = flip zip (cycle [1, -1]) . foldl aux [[]]
where
aux items x = do
(f, item) <- zip (cycle [reverse, id]) items
f (insertEv x item)
insertEv x [] = [[x]]
insertEv x l@(y:ys) = (x : l) : ((y :) <$>) (insertEv x ys)
elemPos :: [[a]] -> Int -> ... |
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.
| #E | E | def divide(numerator, denominator) {
def floatQuotient := numerator / denominator
if (floatQuotient.isNaN() || floatQuotient.isInfinite()) {
return ["zero denominator"]
} else {
return ["ok", floatQuotient]
}
} |
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.
| #ECL | ECL |
DBZ(REAL8 Dividend,INTEGER8 Divisor) := Quotient/Divisor;
#option ('divideByZero', 'zero');
DBZ(10,0); //returns 0.0
|
http://rosettacode.org/wiki/Determine_if_a_string_is_numeric | Determine if a string is numeric | Task
Create a boolean function which takes in a string and tells whether it is a numeric string (floating point and negative numbers included) in the syntax the language uses for numeric literals or numbers converted from strings.
Other tasks related to string operations:
Metrics
Array length
String length
Cop... | #CFScript | CFScript | isNumeric(42) |
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... | #Clojure | Clojure | (defn numeric? [s]
(if-let [s (seq s)]
(let [s (if (= (first s) \-) (next s) s)
s (drop-while #(Character/isDigit %) s)
s (if (= (first s) \.) (next s) s)
s (drop-while #(Character/isDigit %) s)]
(empty? s)))) |
http://rosettacode.org/wiki/Determine_if_a_string_has_all_unique_characters | Determine if a string has all unique characters | Task
Given a character string (which may be empty, or have a length of zero characters):
create a function/procedure/routine to:
determine if all the characters in the string are unique
indicate if or which character is duplicated and where
display each string and its length (as the strings are being ... | #F.23 | F# |
// Determine if a string has all unique characters. Nigel Galloway: June 9th., 2020
let fN (n:string)=n.ToCharArray()|>Array.mapi(fun n g->(n,g))|>Array.groupBy(fun (_,n)->n)|>Array.filter(fun(_,n)->n.Length>1)
let allUnique n=match fN n with
g when g.Length=0->printfn "All charcters in <<<%s>>> (l... |
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... | #Julia | Julia | const teststrings = [
"",
""""If I were two-faced, would I be wearing this one?" --- Abraham Lincoln """,
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"""I never give 'em hell, I just tell the truth, and they think it's hell. """,
" ... |
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible | Determine if a string is collapsible | Determine if a character string is collapsible.
And if so, collapse the string (by removing immediately repeated characters).
If a character string has immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An immediatel... | #Kotlin | Kotlin | fun collapse(s: String): String {
val cs = StringBuilder()
var last: Char = 0.toChar()
for (c in s) {
if (c != last) {
cs.append(c)
last = c
}
}
return cs.toString()
}
fun main() {
val strings = arrayOf(
"",
"\"If I were two-faced, would ... |
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... | #Haskell | Haskell | import Numeric (showHex)
import Data.List (span)
import Data.Char (ord)
inconsistentChar :: Eq a => [a] -> Maybe (Int, a)
inconsistentChar [] = Nothing
inconsistentChar xs@(x:_) =
let (pre, post) = span (x ==) xs
in if null post
then Nothing
else Just (length pre, head post)
--------------------... |
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... | #OxygenBasic | OxygenBasic |
'=========================
class RoundTableWith5Seats
'=========================
% hungry 0
% beingUsed 1
% putDown 0
% empty 0
sys fork[5], plate[5],chair[5],philosopher[5]
sys first
method AddPasta() as sys
function rand() as sys
static seed=0x12345678
mov eax,seed
... |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Nim | Nim | import times, strformat
const
DiscordianOrigin = -1166
SaintTibsDay = "St. Tib’s Day"
type
Season = enum
sCha = (1, "Chaos"), sDis = "Discord", sCon = "Confusion",
sBur = "Bureaucracy", sAft = "The Aftermath"
ErisianWeekDay = enum
eSwe = "Sweetmorn", eBoo = "Boomtime", ePun = "Pungenday",
... |
http://rosettacode.org/wiki/Dijkstra%27s_algorithm | Dijkstra's algorithm | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path pro... | #PARI.2FGP | PARI/GP | shortestPath(G, startAt=1)={
my(n=#G[,1],dist=vector(n,i,9e99),prev=dist,Q=2^n-1);
dist[startAt]=0;
while(Q,
my(t=vecmin(vecextract(dist,Q)),u);
if(t==9e99, break);
for(i=1,#v,if(dist[i]==t && bittest(Q,i-1), u=i; break));
Q-=1<<(u-1);
for(i=1,n,
if(!G[u,i],next);
my(alt=dist[u]+G[u,i]);
if (alt <... |
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... | #J | J | digrot=: +/@(#.inv~&10)^:_
addper=: _1 + [: # +/@(#.inv~&10)^:a: |
http://rosettacode.org/wiki/Digital_root | Digital root | The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
, repeating until
X
{\displ... | #Java | Java | import java.math.BigInteger;
class DigitalRoot
{
public static int[] calcDigitalRoot(String number, int base)
{
BigInteger bi = new BigInteger(number, base);
int additivePersistence = 0;
if (bi.signum() < 0)
bi = bi.negate();
BigInteger biBase = BigInteger.valueOf(base);
while (bi.compar... |
http://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root | Digital root/Multiplicative digital root | The multiplicative digital root (MDR) and multiplicative persistence (MP) of a number,
n
{\displaystyle n}
, is calculated rather like the Digital root except digits are multiplied instead of being added:
Set
m
{\displaystyle m}
to
n
{\displaystyle n}
and
i
{\displaystyle i}
to
0
... | #Sidef | Sidef | func mdroot(n) {
var (mdr, persist) = (n, 0)
while (mdr >= 10) {
mdr = mdr.digits.prod
++persist
}
[mdr, persist]
}
say "Number: MDR MP\n====== === =="
[123321, 7739, 893, 899998].each{|n| "%6d: %3d %3d\n" \
.printf(n, mdroot(n)...) }
var counter = Hash()
Inf.times { ... |
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... | #Picat | Picat | import util.
import cp.
dinesman_cp =>
println(dinesman_cp),
N = 5,
X = [Baker, Cooper, Fletcher, Miller, Smith],
X :: 1..N,
all_different(X),
% Baker does not live on the fifth floor.
Baker #!= 5,
% Cooper does not live on the first floor.
Cooper #!= 1,
% Fletcher does not live... |
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 ... | #Icon_and_Unicon | Icon and Unicon | procedure main()
write("a dot b := ",dotproduct([1, 3, -5],[4, -2, -1]))
end
procedure dotproduct(a,b) #: return dot product of vectors a & b or error
if *a ~= *b & type(a) == type(b) == "list" then runerr(205,a) # invalid value
every (dp := 0) +:= a[i := 1 to *a] * b[i]
return dp
end |
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... | #Lua | Lua | function squeezable(s, rune)
print("squeeze: `" .. rune .. "`")
print("old: <<<" .. s .. ">>>, length = " .. string.len(s))
local last = nil
local le = 0
io.write("new: <<<")
for c in s:gmatch"." do
if c ~= last or c ~= rune then
io.write(c)
le = le + 1
... |
http://rosettacode.org/wiki/Determine_if_a_string_is_squeezable | Determine if a string is squeezable | Determine if a character string is squeezable.
And if so, squeeze the string (by removing any number of
a specified immediately repeated character).
This task is very similar to the task Determine if a character string is collapsible except
that only a specified character is squeezed instead... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[Squeeze]
Squeeze[s_String,sq_String]:=StringReplace[s,x:(sq..):>sq]
s={
"",
"\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln",
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ... |
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.