task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Digital_root | Digital root | The digital root,
X
{\displaystyle X}
, of a number,
n
{\displaystyle n}
, is calculated:
find
X
{\displaystyle X}
as the sum of the digits of
n
{\displaystyle n}
find a new
X
{\displaystyle X}
by summing the digits of
X
{\displaystyle X}
, repeating until
X
{\displ... | #C.23 | C# | using System;
using System.Linq;
class Program
{
static Tuple<int, int> DigitalRoot(long num)
{
int additivepersistence = 0;
while (num > 9)
{
num = num.ToString().ToCharArray().Sum(x => x - '0');
additivepersistence++;
}
return new Tuple<int, in... |
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
... | #J | J | 10&#.inv 123321
1 2 3 3 2 1 |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an... | #Xfractint | Xfractint | Dragon3 {
Angle 4
Axiom XF
X=XF+Y
Y=XF-Y
} |
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... | #Erlang | Erlang |
-module( dinesman_multiple_dwelling ).
-export( [solve/2, task/0] ).
solve( All_persons, Rules ) ->
[house(Bottom_floor, B, C, D, Top_floor) || Bottom_floor <- All_persons, B <- All_persons, C <- All_persons, D <- All_persons, Top_floor <- All_persons,
lists:all( fun (Fun) -> Fun( house(Bottom_floor, B, C, D... |
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 ... | #DWScript | DWScript | function DotProduct(a, b : array of Float) : Float;
require
a.Length = b.Length;
var
i : Integer;
begin
Result := 0;
for i := 0 to a.High do
Result += a[i]*b[i];
end;
PrintLn(DotProduct([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... | #11l | 11l | F squeeze(input, include)
V s = ‘’
L(i) 0 .< input.len
I i == 0 | input[i - 1] != input[i] | (input[i - 1] == input[i] & input[i] != include)
s ‘’= input[i]
R s
V testStrings = [
‘’,
‘"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ’,
‘..11111111111111111111111... |
http://rosettacode.org/wiki/Doubly-linked_list/Definition | Doubly-linked list/Definition | Define the data structure for a complete Doubly Linked List.
The structure should support adding elements to the head, tail and middle of the list.
The structure should not allow circular loops
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definitio... | #Raku | Raku | role DLElem[::T] {
has DLElem[T] $.prev is rw;
has DLElem[T] $.next is rw;
has T $.payload = T;
method pre-insert(T $payload) {
die "Can't insert before beginning" unless $!prev;
my $elem = ::?CLASS.new(:$payload);
$!prev.next = $elem;
$elem.prev = $!prev;
$elem.next = self;
$!prev = $elem;
$el... |
http://rosettacode.org/wiki/Dice_game_probabilities | Dice game probabilities | Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.
They roll their dice and sum the totals of the faces. The player with the highest total wins (i... | #Lua | Lua |
local function simu(ndice1, nsides1, ndice2, nsides2)
local function roll(ndice, nsides)
local result = 0;
for i = 1, ndice do
result = result + math.random(nsides)
end
return result
end
local wins, coms = 0, 1000000
for i = 1, coms do
local roll1 = roll(ndice1, nsides1)
local ro... |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Jsish | Jsish | /* Determine if only one instance, in Jsish */
var sock;
try {
sock = new Socket({client:false, port:54321});
puts('\nApplication running for 30 seconds, from', strftime());
update(30000);
puts('\nApplication ended at', strftime());
} catch (err) {
puts('Applicaion already running');
exit(1);
... |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Julia | Julia |
using Sockets
const portnum = 12345
function canopen()
try
server = listen(portnum)
println("This is the only instance.")
sleep(20)
catch y
if findfirst("EADDRINUSE", string(y)) != nothing
println("There is already an instance running.")
end
end
end
... |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Kotlin | Kotlin | // version 1.0.6
import java.io.IOException
import java.net.*
object SingleInstance {
private var ss: ServerSocket? = null
fun alreadyRunning(): Boolean {
try {
ss = ServerSocket(65000, 10, InetAddress.getLocalHost()) // using private port 65000
}
catch (e: IO... |
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... | #EchoLisp | EchoLisp |
(lib 'tasks)
(define names #(Aristotle Kant Spinoza Marx Russell))
(define abouts #("Wittgenstein" "the nature of the World" "Kant" "starving"
"spaghettis" "the essence of things" "Ω" "📞" "⚽️" "🍅" "🌿"
"philosophy" "💔" "👠" "rosetta code" "his to-do list" ))
(define (about) (format "thinking about %a... |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Clojure | Clojure | (require '[clj-time.core :as tc])
(def seasons ["Chaos" "Discord" "Confusion" "Bureaucracy" "The Aftermath"])
(def weekdays ["Sweetmorn" "Boomtime" "Pungenday" "Prickle-Prickle" "Setting Orange"])
(def year-offset 1166)
(defn leap-year? [year]
(= 29 (tc/number-of-days-in-the-month year 2)))
(defn discordian-day... |
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... | #Delphi | Delphi | program Rosetta_Dijkstra_Console;
{$APPTYPE CONSOLE}
uses SysUtils; // for printing the result
// Conventional values (any negative values would do)
const
INFINITY = -1;
NO_VERTEX = -2;
const
NR_VERTICES = 6;
// DISTANCE_MATRIX[u, v] = length of directed edge from u to v, or -1 if no such edge exists.
... |
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... | #C.2B.2B | C++ | // Calculate the Digital Root and Additive Persistance of an Integer - Compiles with gcc4.7
//
// Nigel Galloway. July 23rd., 2012
//
#include <iostream>
#include <cmath>
#include <utility>
template<class P_> P_ IncFirst(const P_& src) {return P_(src.first + 1, src.second);}
std::pair<int, int> DigitalRoot(unsigned... |
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
... | #Java | Java | import java.util.*;
public class MultiplicativeDigitalRoot {
public static void main(String[] args) {
System.out.println("NUMBER MDR MP");
for (long n : new long[]{123321, 7739, 893, 899998}) {
long[] a = multiplicativeDigitalRoot(n);
System.out.printf("%6d %4d %4d%n... |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an... | #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
proc Dragon(D, P, Q); \Draw a colorful dragon curve
int D, P, Q; \recursive depth, coordinates of line segment
int R(2), \coordinates of generated new point
DX, DY, C; \deltas, color
... |
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... | #ERRE | ERRE | PROGRAM DINESMAN
BEGIN
! Floors are numbered 0 (ground) to 4 (top)
! "Baker, Cooper, Fletcher, Miller, and Smith live on different floors":
stmt1$="Baker<>Cooper AND Baker<>Fletcher AND Baker<>Miller AND "+"Baker<>Smith AND Cooper<>Fletcher AND Cooper<>Miller AND "+"Cooper<>Smith AND Fletcher<>Mil... |
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 ... | #D.C3.A9j.C3.A0_Vu | Déjà Vu | dot a b:
if /= len a len b:
Raise value-error "dot product needs two vectors with the same length"
0
while a:
+ * pop-from a pop-from b
!. dot [ 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... | #8080_Assembly | 8080 Assembly | puts: equ 9
org 100h
jmp demo
;;; Squeeze the string at DE on the character in C.
;;; The result is written starting at HL.
squeez: mvi b,'$' ; Last character seen
dcx d ; Move pointer back one item
sqzlp: mvi m,'$' ; Stop on end of string
inx d ; Increment input pointer
ldax d ; Grab character from input str... |
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... | #Action.21 | Action! | PROC Squeeze(CHAR ARRAY in,out CHAR a)
BYTE i,j
CHAR c
j=1 c=0
FOR i=1 TO in(0)
DO
IF in(i)#c OR in(i)#a THEN
c=in(i)
out(j)=c
j==+1
FI
OD
out(0)=j-1
RETURN
PROC Test(CHAR ARRAY s CHAR a)
CHAR ARRAY c(100)
BYTE CH=$02FC ;Internal hardware value for last key pressed
Sq... |
http://rosettacode.org/wiki/Doubly-linked_list/Definition | Doubly-linked list/Definition | Define the data structure for a complete Doubly Linked List.
The structure should support adding elements to the head, tail and middle of the list.
The structure should not allow circular loops
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definitio... | #REXX | REXX | ╔═════════════════════════════════════════════════════════════════════════╗
║ ☼☼☼☼☼☼☼☼☼☼☼ Functions of the List Manager ☼☼☼☼☼☼☼☼☼☼☼ ║
║ @init ─── initializes the List. ║
║ ... |
http://rosettacode.org/wiki/Dice_game_probabilities | Dice game probabilities | Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.
They roll their dice and sum the totals of the faces. The player with the highest total wins (i... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[GetProbability]
GetProbability[{dice1_List, n_Integer}, {dice2_List, m_Integer}] :=
Module[{a, b, lena, lenb},
a = Tuples[dice1, n];
a = Plus @@@ a;
lena = a // Length;
a = Tally[a];
a[[All, 2]] /= lena;
b = Tuples[dice2, m];
b = Plus @@@ b;
lenb = b // Length;
b = Tally[b];
b[[All, 2]]... |
http://rosettacode.org/wiki/Dice_game_probabilities | Dice game probabilities | Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.
They roll their dice and sum the totals of the faces. The player with the highest total wins (i... | #Nim | Nim | import bignum
from math import sum
proc counts(ndices, nsides: int): seq[int] =
result.setlen(ndices * nsides + 1)
for i in 1..nsides:
result[i] = 1
for i in 1..<ndices:
var c = newSeq[int](result.len)
for sum in i..(i * nsides):
for val in 1..nsides:
inc c[sum + val], result[sum]
... |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Lasso | Lasso | #!/usr/bin/lasso9
local(lockfile = file('/tmp/myprocess.lockfile'))
if(#lockfile -> exists) => {
stdoutnl('Error: App is running as of ' + #lockfile -> readstring)
abort
}
handle => {
#lockfile -> delete
}
stdoutnl('Starting execution')
#lockfile -> doWithClose => {
#lockfile -> writebytes(bytes(date))
}
... |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Liberty_BASIC | Liberty BASIC | 'Create a Mutex to prevent more than one instance from being open at a single time.
CallDLL #kernel32, "CreateMutexA", 0 as Long, 1 as Long, "Global\My Program" as ptr, mutex as ulong
CallDLL #kernel32, "GetLastError", LastError as Long
if LastError = 183 then 'Error returned when a Mutex already exists
'Close th... |
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... | #Eiffel | Eiffel | class
DINING_PHILOSOPHERS
create
make
feature -- Initialization
make
-- Create philosophers and forks.
local
first_fork: separate FORK
left_fork: separate FORK
right_fork: separate FORK
philosopher: separate PHILOSOPHER
i:... |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #CLU | CLU | % This program needs to be merged with PCLU's "useful.lib",
% so it can use get_argv to read the command line.
%
% pclu -merge $CLUHOME/lib/useful.lib -compile cmdline.clu
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Represent a day in the Discordian calendar %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
eris... |
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... | #Erlang | Erlang |
-module(dijkstra).
-include_lib("eunit/include/eunit.hrl").
-export([dijkstrafy/3]).
% just hide away recursion so we have a nice interface
dijkstrafy(Graph, Start, End) when is_map(Graph) ->
shortest_path(Graph, [{0, [Start]}], End, #{}).
shortest_path(_Graph, [], _End, _Visited) ->
% if we're not going anywhe... |
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... | #Clojure | Clojure |
(defn dig-root [value]
(let [digits (fn [n]
(map #(- (byte %) (byte \0))
(str n)))
sum (fn [nums]
(reduce + nums))]
(loop [n value
step 0]
(if (< n 10)
{:n value :add-persist step :digital-root n}
(recur (sum ... |
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
... | #jq | jq | def do_until(condition; next):
def u: if condition then . else (next|u) end;
u;
def mdroot(n):
def multiply: reduce .[] as $i (1; .*$i);
# state: [mdr, persist]
[n, 0]
| do_until( .[0] < 10;
[(.[0] | tostring | explode | map(.-48) | multiply), .[1] + 1]
);
# Produce a table wit... |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an... | #Yabasic | Yabasic | w = 390 : h = int(w * 11 / 16)
open window w, h
level = 18 : insize = 247
x = 92 : y = 94
iters = 2^level
qiter = 510/iters
SQ = sqrt(2) : QPI = pi/4
rotation = 0 : iter = 0 : rq = 1.0
dim rqs(level)
color 0,0,0
clear window
dragon()
sub dragon()
if level<=0 then
yn = sin(rotation)*insize + y
xn = cos(ro... |
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... | #F.23 | F# |
// Dinesman's multiple-dwelling. Nigel Galloway: September 23rd., 2020
type names = |Baker=0 |Cooper=1 |Miller=2 |Smith=3 |Fletcher=4
let fN=Ring.PlainChanges [|for n in System.Enum.GetValues(typeof<names>)->n:?>names|]
let fG n g l=n|>Array.pairwise|>Array.forall(fun n->match n with (n,i) when (n=g && i=l)->false |(... |
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 ... | #Draco | Draco | proc nonrec dot_product([*] int a, b) int:
int total;
word i;
total := 0;
for i from 0 upto dim(a,1)-1 do
total := total + a[i] * b[i]
od;
total
corp
proc nonrec main() void:
[3] int a = (1, 3, -5);
[3] int b = (4, -2, -1);
write(dot_product(a, b))
corp |
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... | #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Squeezable is
procedure Squeeze (S : in String; C : in Character) is
Res : String (1 .. S'Length);
Len : Natural := 0;
begin
Put_Line ("Character to be squeezed: '" & C & "'");
Put_Line ("Input = <<<" & S & ">>>, length =" & S'Length'Image... |
http://rosettacode.org/wiki/Doubly-linked_list/Definition | Doubly-linked list/Definition | Define the data structure for a complete Doubly Linked List.
The structure should support adding elements to the head, tail and middle of the list.
The structure should not allow circular loops
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definitio... | #Ring | Ring |
# Project : Doubly-linked list/Definition
test = [1, 5, 7, 0, 3, 2]
insert(test, 0, 9)
insert(test, len(test), 4)
item = len(test)/2
insert(test, item, 6)
showarray(test)
func showarray(vect)
svect = ""
for n = 1 to len(vect)
svect = svect + vect[n] + " "
next
svect =... |
http://rosettacode.org/wiki/Dice_game_probabilities | Dice game probabilities | Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.
They roll their dice and sum the totals of the faces. The player with the highest total wins (i... | #ooRexx | ooRexx | Numeric Digits 30
Call test '9 4 6 6'
Call test '5 10 6 7'
Exit
test:
Parse Arg w1 s1 w2 s2
p1.=0
p2.=0
Call pp 1,w1,s1,p1.,p2.
Call pp 2,w2,s2,p1.,p2.
p2low.=0
Do x=w1 To w1*s1
Do y=0 To x-1
p2low.x+=p2.y
End
End
pwin1=0
Do x=w1 To w1*s1
pwin1+=p1.x*p2low.x
End
Say 'Player 1 has' w1 'dice with' s1 'sid... |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #M2000_Interpreter | M2000 Interpreter |
Module Checkit {
Try {
Open "MYLOCK" For Output Exclusive As #F
Print "DO SOMETHING"
A$=Key$
Close#f
}
}
|
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | $Epilog := Print["Another instance is running "];
If[Attributes[Global`Mutex] == {Protected},
Exit[],
Global`Mutex[x_] := Locked; Protect[Global`Mutex];
] |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Nim | Nim | import os, posix
let fn = getHomeDir() & "rosetta-code-lock"
proc ooiUnlink {.noconv.} = discard unlink fn
proc onlyOneInstance =
var fl = TFlock(lType: F_WRLCK.cshort, lWhence: SEEK_SET.cshort)
var fd = getFileHandle fn.open fmReadWrite
if fcntl(fd, F_SETLK, addr fl) < 0:
stderr.writeLine "Another instan... |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #OCaml | OCaml | open Sem
let () =
let oflags = [Unix.O_CREAT;
Unix.O_EXCL] in
let sem = sem_open "MyUniqueName" ~oflags () in
(* here the real code of the app *)
Unix.sleep 20;
(* end of the app *)
sem_unlink "MyUniqueName";
sem_close sem |
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... | #Elixir | Elixir |
defmodule Philosopher do
defstruct missing: [], clean: [], promised: []
def run_demo do
pid1 = spawn(__MODULE__, :init, ["Russell"])
pid2 = spawn(__MODULE__, :init, ["Marx"])
pid3 = spawn(__MODULE__, :init, ["Spinoza"])
pid4 = spawn(__MODULE__, :init, ["Kant"])
pid5 = spawn(__MODULE__, :in... |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #D | D | import std.stdio, std.datetime, std.conv, std.string;
immutable seasons = ["Chaos", "Discord", "Confusion",
"Bureaucracy", "The Aftermath"],
weekday = ["Sweetmorn", "Boomtime", "Pungenday",
"Prickle-Prickle", "Setting Orange"],
apostle = ["Mungday", "Mojod... |
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... | #F.23 | F# |
//Dijkstra's algorithm: Nigel Galloway, August 5th., 2018
[<CustomEquality;CustomComparison>]
type Dijkstra<'N,'G when 'G:comparison>={toN:'N;cost:Option<'G>;fromN:'N}
override g.Equals n =match n with| :? Dijkstra<'N,'G> as n->n.cost=g.cost|_->false
... |
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... | #CLU | CLU | sum_digits = proc (n, base: int) returns (int)
sum: int := 0
while n > 0 do
sum := sum + n // base
n := n / base
end
return (sum)
end sum_digits
digital_root = proc (n, base: int) returns (int, int)
persistence: int := 0
while n >= base do
persistence := persistence + 1... |
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... | #Common_Lisp | Common Lisp | (defun digital-root (number &optional (base 10))
(loop for n = number then s
for ap = 1 then (1+ ap)
for s = (sum-digits n base)
when (< s base)
return (values s ap)))
(loop for (nr base) in '((627615 10) (393900588225 10) (#X14e344 16) (#36Rdg9r 36))
do (multiple-value-bind ... |
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
... | #Julia | Julia |
function digitalmultroot{S<:Integer,T<:Integer}(n::S, bs::T=10)
-1 < n && 1 < bs || throw(DomainError())
ds = n
pers = 0
while bs <= ds
ds = prod(digits(ds, bs))
pers += 1
end
return (pers, ds)
end
|
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an... | #zkl | zkl | println(0'|<?xml version='1.0' encoding='utf-8' standalone='no'?>|"\n"
0'|<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN'|"\n"
0'|'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'>|"\n"
0'|<svg width='100%' height='100%' version='1.1'|"\n"
0'|xmlns='http://www.w3.org/2000/svg'>|);
order:=13.0; # akin to n... |
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem | Dinesman's multiple-dwelling problem | Task
Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below.
Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of... | #Factor | Factor | USING: kernel
combinators.short-circuit
math math.combinatorics math.ranges
sequences
qw prettyprint ;
IN: rosetta.dinesman
: /= ( x y -- ? ) = not ;
: fifth ( seq -- elt ) 4 swap nth ;
: meets-constraints? ( seq -- ? )
{
[ first 5 /= ] ! Baker does not live o... |
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 ... | #EchoLisp | EchoLisp |
(define a #(1 3 -5))
(define b #(4 -2 -1))
;; function definition
(define ( ⊗ a b) (for/sum ((x a)(y b)) (* x y)))
(⊗ a b) → 3
;; library
(lib 'math)
(dot-product a b) → 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... | #ALGOL_68 | ALGOL 68 | BEGIN
# returns a squeezed version of s #
# i.e. s with adjacent duplicate c characters removed #
PRIO SQUEEZE = 9;
OP SQUEEZE = ( STRING s, CHAR c )STRING:
IF s = ""
THEN "" # empty string ... |
http://rosettacode.org/wiki/Doubly-linked_list/Definition | Doubly-linked list/Definition | Define the data structure for a complete Doubly Linked List.
The structure should support adding elements to the head, tail and middle of the list.
The structure should not allow circular loops
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definitio... | #Ruby | Ruby | (cond-expand
(r7rs)
(chicken (import r7rs)))
(import (scheme base))
(import (scheme write))
(import (scheme case-lambda))
(import (scheme process-context))
;; A doubly-linked list will be represented by a reference to any of
;; its nodes. This is possible because the "root node" is marked as
;; such.
(define-re... |
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... | #11l | 11l | F collapse(s)
V cs = ‘’
V last = Char("\0")
L(c) s
I c != last
cs ‘’= c
last = c
R cs
V strings = [
‘’,
‘"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ’,
‘..1111111111111111111111111111111111111111111111111111111111111117777888’,
‘I never give ... |
http://rosettacode.org/wiki/Dice_game_probabilities | Dice game probabilities | Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.
They roll their dice and sum the totals of the faces. The player with the highest total wins (i... | #Perl | Perl | use List::Util qw(sum0 max);
sub comb {
my ($s, $n) = @_;
$n || return (1);
my @r = (0) x ($n - max(@$s) + 1);
my @c = comb($s, $n - 1);
foreach my $i (0 .. $#c) {
$c[$i] || next;
foreach my $k (@$s) {
$r[$i + $k] += $c[$i];
}
}
return @r;
}
sub winnin... |
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... | #11l | 11l | F analyze(s)
print(‘Examining [’s‘] which has a length of ’s.len‘:’)
I s.len > 1
V b = s[0]
L(c) s
V i = L.index
I c != b
print(‘ Not all characters in the string are the same.’)
print(‘ '’c‘' (0x’hex(c.code)‘) is different at position ’i)
R
... |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Oz | Oz | functor
import Application Open System
define
fun {IsAlreadyRunning}
try
S = {New Open.socket init}
in
{S bind(takePort:12345)}
false
catch system(os(os "bind" ...) ...) then
true
end
end
if {IsAlreadyRunning} then
{System.showInfo "Exiting because already running."}
... |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Perl | Perl | use Fcntl ':flock';
INIT
{
die "Not able to open $0\n" unless (open ME, $0);
die "I'm already running !!\n" unless(flock ME, LOCK_EX|LOCK_NB);
}
sleep 60; # then your code goes here |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Phix | Phix | -- demo\rosetta\Single_instance.exw
without js
include pGUI.e
function copydata_cb(Ihandle /*ih*/, atom pCommandLine, integer size)
-- (the first instance is sent a copy of the second one's command line)
printf(1,"COPYDATA(%s, %d)\n",{peek_string(pCommandLine), size});
return IUP_DEFAULT;
end function
Iup... |
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... | #Erlang | Erlang |
%%%
%%% to compile and run:
%%% $ erl
%%% > c(rosetta).
%%% {ok,rosetta}
%%% > rosetta:dining().
%%%
%%% contributor: bksteele
%%%
-module(rosetta).
-export([dining/0]).
sleep(T) ->
receive
after T ->
true
end.
doForks(ForkList) ->
receive
{grabforks, {Left, Right}} ->
... |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Delphi | Delphi |
program Discordian_date;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.DateUtils;
type
TDateTimeHelper = record helper for TDateTime
const
seasons: array of string = ['Chaos', 'Discord', 'Confusion', 'Bureaucracy',
'The Aftermath'];
weekday: array of string = ['Sweetmorn', 'Boomt... |
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... | #Go | Go | package main
import (
"container/heap"
"fmt"
)
// A PriorityQueue implements heap.Interface and holds Items.
type PriorityQueue struct {
items []Vertex
m map[Vertex]int // value to index
pr map[Vertex]int // value to priority
}
func (pq *PriorityQueue) Len() int { return len(pq.items) }
func... |
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... | #Component_Pascal | Component Pascal |
MODULE DigitalRoot;
IMPORT StdLog, Strings, TextMappers, DevCommanders;
PROCEDURE CalcDigitalRoot(x: LONGINT; OUT dr,pers: LONGINT);
VAR
str: ARRAY 64 OF CHAR;
i: INTEGER;
BEGIN
dr := 0;pers := 0;
LOOP
Strings.IntToString(x,str);
IF LEN(str$) = 1 THEN dr := x ;EXIT END;
i := 0;dr := 0;
WHILE (i < LEN(st... |
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
... | #Kotlin | Kotlin | // version 1.1.2
fun multDigitalRoot(n: Int): Pair<Int, Int> = when {
n < 0 -> throw IllegalArgumentException("Negative numbers not allowed")
else -> {
var mdr: Int
var mp = 0
var nn = n
do {
mdr = if (nn > 0) 1 else 0
... |
http://rosettacode.org/wiki/Dragon_curve | Dragon curve |
Create and display a dragon curve fractal.
(You may either display the curve directly or write it to an image file.)
Algorithms
Here are some brief notes the algorithms used and how they might suit various languages.
Recursively a right curling dragon is a right dragon followed by a left dragon, at 90-degree an... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 LET level=15: LET insize=120
20 LET x=80: LET y=70
30 LET iters=2^level
40 LET qiter=256/iters
50 LET sq=SQR (2): LET qpi=PI/4
60 LET rotation=0: LET iter=0: LET rq=1
70 DIM r(level)
75 GO SUB 80: STOP
80 REM Dragon
90 IF level>1 THEN GO TO 200
100 LET yn=SIN (rotation)*insize+y
110 LET xn=COS (rotation)*insize+x
1... |
http://rosettacode.org/wiki/Dinesman%27s_multiple-dwelling_problem | Dinesman's multiple-dwelling problem | Task
Solve Dinesman's multiple dwelling problem but in a way that most naturally follows the problem statement given below.
Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of... | #Forth | Forth | 0 enum baker \ enumeration of all tenants
enum cooper
enum fletcher
enum miller
constant smith
create names \ names of all the tenants
," Baker"
," Cooper"
," Fletcher"
," Miller"
," Smith" \ get name, type it
does> 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 ... | #Eiffel | Eiffel | class
APPLICATION
create
make
feature {NONE} -- Initialization
make
-- Run application.
do
print(dot_product(<<1, 3, -5>>, <<4, -2, -1>>).out)
end
feature -- Access
dot_product (a, b: ARRAY[INTEGER]): INTEGER
-- Dot product of vectors `a' and `b'.
require
a.lower = b.lower
a.upper = b... |
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... | #APL | APL | task←{
⍝ Squeeze a string
squeeze ← ⊢(/⍨)≠∨1,1↓⊣≠¯1⌽⊢
⍝ Display string and length in the manner given in the task
display ← {(¯2↑⍕≢⍵),' «««',⍵,'»»»'}
⍝ Squeeze string and display output
show ← {
r← ⊂'chr: ''',⍺,''''
r←r,⊂' in: ',display ⍵
r←r,⊂'out: ',display ⍺ squee... |
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... | #AutoHotkey | AutoHotkey | squeezable_string(str, char){
for i, ch in StrSplit(str){
if (ch <> prev) || !InStr(ch, char)
res .= ch
prev := ch
}
result := "
(ltrim
Original string:`t" StrLen(str) " characters`t«««" str "»»»
Squeezable Character «««" char "»»»
Resultant string:`t" StrLen(res)... |
http://rosettacode.org/wiki/Doubly-linked_list/Definition | Doubly-linked list/Definition | Define the data structure for a complete Doubly Linked List.
The structure should support adding elements to the head, tail and middle of the list.
The structure should not allow circular loops
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definitio... | #Scheme | Scheme | (cond-expand
(r7rs)
(chicken (import r7rs)))
(import (scheme base))
(import (scheme write))
(import (scheme case-lambda))
(import (scheme process-context))
;; A doubly-linked list will be represented by a reference to any of
;; its nodes. This is possible because the "root node" is marked as
;; such.
(define-re... |
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... | #8080_Assembly | 8080 Assembly | bdos: equ 5
puts: equ 9
org 100h
jmp main
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Collapse the $-terminated string at [HL]
colaps: mov b,m ; B = last character seen
inx h ; First character never collapses
mov d,h ; DE = output pointer
mov e,l
mov a,b ; Empty string?
cpi '$'
rz ; Then do... |
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... | #Action.21 | Action! | PROC Collapse(CHAR ARRAY in,out)
BYTE i,j
CHAR c
j=1 c=0
FOR i=1 TO in(0)
DO
IF in(i)#c THEN
c=in(i)
out(j)=c
j==+1
FI
OD
out(0)=j-1
RETURN
PROC Test(CHAR ARRAY s)
CHAR ARRAY c(100)
BYTE CH=$02FC ;Internal hardware value for last key pressed
Collapse(s,c)
PrintF("<<... |
http://rosettacode.org/wiki/Dice_game_probabilities | Dice game probabilities | Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.
They roll their dice and sum the totals of the faces. The player with the highest total wins (i... | #Phix | Phix | with javascript_semantics
function throwDie(integer nSides, nDice, s, sequence counts)
if nDice == 0 then
counts[s] += 1
else
for i=1 to nSides do
counts = throwDie(nSides, nDice-1, s+i, counts)
end for
end if
return counts
end function
function beatingProbability(i... |
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... | #Action.21 | Action! | PROC PrintBH(BYTE a)
BYTE ARRAY hex=['0 '1 '2 '3 '4 '5 '6 '7 '8 '9 'A 'B 'C 'D 'E 'F]
Put(hex(a RSH 4))
Put(hex(a&$0F))
RETURN
PROC Test(CHAR ARRAY s)
BYTE i,pos
pos=0
FOR i=2 TO s(0)
DO
IF s(i)#s(1) THEN
pos=i
EXIT
FI
OD
PrintF("""%S"" (len=%B) -> ",s,s(0))
IF pos=0 THE... |
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... | #Ada | Ada | with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_All_Chars_Are_Same is
procedure All_Chars_Are_Same (S : in String) is
First_Diff : Natural := 0;
begin
Put_Line ("Input = """ & S & """, length =" & S'Length'Image);
for I in S'First + 1 .. S'Las... |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #PicoLisp | PicoLisp | $ cat myScript
#!/usr/bin/picolisp /usr/lib/picolisp/lib.l
(wait 120000)
(bye) |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #PowerShell | PowerShell |
if (Get-Process -Name "notepad" -ErrorAction SilentlyContinue)
{
Write-Warning -Message "notepad is already running."
}
else
{
Start-Process -FilePath C:\Windows\notepad.exe
}
|
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #PureBasic | PureBasic | #MyApp="MyLittleApp"
Mutex=CreateMutex_(0,1,#MyApp)
If GetLastError_()=#ERROR_ALREADY_EXISTS
MessageRequester(#MyApp,"One instance is already started.")
End
EndIf
; Main code executes here
ReleaseMutex_(Mutex)
End |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Python | Python | import __main__, os
def isOnlyInstance():
# Determine if there are more than the current instance of the application
# running at the current time.
return os.system("(( $(ps -ef | grep python | grep '[" +
__main__.__file__[0] + "]" + __main__.__file__[1:] +
"' | w... |
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... | #Euphoria | Euphoria | constant FREE = 0, LOCKED = 1
sequence forks
forks = repeat(FREE,5)
procedure person(sequence name, integer left_fork, integer right_fork)
while 1 do
while forks[left_fork] = LOCKED or forks[right_fork] = LOCKED do
if forks[left_fork] = FREE then
puts(1, name & " hasn't right f... |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #Euphoria | Euphoria | function isLeapYear(integer year)
return remainder(year,4)=0 and remainder(year,100)!=0 or remainder(year,400)=0
end function
constant YEAR = 1, MONTH = 2, DAY = 3, DAY_OF_YEAR = 8
constant month_lengths = {31,28,31,30,31,30,31,31,30,31,30,31}
function dayOfYear(sequence Date)
integer d
if length(Date) ... |
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... | #Haskell | Haskell |
{-# LANGUAGE FlexibleContexts #-}
import Data.Array
import Data.Array.MArray
import Data.Array.ST
import Control.Monad.ST
import Control.Monad (foldM)
import Data.Set as S
dijkstra :: (Ix v, Num w, Ord w, Bounded w) => v -> v -> Array v [(v,w)] -> (Array v w, Array v v)
dijkstra src invalid_index adj_list = runST $... |
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... | #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. DIGITAL-ROOT.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 VARIABLES.
03 INPUT-NUMBER PIC 9(16).
03 INPUT-DIGITS REDEFINES INPUT-NUMBER,
PIC 9 OCCURS 16 TIMES.
03 DIGIT-SUM ... |
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
... | #M2000_Interpreter | M2000 Interpreter | multDigitalRoot=lambda (n as decimal) ->{
if n<0 then error "Negative numbers not allowed"
def decimal mdr, mp, nn
nn=n
do
mdr=IF(nn>0->1@, 0@)
while nn>0
mdr*=nn mod 10@
nn|div 10@
end while
mp++
nn=mdr
when mdr>=10
=(mdr, mp)
}
Document doc$
ia=(123321, 7739, 893, 899998)
in_ia=each(ia)
while in... |
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... | #Go | Go | package main
import "fmt"
// The program here is restricted to finding assignments of tenants (or more
// generally variables with distinct names) to floors (or more generally
// integer values.) It finds a solution assigning all tenants and assigning
// them to different floors.
// Change number and names of te... |
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 ... | #Ela | Ela | open list
dotp a b | length a == length b = sum (zipWith (*) a b)
| else = fail "Vector sizes must match."
dotp [1,3,-5] [4,-2,-1] |
http://rosettacode.org/wiki/Dot_product | Dot product | Task
Create a function/use an in-built function, to compute the dot product, also known as the scalar product of two vectors.
If possible, make the vectors of arbitrary length.
As an example, compute the dot product of the vectors:
[1, 3, -5] and
[4, -2, -1]
If implementing the dot ... | #Elena | Elena | import extensions;
import system'routines;
extension op
{
method dotProduct(int[] array)
= self.zipBy(array, (x,y => x * y)).summarize();
}
public program()
{
console.printLine(new int[]{1, 3, -5}.dotProduct(new int[]{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... | #AWK | AWK |
# syntax: GAWK -f DETERMINE_IF_A_STRING_IS_SQUEEZABLE.AWK
BEGIN {
arr[++n] = "" ; arr2[n] = " "
arr[++n] = "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln " ; arr2[n] = "-"
arr[++n] = "..111111... |
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... | #6502_Assembly | 6502 Assembly |
macro loadpair,regs,addr
lda #<\addr
sta \regs
lda #>\addr
sta \regs+1
endm
macro pushY
tya
pha
endm
macro popY
pla
tay
endm
|
http://rosettacode.org/wiki/Doubly-linked_list/Definition | Doubly-linked list/Definition | Define the data structure for a complete Doubly Linked List.
The structure should support adding elements to the head, tail and middle of the list.
The structure should not allow circular loops
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definitio... | #Swift | Swift | typealias NodePtr<T> = UnsafeMutablePointer<Node<T>>
class Node<T> {
var value: T
fileprivate var prev: NodePtr<T>?
fileprivate var next: NodePtr<T>?
init(value: T, prev: NodePtr<T>? = nil, next: NodePtr<T>? = nil) {
self.value = value
self.prev = prev
self.next = next
}
}
struct DoublyLinke... |
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... | #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Collapsible is
procedure Collapse (S : in String) is
Res : String (1 .. S'Length);
Len : Natural := 0;
begin
Put_Line ("Input = <<<" & S & ">>>, length =" & S'Length'Image);
for I in S'Range loop
if Len = 0 or else S(I) /= Res(Len... |
http://rosettacode.org/wiki/Determine_if_a_string_is_collapsible | Determine if a string is collapsible | Determine if a character string is collapsible.
And if so, collapse the string (by removing immediately repeated characters).
If a character string has immediately repeated character(s), the repeated characters are to be
deleted (removed), but not the primary (1st) character(s).
An immediatel... | #ALGOL_68 | ALGOL 68 | BEGIN
# returns a collapsed version of s #
# i.e. s with adjacent duplicate characters removed #
PROC collapse = ( STRING s )STRING:
IF s = ""
THEN "" # empty string #
ELSE # non-empt... |
http://rosettacode.org/wiki/Dice_game_probabilities | Dice game probabilities | Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.
They roll their dice and sum the totals of the faces. The player with the highest total wins (i... | #PL.2FI | PL/I | *process source attributes xref;
dicegame: Proc Options(main);
Call test(9, 4,6,6);
Call test(5,10,6,7);
test: Proc(w1,s1,w2,s2);
Dcl (w1,s1,w2,s2,x,y) Bin Fixed(31);
Dcl p1(100) Dec Float(18) Init((100)0);
Dcl p2(100) Dec Float(18) Init((100)0);
Dcl p2low(100) Dec Float(18) Init((100)0);
Call pp(w1,s1,p... |
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... | #ALGOL_68 | ALGOL 68 | BEGIN
# return the position of the first different character in s #
# or UPB s + 1 if all the characters are the same #
OP FIRSTDIFF = ( STRING s )INT:
IF UPB s <= LWB s
THEN
# 0 or 1 character #
... |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Racket | Racket |
#lang racket
(define *port* 12345) ; random large port number
(define listener-handler
(with-handlers ([exn? (λ(e) (printf "Already running, bye.\n") (exit))])
(tcp-listen *port*)))
(printf "Working...\n")
(sleep 10)
|
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #Raku | Raku | my $name = $*PROGRAM-NAME;
my $pid = $*PID;
my $lockdir = "/tmp";
my $lockfile = "$lockdir/$name.pid";
my $lockpid = "$lockfile$pid";
my $havelock = False;
END {
unlink $lockfile if $havelock;
try unlink $lockpid;
}
my $pidfile = open "$lockpid", :w orelse .die;
$pidfile.say($pid);
$pidfile.close;
if tr... |
http://rosettacode.org/wiki/Determine_if_only_one_instance_is_running | Determine if only one instance is running | This task is to determine if there is only one instance of an application running. If the program discovers that an instance of it is already running, then it should display a message indicating that it is already running and exit.
| #REXX | REXX | /* Simple ARexx program to open a port after checking if it's already open */
IF Show('PORTS','ROSETTA') THEN DO /* Port is already open; exit */
SAY 'This program may only be run in a single instance at a time.'
EXIT 5 /* Exit with a mild warning */
END
... |
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... | #F.23 | F# |
open System
let flip f x y = f y x
let rec cycle s = seq { yield! s; yield! cycle s }
type Agent<'T> = MailboxProcessor<'T>
type Message = Waiting of (Set<int> * AsyncReplyChannel<unit>) | Done of Set<int>
let reply (c: AsyncReplyChannel<_>) = c.Reply()
let strategy forks waiting =
let aux, waiting =... |
http://rosettacode.org/wiki/Discordian_date | Discordian date |
Task
Convert a given date from the Gregorian calendar to the Discordian calendar.
| #F.23 | F# | open System
let seasons = [| "Chaos"; "Discord"; "Confusion"; "Bureaucracy"; "The Aftermath" |]
let ddate (date:DateTime) =
let dyear = date.Year + 1166
let leapYear = DateTime.IsLeapYear(date.Year)
if leapYear && date.Month = 2 && date.Day = 29 then
sprintf "St. Tib's Day, %i YOLD" dyear
... |
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... | #Huginn | Huginn | import Algorithms as algo;
import Mathematics as math;
import Text as text;
class Edge {
_to = none;
_name = none;
_cost = none;
constructor( to_, name_, cost_ ) {
_to = to_;
_name = name_;
_cost = real( cost_ );
}
to_string() {
return ( "{}<{}>".format( _name, _cost ) );
}
}
class Path {
_id = none... |
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... | #Cowgol | Cowgol | include "cowgol.coh";
# Calculate the digital root and additive persistance of a number
# in a given base
sub digital_root(n: uint32, base: uint32): (root: uint32, pers: uint8) is
pers := 0;
while base < n loop
var step: uint32 := 0;
while n > 0 loop
step := step + (n % base);
... |
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.