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/Checkpoint_synchronization | Checkpoint synchronization | The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before st... | #Ada | Ada | with Ada.Calendar; use Ada.Calendar;
with Ada.Numerics.Float_Random;
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Checkpoint is
package FR renames Ada.Numerics.Float_Random;
No_Of_Cubicles: constant Positive := 3;
-- That many workers can work in parallel
No_Of_Worker... |
http://rosettacode.org/wiki/Collections | Collections | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Collections are abstractions to represent sets of values.
In statically-typed languages, the values are typically of a common data type.
Task
Create a collection, and add a fe... | #EchoLisp | EchoLisp |
(define my-collection ' ( 🌱 ☀️ ☔️ ))
(set! my-collection (cons '🎥 my-collection))
(set! my-collection (cons '🐧 my-collection))
my-collection
→ (🐧 🎥 🌱 ☀️ ☔️)
;; save it
(local-put 'my-collection)
→ my-collection
|
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
... | #Lambdatalk | Lambdatalk |
{def comb
{def comb.r
{lambda {:m :n :N}
{if {= :m 0}
then {A.new {A.new}}
else {if {= :n :N}
then {A.new}
else {A.concat
{A.map {{lambda {:n :rest} {A.addfirst! :n :rest}} :n}
{comb.r {- :m 1} {+ :n 1} :N}}
{comb.r :m {+ :n 1} :N}}}}}}
{lambda {:m :n}
{... |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include ... | #PowerShell | PowerShell | # standard if
if (condition) {
# ...
}
# if-then-else
if (condition) {
# ...
} else {
# ...
}
# if-then-elseif-else
if (condition) {
# ...
} elseif (condition2) {
# ...
} else {
# ...
} |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Z80_Assembly | Z80 Assembly | ld hl,&8000 ;This is a comment |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #zig | zig | // This is a normal comment in Zig
/// This is a documentation comment in Zig (for the following line) |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #zkl | zkl | x=1; // comment ala C++
x=2; # ala scripts
/* ala C, these comments are parsed (also ala C) */
/* can /* be */ nested */
#if 0
also ala C (and parsed)
#endif
#<<<#
"here" comment, unparsed
#<<<# |
http://rosettacode.org/wiki/Chinese_remainder_theorem | Chinese remainder theorem | Suppose
n
1
{\displaystyle n_{1}}
,
n
2
{\displaystyle n_{2}}
,
…
{\displaystyle \ldots }
,
n
k
{\displaystyle n_{k}}
are positive integers that are pairwise co-prime.
Then, for any given sequence of integers
a
1
{\displaystyle a_{1}}
,
a
2
... | #Ada | Ada | with Ada.Text_IO, Mod_Inv;
procedure Chin_Rema is
N: array(Positive range <>) of Positive := (3, 5, 7);
A: array(Positive range <>) of Positive := (2, 3, 2);
Tmp: Positive;
Prod: Positive := 1;
Sum: Natural := 0;
begin
for I in N'Range loop
Prod := Prod * N(I);
end loop;
for I ... |
http://rosettacode.org/wiki/Chernick%27s_Carmichael_numbers | Chernick's Carmichael numbers | In 1939, Jack Chernick proved that, for n ≥ 3 and m ≥ 1:
U(n, m) = (6m + 1) * (12m + 1) * Product_{i=1..n-2} (2^i * 9m + 1)
is a Carmichael number if all the factors are primes and, for n > 4, m is a multiple of 2^(n-4).
Example
U(3, m) = (6m + 1) * (12m + 1) * (18m + 1)
U(4, m) = U(3, m) * (2^2 * 9m + 1)... | #J | J | a=: {{)v
if.3=y do.1729 return.end.
m=. z=. 2^y-4
f=. 6 12,9*2^}.i.y-1
while.do.
uf=.1+f*m
if.*/1 p: uf do. */x:uf return.end.
m=.m+z
end.
}} |
http://rosettacode.org/wiki/Chernick%27s_Carmichael_numbers | Chernick's Carmichael numbers | In 1939, Jack Chernick proved that, for n ≥ 3 and m ≥ 1:
U(n, m) = (6m + 1) * (12m + 1) * Product_{i=1..n-2} (2^i * 9m + 1)
is a Carmichael number if all the factors are primes and, for n > 4, m is a multiple of 2^(n-4).
Example
U(3, m) = (6m + 1) * (12m + 1) * (18m + 1)
U(4, m) = U(3, m) * (2^2 * 9m + 1)... | #Java | Java |
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
public class ChernicksCarmichaelNumbers {
public static void main(String[] args) {
for ( long n = 3 ; n < 10 ; n++ ) {
long m = 0;
boolean foundComposite = true;
List<Long> factors = nul... |
http://rosettacode.org/wiki/Chowla_numbers | Chowla numbers | Chowla numbers are also known as:
Chowla's function
chowla numbers
the chowla function
the chowla number
the chowla sequence
The chowla number of n is (as defined by Chowla's function):
the sum of the divisors of n excluding unity and n
where n is a positive integer
The s... | #C.2B.2B | C++ | #include <vector>
#include <iostream>
using namespace std;
int chowla(int n)
{
int sum = 0;
for (int i = 2, j; i * i <= n; i++)
if (n % i == 0) sum += i + (i == (j = n / i) ? 0 : j);
return sum;
}
vector<bool> sieve(int limit)
{
// True denotes composite, false denotes prime.
// Only interested in odd numb... |
http://rosettacode.org/wiki/Church_numerals | Church numerals | Task
In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.
Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.
C... | #J | J | chget=: {{(0;1;1;1) {:: y}}
chset=: {{
'A B'=.;y
'C D'=.B
'E F'=.D
<A;<C;<E;<<.x
}}
ch0=: {{
if.0=#y do.y=.;:'>:' end. NB. replace empty gerund with increment
0 chset y`:6^:2`''
}}
apply=: `:6
chNext=: {{(1+chget y) chset y}}
chAdd=: {{(x +&chget y) chset y}}
chSub=: {{(x -&chget y) chset y}}
chMu... |
http://rosettacode.org/wiki/Church_numerals | Church numerals | Task
In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.
Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.
C... | #Java | Java | package lvijay;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
public class Church {
public static interface ChurchNum extends Function<ChurchNum, ChurchNum> {
}
public static ChurchNum zero() {
return f -> x -> x;
}
public static ChurchNum next... |
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, a... | #Delphi | Delphi | program SampleClass;
{$APPTYPE CONSOLE}
type
TMyClass = class
private
FSomeField: Integer; // by convention, fields are usually private and exposed as properties
public
constructor Create;
destructor Destroy; override;
procedure SomeMethod;
property SomeField: Integer read FSomeField write... |
http://rosettacode.org/wiki/Cistercian_numerals | Cistercian numerals | Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999.
How they work
All Cistercian numerals begin with a vertical line segment, which by itself represents the number 0. Then, glyp... | #Plain_English | Plain English | To run:
Start up.
Show some example Cistercian numbers.
Wait for the escape key.
Shut down.
To show some example Cistercian numbers:
Put the screen's left plus 1 inch into the context's spot's x.
Clear the screen to the lightest gray color.
Use the black color.
Use the fat pen.
Draw 0.
Draw 1.
Draw 20.
Draw 300.
Draw... |
http://rosettacode.org/wiki/Cistercian_numerals | Cistercian numerals | Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999.
How they work
All Cistercian numerals begin with a vertical line segment, which by itself represents the number 0. Then, glyp... | #Python | Python | # -*- coding: utf-8 -*-
"""
Some UTF-8 chars used:
‾ 8254 203E ‾ OVERLINE
┃ 9475 2503 BOX DRAWINGS HEAVY VERTICAL
╱ 9585 2571 BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT
╲ 9586 2572 BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT
◸ 9720 25F8 UPPER LEFT TRIANGLE
◹ 9721 25F9 UPPER RIGHT ... |
http://rosettacode.org/wiki/Closest-pair_problem | Closest-pair problem |
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a function to find the closest two p... | #FreeBASIC | FreeBASIC |
Dim As Integer i, j
Dim As Double minDist = 1^30
Dim As Double x(9), y(9), dist, mini, minj
Data 0.654682, 0.925557
Data 0.409382, 0.619391
Data 0.891663, 0.888594
Data 0.716629, 0.996200
Data 0.477721, 0.946355
Data 0.925092, 0.818220
Data 0.624291, 0.142924
Data 0.211332, 0.221507
Data 0.293786, 0.691701... |
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of runnin... | #M2000_Interpreter | M2000 Interpreter |
Dim Base 0, A(10)
For i=0 to 9 {
a(i)=lambda i -> i**2
}
For i=0 to 9 {
Print a(i)()
}
|
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of runnin... | #Maple | Maple | > L := map( i -> (() -> i^2), [seq](1..10) ):
> seq( L[i](),i=1..10);
1, 4, 9, 16, 25, 36, 49, 64, 81, 100
> L[4]();
16
|
http://rosettacode.org/wiki/Circular_primes | Circular primes | Definitions
A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime.
For example:
1193 is a circular prime, since 1931, 9311 and 3119 are all also prime.
Note that a number which is a cyclic permutation ... | #REXX | REXX | /*REXX program finds & displays circular primes (with a title & in a horizontal format).*/
parse arg N hp . /*obtain optional arguments from the CL*/
if N=='' | N=="," then N= 19 /* " " " " " " */
if hp=='' | hp=="," then hip= 1000000 ... |
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points | Circles of given radius through two points |
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points.
Exceptions
r==0.0 should be treated as never describing circles (except in the case where the points are coincident).
If the points are coincident then an infinite number of circles with the point on thei... | #AWK | AWK |
# syntax: GAWK -f CIRCLES_OF_GIVEN_RADIUS_THROUGH_TWO_POINTS.AWK
# converted from PL/I
BEGIN {
split("0.1234,0,0.1234,0.1234,0.1234",m1x,",")
split("0.9876,2,0.9876,0.9876,0.9876",m1y,",")
split("0.8765,0,0.1234,0.8765,0.1234",m2x,",")
split("0.2345,0,0.9876,0.2345,0.9876",m2y,",")
leng = split("2... |
http://rosettacode.org/wiki/Chinese_zodiac | Chinese zodiac | Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zo... | #AppleScript | AppleScript | on run
-- TRADITIONAL STRINGS ---------------------------------------------------
-- ts :: Array Int (String, String) -- 天干 tiangan – 10 heavenly stems
set ts to zip(chars("甲乙丙丁戊己庚辛壬癸"), ¬
|words|("jiă yĭ bĭng dīng wù jĭ gēng xīn rén gŭi"))
-- ds :: Array Int (String, String) ... |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #6502_Assembly | 6502 Assembly | LDA $D011 ;screen control register 1
AND #%00100000 ;bit 5 clear = text mode, bit 5 set = gfx mode
BEQ isTerminal |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with Interfaces.C_Streams; use Interfaces.C_Streams;
procedure Test_tty is
begin
if Isatty(Fileno(Stdout)) = 0 then
Put_Line(Standard_Error, "stdout is not a tty.");
else
Put_Line(Standard_Error, "stdout is a tty.");
end if;
end Test_tty; |
http://rosettacode.org/wiki/Cholesky_decomposition | Cholesky decomposition | Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose:
A
=
L
L
T
{\displaystyle A=LL^{T}}
L
{\displaystyle L}
is called the Cholesky factor of
A
{\displaystyle A}
, and can be interpreted as a generalized square r... | #BBC_BASIC | BBC BASIC | DIM m1(2,2)
m1() = 25, 15, -5, \
\ 15, 18, 0, \
\ -5, 0, 11
PROCcholesky(m1())
PROCprint(m1())
PRINT
@% = &2050A
DIM m2(3,3)
m2() = 18, 22, 54, 42, \
\ 22, 70, 86, 62, \
\ 54, 86, 174, 134, \
\ 42, 62, 134, 10... |
http://rosettacode.org/wiki/Cholesky_decomposition | Cholesky decomposition | Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose:
A
=
L
L
T
{\displaystyle A=LL^{T}}
L
{\displaystyle L}
is called the Cholesky factor of
A
{\displaystyle A}
, and can be interpreted as a generalized square r... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
double *cholesky(double *A, int n) {
double *L = (double*)calloc(n * n, sizeof(double));
if (L == NULL)
exit(EXIT_FAILURE);
for (int i = 0; i < n; i++)
for (int j = 0; j < (i+1); j++) {
double s = 0;
for (in... |
http://rosettacode.org/wiki/Cheryl%27s_birthday | Cheryl's birthday | Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.
Cheryl gave them a list of ten possible dates:
May 15, May 16, May 19
June 17, June 18
July 14, July 16
August 14, August 15, August 17
Cheryl then tells Albert the month of birth, ... | #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Main is
type Months is
(January, February, March, April, May, June, July, August, September,
November, December);
type day_num is range 1 .. 31;
type birthdate is record
Month : Months;
Day : day_num;
Active : Boolean;
end recor... |
http://rosettacode.org/wiki/Checkpoint_synchronization | Checkpoint synchronization | The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before st... | #BBC_BASIC | BBC BASIC | INSTALL @lib$+"TIMERLIB"
nWorkers% = 3
DIM tID%(nWorkers%)
tID%(1) = FN_ontimer(10, PROCworker1, 1)
tID%(2) = FN_ontimer(11, PROCworker2, 1)
tID%(3) = FN_ontimer(12, PROCworker3, 1)
DEF PROCworker1 : PROCtask(1) : ENDPROC
DEF PROCworker2 : PROCtask(2) : ENDPROC
... |
http://rosettacode.org/wiki/Checkpoint_synchronization | Checkpoint synchronization | The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before st... | #C | C | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <omp.h>
int main()
{
int jobs = 41, tid;
omp_set_num_threads(5);
#pragma omp parallel shared(jobs) private(tid)
{
tid = omp_get_thread_num();
while (jobs > 0) {
... |
http://rosettacode.org/wiki/Collections | Collections | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Collections are abstractions to represent sets of values.
In statically-typed languages, the values are typically of a common data type.
Task
Create a collection, and add a fe... | #Elena | Elena |
// Weak array
var stringArr := Array.allocate(5);
stringArr[0] := "string";
// initialized array
var intArray := new int[]{1, 2, 3, 4, 5};
|
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
... | #Kotlin | Kotlin | class Combinations(val m: Int, val n: Int) {
private val combination = IntArray(m)
init {
generate(0)
}
private fun generate(k: Int) {
if (k >= m) {
for (i in 0 until m) print("${combination[i]} ")
println()
}
else {
for (j in 0 unt... |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include ... | #Prolog | Prolog | go :- write('Hello, World!'), nl. |
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Zoea | Zoea |
program comments # this program does nothing
# zoea supports single line comments starting with a '#' char
/*
zoea also supports
multi line
comments
*/
|
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #Zoea_Visual | Zoea Visual |
(* this is a comment *)
(*
and this is a
multiline comment
(* with a nested comment *)
*)
|
http://rosettacode.org/wiki/Comments | Comments | Task
Show all ways to include text in a language source file
that's completely ignored by the compiler or interpreter.
Related tasks
Documentation
Here_document
See also
Wikipedia
xkcd (Humor: hand gesture denoting // for "commenting out" people.)
| #zonnon | zonnon |
(* this is a comment *)
(*
and this is a
multiline comment
(* with a nested comment *)
*)
|
http://rosettacode.org/wiki/Chinese_remainder_theorem | Chinese remainder theorem | Suppose
n
1
{\displaystyle n_{1}}
,
n
2
{\displaystyle n_{2}}
,
…
{\displaystyle \ldots }
,
n
k
{\displaystyle n_{k}}
are positive integers that are pairwise co-prime.
Then, for any given sequence of integers
a
1
{\displaystyle a_{1}}
,
a
2
... | #Arturo | Arturo | mulInv: function [a0, b0][
[a b x0]: @[a0 b0 0]
result: 1
if b = 1 -> return result
while [a > 1][
q: a / b
a: a % b
tmp: a
a: b
b: tmp
result: result - q * x0
tmp: x0
x0: result
result: tmp
]
if result < 0 -> result: result... |
http://rosettacode.org/wiki/Chernick%27s_Carmichael_numbers | Chernick's Carmichael numbers | In 1939, Jack Chernick proved that, for n ≥ 3 and m ≥ 1:
U(n, m) = (6m + 1) * (12m + 1) * Product_{i=1..n-2} (2^i * 9m + 1)
is a Carmichael number if all the factors are primes and, for n > 4, m is a multiple of 2^(n-4).
Example
U(3, m) = (6m + 1) * (12m + 1) * (18m + 1)
U(4, m) = U(3, m) * (2^2 * 9m + 1)... | #Julia | Julia | using Primes
function trial_pretest(k::UInt64)
if ((k % 3)==0 || (k % 5)==0 || (k % 7)==0 || (k % 11)==0 ||
(k % 13)==0 || (k % 17)==0 || (k % 19)==0 || (k % 23)==0)
return (k <= 23)
end
return true
end
function gcd_pretest(k::UInt64)
if (k <= 107)
return true
en... |
http://rosettacode.org/wiki/Chernick%27s_Carmichael_numbers | Chernick's Carmichael numbers | In 1939, Jack Chernick proved that, for n ≥ 3 and m ≥ 1:
U(n, m) = (6m + 1) * (12m + 1) * Product_{i=1..n-2} (2^i * 9m + 1)
is a Carmichael number if all the factors are primes and, for n > 4, m is a multiple of 2^(n-4).
Example
U(3, m) = (6m + 1) * (12m + 1) * (18m + 1)
U(4, m) = U(3, m) * (2^2 * 9m + 1)... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[PrimeFactorCounts, U]
PrimeFactorCounts[n_Integer] := Total[FactorInteger[n][[All, 2]]]
U[n_, m_] := (6 m + 1) (12 m + 1) Product[2^i 9 m + 1, {i, 1, n - 2}]
FindFirstChernickCarmichaelNumber[n_Integer?Positive] :=
Module[{step, i, m, formula, value},
step = Ceiling[2^(n - 4)];
If[n > 5, step *= 5];
i ... |
http://rosettacode.org/wiki/Chernick%27s_Carmichael_numbers | Chernick's Carmichael numbers | In 1939, Jack Chernick proved that, for n ≥ 3 and m ≥ 1:
U(n, m) = (6m + 1) * (12m + 1) * Product_{i=1..n-2} (2^i * 9m + 1)
is a Carmichael number if all the factors are primes and, for n > 4, m is a multiple of 2^(n-4).
Example
U(3, m) = (6m + 1) * (12m + 1) * (18m + 1)
U(4, m) = U(3, m) * (2^2 * 9m + 1)... | #Nim | Nim | import strutils, sequtils
import bignum
const
Max = 10
Factors: array[3..Max, int] = [1, 1, 2, 4, 8, 16, 32, 64] # 1 for n=3 then 2^(n-4).
FirstPrimes = [3, 5, 7, 11, 13, 17, 19, 23]
#---------------------------------------------------------------------------------------------------
iterator factors(n, m:... |
http://rosettacode.org/wiki/Chowla_numbers | Chowla numbers | Chowla numbers are also known as:
Chowla's function
chowla numbers
the chowla function
the chowla number
the chowla sequence
The chowla number of n is (as defined by Chowla's function):
the sum of the divisors of n excluding unity and n
where n is a positive integer
The s... | #CLU | CLU | % Chowla's function
chowla = proc (n: int) returns (int)
sum: int := 0
i: int := 2
while i*i <= n do
if n//i = 0 then
sum := sum + i
j: int := n/i
if i ~= j then
sum := sum + j
end
end
i := i + 1
end
return(sum)
... |
http://rosettacode.org/wiki/Chowla_numbers | Chowla numbers | Chowla numbers are also known as:
Chowla's function
chowla numbers
the chowla function
the chowla number
the chowla sequence
The chowla number of n is (as defined by Chowla's function):
the sum of the divisors of n excluding unity and n
where n is a positive integer
The s... | #Cowgol | Cowgol | include "cowgol.coh";
sub chowla(n: uint32): (sum: uint32) is
sum := 0;
var i: uint32 := 2;
while i*i <= n loop
if n % i == 0 then
sum := sum + i;
var j := n / i;
if i != j then
sum := sum + j;
end if;
end if;
i := i... |
http://rosettacode.org/wiki/Church_numerals | Church numerals | Task
In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.
Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.
C... | #JavaScript | JavaScript | (() => {
'use strict';
// ----------------- CHURCH NUMERALS -----------------
const churchZero = f =>
identity;
const churchSucc = n =>
f => compose(f)(n(f));
const churchAdd = m =>
n => f => compose(n(f))(m(f));
const churchMult = m =>
n => f => n... |
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, a... | #DM | DM | s |
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, a... | #Dragon | Dragon | class run{
func val(){
showln 10+20
}
}
|
http://rosettacode.org/wiki/Cistercian_numerals | Cistercian numerals | Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999.
How they work
All Cistercian numerals begin with a vertical line segment, which by itself represents the number 0. Then, glyp... | #Raku | Raku | my @line-segments = (0, 0, 0, 100),
(0, 0, 35, 0), (0, 35, 35, 35), (0, 0, 35, 35), (0, 35, 35, 0), ( 35, 0, 35, 35),
(0, 0,-35, 0), (0, 35,-35, 35), (0, 0,-35, 35), (0, 35,-35, 0), (-35, 0,-35, 35),
(0,100, 35,100), (0, 65, 35, 65), (0,100, 35, 65), (0, 65, 35,100), ( 35, 65, 35,100),
(0,100,... |
http://rosettacode.org/wiki/Closest-pair_problem | Closest-pair problem |
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a function to find the closest two p... | #Go | Go | package main
import (
"fmt"
"math"
"math/rand"
"time"
)
type xy struct {
x, y float64
}
const n = 1000
const scale = 100.
func d(p1, p2 xy) float64 {
return math.Hypot(p2.x-p1.x, p2.y-p1.y)
}
func main() {
rand.Seed(time.Now().Unix())
points := make([]xy, n)
for i := range ... |
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of runnin... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | Function[i, i^2 &] /@ Range@10
->{1^2 &, 2^2 &, 3^2 &, 4^2 &, 5^2 &, 6^2 &, 7^2 &, 8^2 &, 9^2 &, 10^2 &}
%[[2]][]
->4 |
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of runnin... | #Nemerle | Nemerle | using System.Console;
module Closures
{
Main() : void
{
def f(x) { fun() { x ** 2 } }
def funcs = $[f(x) | x in $[0 .. 10]].ToArray(); // using array for easy indexing
WriteLine($"$(funcs[4]())");
WriteLine($"$(funcs[2]())");
}
} |
http://rosettacode.org/wiki/Circular_primes | Circular primes | Definitions
A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime.
For example:
1193 is a circular prime, since 1931, 9311 and 3119 are all also prime.
Note that a number which is a cyclic permutation ... | #Ring | Ring |
see "working..." + nl
see "First 19 circular numbers are:" + nl
n = 0
row = 0
Primes = []
while row < 19
n++
flag = 1
nStr = string(n)
lenStr = len(nStr)
for m = 1 to lenStr
leftStr = left(nStr,m)
rightStr = right(nStr,lenStr-m)
strOk = rightStr + leftSt... |
http://rosettacode.org/wiki/Circular_primes | Circular primes | Definitions
A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime.
For example:
1193 is a circular prime, since 1931, 9311 and 3119 are all also prime.
Note that a number which is a cyclic permutation ... | #Ruby | Ruby | require 'gmp'
require 'prime'
candidate_primes = Enumerator.new do |y|
DIGS = [1,3,7,9]
[2,3,5,7].each{|n| y << n.to_s}
(2..).each do |size|
DIGS.repeated_permutation(size) do |perm|
y << perm.join if (perm == min_rotation(perm)) && GMP::Z(perm.join).probab_prime? > 0
end
end
end
def min_rotatio... |
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points | Circles of given radius through two points |
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points.
Exceptions
r==0.0 should be treated as never describing circles (except in the case where the points are coincident).
If the points are coincident then an infinite number of circles with the point on thei... | #BASIC256 | BASIC256 |
function twoCircles(x1, y1, x2, y2, radio)
if x1 = x2 and y1 = y2 then #Si los puntos coinciden
if radio = 0 then #a no ser que radio=0
print "Los puntos son los mismos "
return ""
else
print "Hay cualquier número de círculos a través de un solo punto ("; x1; ", "; y1; ") de radio "; int(radio)
... |
http://rosettacode.org/wiki/Chinese_zodiac | Chinese zodiac | Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zo... | #AutoHotkey | AutoHotkey | Chinese_zodiac(year){
Animal := StrSplit("Rat,Ox,Tiger,Rabbit,Dragon,Snake,Horse,Goat,Monkey,Rooster,Dog,Pig", ",")
AnimalCh := StrSplit("鼠牛虎兔龍蛇馬羊猴鸡狗豬")
AnimalName := StrSplit("shǔ,niú,hǔ,tù,lóng,shé,mǎ,yáng,hóu,jī,gǒu,zhū", ",")
Element := StrSplit("Wood,Fire,Earth,Metal,Water", ",")
ElementCh := StrSplit("木火土... |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #C | C | #include <unistd.h> // for isatty()
#include <stdio.h> // for fileno()
int main()
{
puts(isatty(fileno(stdout))
? "stdout is tty"
: "stdout is not tty");
return 0;
} |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #C.23 | C# | using System;
namespace CheckTerminal {
class Program {
static void Main(string[] args) {
Console.WriteLine("Stdout is tty: {0}", Console.IsOutputRedirected);
}
}
} |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #C.2B.2B | C++ | #if _WIN32
#include <io.h>
#define ISATTY _isatty
#define FILENO _fileno
#else
#include <unistd.h>
#define ISATTY isatty
#define FILENO fileno
#endif
#include <iostream>
int main() {
if (ISATTY(FILENO(stdout))) {
std::cout << "stdout is a tty\n";
} else {
std::cout << "stdout is not a tty\n"... |
http://rosettacode.org/wiki/Cholesky_decomposition | Cholesky decomposition | Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose:
A
=
L
L
T
{\displaystyle A=LL^{T}}
L
{\displaystyle L}
is called the Cholesky factor of
A
{\displaystyle A}
, and can be interpreted as a generalized square r... | #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Cholesky
{
class Program
{
/// <summary>
/// This is example is written in C#, and compiles with .NET Framework 4.0
/// </summary>
/// <param name="args"></param>
static void... |
http://rosettacode.org/wiki/Check_input_device_is_a_terminal | Check input device is a terminal | Task
Demonstrate how to check whether the input device is a terminal or not.
Related task
Check output device is a terminal
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with Interfaces.C_Streams; use Interfaces.C_Streams;
procedure Test_tty is
begin
if Isatty(Fileno(Stdin)) = 0 then
Put_Line(Standard_Error, "stdin is not a tty.");
else
Put_Line(Standard_Error, "stdin is a tty.");
end if;
end Test_tty; |
http://rosettacode.org/wiki/Check_input_device_is_a_terminal | Check input device is a terminal | Task
Demonstrate how to check whether the input device is a terminal or not.
Related task
Check output device is a terminal
| #BaCon | BaCon | terminal = isatty(0)
PRINT terminal |
http://rosettacode.org/wiki/Check_input_device_is_a_terminal | Check input device is a terminal | Task
Demonstrate how to check whether the input device is a terminal or not.
Related task
Check output device is a terminal
| #C | C | #include <unistd.h> //for isatty()
#include <stdio.h> //for fileno()
int main(void)
{
puts(isatty(fileno(stdin))
? "stdin is tty"
: "stdin is not tty");
return 0;
} |
http://rosettacode.org/wiki/Cheryl%27s_birthday | Cheryl's birthday | Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.
Cheryl gave them a list of ten possible dates:
May 15, May 16, May 19
June 17, June 18
July 14, July 16
August 14, August 15, August 17
Cheryl then tells Albert the month of birth, ... | #AppleScript | AppleScript | use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
property M : 1 -- Month
property D : 2 -- Day
on run
-- The MONTH with only one remaining day
-- among the DAYs with unique months,
-- EXCLUDING months with unique days,
-- in Cheryl's list:
showList(uniquePairing... |
http://rosettacode.org/wiki/Checkpoint_synchronization | Checkpoint synchronization | The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before st... | #C.2B.2B | C++ | #include <iostream>
#include <chrono>
#include <atomic>
#include <mutex>
#include <random>
#include <thread>
std::mutex cout_lock;
class Latch
{
std::atomic<int> semafor;
public:
Latch(int limit) : semafor(limit) {}
void wait()
{
semafor.fetch_sub(1);
while(semafor.load() > 0)
... |
http://rosettacode.org/wiki/Collections | Collections | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Collections are abstractions to represent sets of values.
In statically-typed languages, the values are typically of a common data type.
Task
Create a collection, and add a fe... | #Elixir | Elixir | empty_list = []
list = [1,2,3,4,5]
length(list) #=> 5
[0 | list] #=> [0,1,2,3,4,5]
hd(list) #=> 1
tl(list) #=> [2,3,4,5]
Enum.at(list,3) #=> 4
list ++ [6,7] #=> [1,2,3,4,5,6,7]
list -- [4,2] ... |
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
... | #Lobster | Lobster | import std
// combi is an itertor that solves the Combinations problem for iota arrays as stated
def combi(m, n, f):
let c = map(n): _
while true:
f(c)
var i = n-1
c[i] = c[i] + 1
if c[i] > m - 1:
while c[i] >= m - n + i:
i -= 1
i... |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include ... | #PureBasic | PureBasic | If a = 0
Debug "a = 0"
ElseIf a > 0
Debug "a > 0"
Else
Debug "a < 0"
EndIf |
http://rosettacode.org/wiki/Chinese_remainder_theorem | Chinese remainder theorem | Suppose
n
1
{\displaystyle n_{1}}
,
n
2
{\displaystyle n_{2}}
,
…
{\displaystyle \ldots }
,
n
k
{\displaystyle n_{k}}
are positive integers that are pairwise co-prime.
Then, for any given sequence of integers
a
1
{\displaystyle a_{1}}
,
a
2
... | #AWK | AWK | # Usage: GAWK -f CHINESE_REMAINDER_THEOREM.AWK
BEGIN {
len = split("3 5 7", n)
len = split("2 3 2", a)
printf("%d\n", chineseremainder(n, a, len))
}
function chineseremainder(n, a, len, p, i, prod, sum) {
prod = 1
sum = 0
for (i = 1; i <= len; i++)
prod *= n[i]
for (i = 1; i <= le... |
http://rosettacode.org/wiki/Chernick%27s_Carmichael_numbers | Chernick's Carmichael numbers | In 1939, Jack Chernick proved that, for n ≥ 3 and m ≥ 1:
U(n, m) = (6m + 1) * (12m + 1) * Product_{i=1..n-2} (2^i * 9m + 1)
is a Carmichael number if all the factors are primes and, for n > 4, m is a multiple of 2^(n-4).
Example
U(3, m) = (6m + 1) * (12m + 1) * (18m + 1)
U(4, m) = U(3, m) * (2^2 * 9m + 1)... | #PARI.2FGP | PARI/GP |
cherCar(n)={
my(C=vector(n));C[1]=6; C[2]=12; for(g=3,n,C[g]=2^(g-2)*9);
my(i=1); my(N(g)=while(i<=n&ispseudoprime(g*C[i]+1),i=i+1); return(i>n));
i=1; my(G(g)=while(i<=n&isprime(g*C[i]+1),i=i+1); return(i>n));
i=1; if(n>4,i=2^(n-4)); if(n>5,i=i*5); my(m=i); while(!(N(m)&G(m)),m=m+i);
printf("cherCar(%d... |
http://rosettacode.org/wiki/Chowla_numbers | Chowla numbers | Chowla numbers are also known as:
Chowla's function
chowla numbers
the chowla function
the chowla number
the chowla sequence
The chowla number of n is (as defined by Chowla's function):
the sum of the divisors of n excluding unity and n
where n is a positive integer
The s... | #D | D | import std.stdio;
int chowla(int n) {
int sum;
for (int i = 2, j; i * i <= n; ++i) {
if (n % i == 0) {
sum += i + (i == (j = n / i) ? 0 : j);
}
}
return sum;
}
bool[] sieve(int limit) {
// True denotes composite, false denotes prime.
// Only interested in odd numb... |
http://rosettacode.org/wiki/Church_numerals | Church numerals | Task
In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.
Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.
C... | #jq | jq | def church(f; $x; $m):
if $m == 0 then .
elif $m == 1 then $x|f
else church(f; $x; $m - 1)
end; |
http://rosettacode.org/wiki/Church_numerals | Church numerals | Task
In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.
Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.
C... | #Julia | Julia |
id(x) = x -> x
zero() = x -> id(x)
add(m) = n -> (f -> (x -> n(f)(m(f)(x))))
mult(m) = n -> (f -> (x -> n(m(f))(x)))
exp(m) = n -> n(m)
succ(i::Int) = i + 1
succ(cn) = f -> (x -> f(cn(f)(x)))
church2int(cn) = cn(succ)(0)
int2church(n) = n < 0 ? throw("negative Church numeral") : (n == 0 ? zero() : succ(int2church(n -... |
http://rosettacode.org/wiki/Classes | Classes | In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T.
The first type T from the class T sometimes is called the root type of the class.
A class of types itself, a... | #DWScript | DWScript | type
TMyClass = class
private
FSomeField: Integer; // by convention, fields are usually private and exposed as properties
public
constructor Create;
begin
FSomeField := -1;
end;
procedure SomeMethod;
property SomeField: Integer read FSomeField write FSomeField;
end;
procedure TM... |
http://rosettacode.org/wiki/Cistercian_numerals | Cistercian numerals | Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999.
How they work
All Cistercian numerals begin with a vertical line segment, which by itself represents the number 0. Then, glyp... | #REXX | REXX | /*REXX program displays a (non-negative 4-digit) integer in Cistercian (monk) numerals.*/
parse arg m /*obtain optional arguments from the CL*/
if m='' | m="," then m= 0 1 20 300 4000 5555 6789 9393 /*Not specified? Use defaults.*/
$.=; nnn= words(m)
... |
http://rosettacode.org/wiki/Closest-pair_problem | Closest-pair problem |
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Provide a function to find the closest two p... | #Groovy | Groovy | class Point {
final Number x, y
Point(Number x = 0, Number y = 0) { this.x = x; this.y = y }
Number distance(Point that) { ((this.x - that.x)**2 + (this.y - that.y)**2)**0.5 }
String toString() { "{x:${x}, y:${y}}" }
} |
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of runnin... | #Nim | Nim | var funcs: seq[proc(): int] = @[]
for i in 0..9:
(proc =
let x = i
funcs.add(proc (): int = x * x))()
for i in 0..8:
echo "func[", i, "]: ", funcs[i]() |
http://rosettacode.org/wiki/Closures/Value_capture | Closures/Value capture | Task
Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index i (you may choose to start i from either 0 or 1), when run, should return the square of the index, that is, i 2.
Display the result of runnin... | #Objeck | Objeck | use Collection.Generic;
class Capture {
function : Main(args : String[]) ~ Nil {
funcs := Vector->New()<FuncHolder<IntHolder> >;
for(i := 0; i < 10; i += 1;) {
funcs->AddBack(FuncHolder->New(\() ~ IntHolder : () => i * i)<IntHolder>);
};
each(i : funcs) {
func := funcs->Get(i)-... |
http://rosettacode.org/wiki/Circular_primes | Circular primes | Definitions
A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime.
For example:
1193 is a circular prime, since 1931, 9311 and 3119 are all also prime.
Note that a number which is a cyclic permutation ... | #Rust | Rust | // [dependencies]
// rug = "1.8"
fn is_prime(n: u32) -> bool {
if n < 2 {
return false;
}
if n % 2 == 0 {
return n == 2;
}
if n % 3 == 0 {
return n == 3;
}
let mut p = 5;
while p * p <= n {
if n % p == 0 {
return false;
}
p +=... |
http://rosettacode.org/wiki/Circular_primes | Circular primes | Definitions
A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime.
For example:
1193 is a circular prime, since 1931, 9311 and 3119 are all also prime.
Note that a number which is a cyclic permutation ... | #Scala | Scala | object CircularPrimes {
def main(args: Array[String]): Unit = {
println("First 19 circular primes:")
var p = 2
var count = 0
while (count < 19) {
if (isCircularPrime(p)) {
if (count > 0) {
print(", ")
}
print(p)
count += 1
}
p += 1
}
... |
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points | Circles of given radius through two points |
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points.
Exceptions
r==0.0 should be treated as never describing circles (except in the case where the points are coincident).
If the points are coincident then an infinite number of circles with the point on thei... | #C | C | #include<stdio.h>
#include<math.h>
typedef struct{
double x,y;
}point;
double distance(point p1,point p2)
{
return sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));
}
void findCircles(point p1,point p2,double radius)
{
double separation = distance(p1,p2),mirrorDistance;
if(separation == 0.0)
{
radi... |
http://rosettacode.org/wiki/Chinese_zodiac | Chinese zodiac | Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zo... | #AWK | AWK |
# syntax: GAWK -f CHINESE_ZODIAC.AWK
BEGIN {
print("year element animal aspect")
split("Rat,Ox,Tiger,Rabbit,Dragon,Snake,Horse,Goat,Monkey,Rooster,Dog,Pig",animal_arr,",")
split("Wood,Fire,Earth,Metal,Water",element_arr,",")
n = split("1935,1938,1968,1972,1976,1984,1985,2017",year_arr,",")
for (i... |
http://rosettacode.org/wiki/Check_that_file_exists | Check that file exists | Task
Verify that a file called input.txt and a directory called docs exist.
This should be done twice:
once for the current working directory, and
once for a file and a directory in the filesystem root.
Optional criteria (May 2015): verify it works with:
zero-length files
an ... | #11l | 11l | fs:is_file(‘input.txt’)
fs:is_file(‘/input.txt’)
fs:is_dir(‘docs’)
fs:is_dir(‘/docs’) |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #COBOL | COBOL | *>
*> istty, check id fd 0 is a tty
*> Tectonics: cobc -xj istty.cob
*> echo "test" | ./istty
*>
identification division.
program-id. istty.
data division.
working-storage section.
01 rc usage binary-long.
procedure division.
... |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #Common_Lisp | Common Lisp | (with-open-stream (s *standard-output*)
(format T "stdout is~:[ not~;~] a terminal~%"
(interactive-stream-p s))) |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #Crystal | Crystal | File.new("testfile").tty? #=> false
File.new("/dev/tty").tty? #=> true
STDOUT.tty? #=> true |
http://rosettacode.org/wiki/Check_output_device_is_a_terminal | Check output device is a terminal | Task
Demonstrate how to check whether the output device is a terminal or not.
Related task
Check input device is a terminal
| #D | D | import std.stdio;
extern(C) int isatty(int);
void main() {
writeln("Stdout is tty: ", stdout.fileno.isatty == 1);
} |
http://rosettacode.org/wiki/Cholesky_decomposition | Cholesky decomposition | Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose:
A
=
L
L
T
{\displaystyle A=LL^{T}}
L
{\displaystyle L}
is called the Cholesky factor of
A
{\displaystyle A}
, and can be interpreted as a generalized square r... | #C.2B.2B | C++ | #include <cassert>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <vector>
template <typename scalar_type> class matrix {
public:
matrix(size_t rows, size_t columns)
: rows_(rows), columns_(columns), elements_(rows * columns) {}
matrix(size_t rows, size_t columns, scalar_type value... |
http://rosettacode.org/wiki/Check_input_device_is_a_terminal | Check input device is a terminal | Task
Demonstrate how to check whether the input device is a terminal or not.
Related task
Check output device is a terminal
| #COBOL | COBOL | *>
*> istty, check id fd 0 is a tty
*> Tectonics: cobc -xj istty.cob
*> echo "test" | ./istty
*>
identification division.
program-id. istty.
data division.
working-storage section.
01 rc usage binary-long.
procedure division.
... |
http://rosettacode.org/wiki/Check_input_device_is_a_terminal | Check input device is a terminal | Task
Demonstrate how to check whether the input device is a terminal or not.
Related task
Check output device is a terminal
| #Common_Lisp | Common Lisp | (with-open-stream (s *standard-input*)
(format T "stdin is~:[ not~;~] a terminal~%"
(interactive-stream-p s))) |
http://rosettacode.org/wiki/Check_input_device_is_a_terminal | Check input device is a terminal | Task
Demonstrate how to check whether the input device is a terminal or not.
Related task
Check output device is a terminal
| #Crystal | Crystal | File.new("testfile").tty? #=> false
File.new("/dev/tty").tty? #=> true
STDIN.tty? #=> true |
http://rosettacode.org/wiki/Check_input_device_is_a_terminal | Check input device is a terminal | Task
Demonstrate how to check whether the input device is a terminal or not.
Related task
Check output device is a terminal
| #D | D | import std.stdio;
extern(C) int isatty(int);
void main() {
if (isatty(0))
writeln("Input comes from tty.");
else
writeln("Input doesn't come from tty.");
} |
http://rosettacode.org/wiki/Cheryl%27s_birthday | Cheryl's birthday | Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.
Cheryl gave them a list of ten possible dates:
May 15, May 16, May 19
June 17, June 18
July 14, July 16
August 14, August 15, August 17
Cheryl then tells Albert the month of birth, ... | #Arturo | Arturo | dates: [
[May 15] [May 16] [May 19]
[June 17] [June 18]
[July 14] [July 16]
[August 14] [August 15] [August 17]
]
print ["possible dates:" dates]
print "\n(1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too."
print "\t-> meaning: the month cannot have a uniq... |
http://rosettacode.org/wiki/Checkpoint_synchronization | Checkpoint synchronization | The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before st... | #Clojure | Clojure | (ns checkpoint.core
(:gen-class)
(:require [clojure.core.async :as async :refer [go <! >! <!! >!! alts! close!]]
[clojure.string :as string]))
(defn coordinate [ctl-ch resp-ch combine]
(go
(<! (async/timeout 2000)) ;delay a bit to allow worker setup
(loop [members {}, received {}] ;maps by i... |
http://rosettacode.org/wiki/Collections | Collections | This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.
Collections are abstractions to represent sets of values.
In statically-typed languages, the values are typically of a common data type.
Task
Create a collection, and add a fe... | #Factor | Factor | USING: assocs deques dlists lists lists.lazy sequences sets ;
! ===fixed-size sequences===
{ 1 2 "foo" 3 } ! array
[ 1 2 3 + * ] ! quotation
"Hello, world!" ! string
B{ 1 2 3 } ! byte array
?{ f t t } ! bit array
! Add an element to a fixed-size sequence
{ 1 2 3 } 4 suffix ! { 1 2 3 4 }
! Append a seq... |
http://rosettacode.org/wiki/Combinations | Combinations | Task
Given non-negative integers m and n, generate all size m combinations of the integers from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is sorted).
Example
3 comb 5 is:
0 1 2
0 1 3
0 1 4
0 2 3
0 2 4
0 3 4
1 2 3
1 2 4
1 3 4
2 3 4
... | #Logo | Logo | to comb :n :list
if :n = 0 [output [[]]]
if empty? :list [output []]
output sentence map [sentence first :list ?] comb :n-1 bf :list ~
comb :n bf :list
end
print comb 3 [0 1 2 3 4] |
http://rosettacode.org/wiki/Conditional_structures | Conditional structures | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Task
List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions.
Common conditional structures include ... | #Python | Python | if x == 0:
foo()
elif x == 1:
bar()
elif x == 2:
baz()
else:
boz() |
http://rosettacode.org/wiki/Chinese_remainder_theorem | Chinese remainder theorem | Suppose
n
1
{\displaystyle n_{1}}
,
n
2
{\displaystyle n_{2}}
,
…
{\displaystyle \ldots }
,
n
k
{\displaystyle n_{k}}
are positive integers that are pairwise co-prime.
Then, for any given sequence of integers
a
1
{\displaystyle a_{1}}
,
a
2
... | #Bracmat | Bracmat | ( ( mul-inv
= a b b0 q x0 x1
. !arg:(?a.?b:?b0)
& ( !b:1
| 0:?x0
& 1:?x1
& whl
' ( !a:>1
& (!b.mod$(!a.!b):?q.!x1+-1*!q*!x0.!x0)
: (?a.?b.?x0.?x1)
)
& ( !x1:<0&!b0+!x1
| !x1
)
... |
http://rosettacode.org/wiki/Chinese_remainder_theorem | Chinese remainder theorem | Suppose
n
1
{\displaystyle n_{1}}
,
n
2
{\displaystyle n_{2}}
,
…
{\displaystyle \ldots }
,
n
k
{\displaystyle n_{k}}
are positive integers that are pairwise co-prime.
Then, for any given sequence of integers
a
1
{\displaystyle a_{1}}
,
a
2
... | #C | C | #include <stdio.h>
// returns x where (a * x) % b == 1
int mul_inv(int a, int b)
{
int b0 = b, t, q;
int x0 = 0, x1 = 1;
if (b == 1) return 1;
while (a > 1) {
q = a / b;
t = b, b = a % b, a = t;
t = x0, x0 = x1 - q * x0, x1 = t;
}
if (x1 < 0) x1 += b0;
return x1;
}
int chinese_remainder(int *n, int *a,... |
http://rosettacode.org/wiki/Chernick%27s_Carmichael_numbers | Chernick's Carmichael numbers | In 1939, Jack Chernick proved that, for n ≥ 3 and m ≥ 1:
U(n, m) = (6m + 1) * (12m + 1) * Product_{i=1..n-2} (2^i * 9m + 1)
is a Carmichael number if all the factors are primes and, for n > 4, m is a multiple of 2^(n-4).
Example
U(3, m) = (6m + 1) * (12m + 1) * (18m + 1)
U(4, m) = U(3, m) * (2^2 * 9m + 1)... | #Perl | Perl | use 5.020;
use warnings;
use ntheory qw/:all/;
use experimental qw/signatures/;
sub chernick_carmichael_factors ($n, $m) {
(6*$m + 1, 12*$m + 1, (map { (1 << $_) * 9*$m + 1 } 1 .. $n-2));
}
sub chernick_carmichael_number ($n, $callback) {
my $multiplier = ($n > 4) ? (1 << ($n-4)) : 1;
for (my $m = 1... |
http://rosettacode.org/wiki/Chernick%27s_Carmichael_numbers | Chernick's Carmichael numbers | In 1939, Jack Chernick proved that, for n ≥ 3 and m ≥ 1:
U(n, m) = (6m + 1) * (12m + 1) * Product_{i=1..n-2} (2^i * 9m + 1)
is a Carmichael number if all the factors are primes and, for n > 4, m is a multiple of 2^(n-4).
Example
U(3, m) = (6m + 1) * (12m + 1) * (18m + 1)
U(4, m) = U(3, m) * (2^2 * 9m + 1)... | #Phix | Phix | with javascript_semantics
function chernick_carmichael_factors(integer n, m)
sequence res = {6*m + 1, 12*m + 1}
for i=1 to n-2 do
res &= power(2,i) * 9*m + 1
end for
return res
end function
include mpfr.e
mpz p = mpz_init()
function m_prime(atom a)
mpz_set_d(p,a)
return mpz_prime(p)
... |
http://rosettacode.org/wiki/Chowla_numbers | Chowla numbers | Chowla numbers are also known as:
Chowla's function
chowla numbers
the chowla function
the chowla number
the chowla sequence
The chowla number of n is (as defined by Chowla's function):
the sum of the divisors of n excluding unity and n
where n is a positive integer
The s... | #Delphi | Delphi | func chowla(n) {
var sum = 0
var i = 2
var j = 0
while i * i <= n {
if n % i == 0 {
j = n / i
var app = if i == j {
0
} else {
j
}
sum += i + app
}
i += 1
}
return sum
}
func sie... |
http://rosettacode.org/wiki/Chowla_numbers | Chowla numbers | Chowla numbers are also known as:
Chowla's function
chowla numbers
the chowla function
the chowla number
the chowla sequence
The chowla number of n is (as defined by Chowla's function):
the sum of the divisors of n excluding unity and n
where n is a positive integer
The s... | #Dyalect | Dyalect | func chowla(n) {
var sum = 0
var i = 2
var j = 0
while i * i <= n {
if n % i == 0 {
j = n / i
var app = if i == j {
0
} else {
j
}
sum += i + app
}
i += 1
}
return sum
}
func sie... |
http://rosettacode.org/wiki/Church_numerals | Church numerals | Task
In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument.
Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all.
C... | #Lambdatalk | Lambdatalk |
{def succ {lambda {:n :f :x} {:f {:n :f :x}}}}
{def add {lambda {:n :m :f :x} {{:n :f} {:m :f :x}}}}
{def mul {lambda {:n :m :f} {:m {:n :f}}}}
{def power {lambda {:n :m} {:m :n}}}
{def church {lambda {:n} {{:n {+ {lambda {:x} {+ :x 1}}}} 0}}}
{def zero {lambda {:f :x} :x}}
{def three {succ {succ {succ zero}}}}... |
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.