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/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using onl... | #Ruby | Ruby | def catalan(num)
t = [0, 1] #grows as needed
(1..num).map do |i|
i.downto(1){|j| t[j] += t[j-1]}
t[i+1] = t[i]
(i+1).downto(1) {|j| t[j] += t[j-1]}
t[i+1] - t[i]
end
end
p catalan(15) |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using onl... | #Run_BASIC | Run BASIC | n = 15
dim t(n+2)
t(1) = 1
for i = 1 to n
for j = i to 1 step -1 : t(j) = t(j) + t(j-1): next j
t(i+1) = t(i)
for j = i+1 to 1 step -1: t(j) = t(j) + t(j-1 : next j
print t(i+1) - t(i);" ";
next i |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language... | #PARI.2FGP | PARI/GP | dog="Benjamin";
Dog="Samba";
DOG="Bernie";
printf("The three dogs are named %s, %s, and %s.", dog, Dog, DOG) |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language... | #Pascal | Pascal | # These variables are all different
$dog='Benjamin';
$Dog='Samba';
$DOG='Bernie';
print "The three dogs are named $dog, $Dog, and $DOG \n" |
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists | Cartesian product of two or more lists | Task
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.
Demonstrate that your function/method correctly returns:
{1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}
and, in contrast:
{3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}
Also demonstrate, using y... | #Kotlin | Kotlin | // version 1.1.2
fun flattenList(nestList: List<Any>): List<Any> {
val flatList = mutableListOf<Any>()
fun flatten(list: List<Any>) {
for (e in list) {
if (e !is List<*>)
flatList.add(e)
else
@Suppress("UNCHECKED_CAST")
flatten(... |
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C... | #Crystal | Crystal | require "big"
require "benchmark"
def factorial(n : BigInt) : BigInt
(1..n).product(1.to_big_i)
end
def factorial(n : Int32 | Int64)
factorial n.to_big_i
end
# direct
def catalan_direct(n)
factorial(2*n) / (factorial(n + 1) * factorial(n))
end
# recursive
def catalan_rec1(n)
return 1 if n == 0
(0.... |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance m... | #LFE | LFE | (defmodule aquarium
(export all))
(defun fish-class (species)
"
This is the constructor that will be used most often, only requiring that
one pass a 'species' string.
When the children are not defined, simply use an empty list.
"
(fish-class species ()))
(defun fish-class (species children)
"
Thi... |
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library | Call a function in a shared library | Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.
This is a special case of calling a foreign language function where the focus is c... | #Kotlin | Kotlin | #include <stdio.h>
/* gcc -shared -fPIC -nostartfiles fakeimglib.c -o fakeimglib.so */
int openimage(const char *s)
{
static int handle = 100;
fprintf(stderr, "opening %s\n", s);
return handle++;
} |
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library | Call a function in a shared library | Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.
This is a special case of calling a foreign language function where the focus is c... | #Lingo | Lingo | -- calculate CRC-32 checksum
str = "The quick brown fox jumps over the lazy dog"
-- is shared library (in Director called "Xtra", a DLL in windows, a sharedLib in
-- OS X) available?
if ilk(xtra("Crypto"))=#xtra then
-- use shared library
cx = xtra("Crypto").new()
crc = cx.cx_crc32_string(str)
else
-- o... |
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #ALGOL_68 | ALGOL 68 | BEGIN
# calculate an approximation to e #
LONG REAL epsilon = 1.0e-15;
LONG INT fact := 1;
LONG REAL e := 2;
LONG INT n := 2;
WHILE
LONG REAL e0 = e;
fact *:= n;
n +:= 1;
e +:= 1.0 / fact;
ABS ( e - e0 ) >= epsilon
DO SKIP OD;
p... |
http://rosettacode.org/wiki/Call_a_foreign-language_function | Call a foreign-language function | Task
Show how a foreign language function can be called from the language.
As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the... | #C.2B.2B | C++ | FUNCTION MULTIPLY(X, Y)
DOUBLE PRECISION MULTIPLY, X, Y |
http://rosettacode.org/wiki/Call_a_foreign-language_function | Call a foreign-language function | Task
Show how a foreign language function can be called from the language.
As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the... | #Clojure | Clojure | (JNIDemo/callStrdup "Hello World!") |
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
C... | #ALGOL_68 | ALGOL 68 | # Note functions and subroutines are called procedures (or PROCs) in Algol 68 #
# A function called without arguments: #
f;
# Algol 68 does not expect an empty parameter list for calls with no arguments, "f()" is a syntax error #
# A function with a fixed number of arguments: #
f(1, x);
# variable number of arguments... |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #FreeBASIC | FreeBASIC |
Const ancho = 81
Const alto = 5
Dim Shared intervalo(alto, ancho) As String
Dim As Integer i, j
Sub Cantor()
Dim As Integer i, j
For i = 0 To alto - 1
For j = 0 To ancho - 1
intervalo(i, j) = Chr(254)
Next j
Next i
End Sub
Sub ConjCantor(inicio As Integer, longitud As Integ... |
http://rosettacode.org/wiki/Calkin-Wilf_sequence | Calkin-Wilf sequence | The Calkin-Wilf sequence contains every nonnegative rational number exactly once.
It can be calculated recursively as follows:
a1 = 1
an+1 = 1/(2⌊an⌋+1-an) for n > 1
Task part 1
Show on this page terms 1 through 20 of the Calkin-Wilf sequence.
To avoid floating point error, you may want to ... | #Little_Man_Computer | Little Man Computer |
// Little Man Computer, for Rosetta Code.
// Displays terms of Calkin-Wilf sequence up to the given index.
// The chosen algorithm calculates the i-th term directly from i
// (i.e. not using any previous terms).
input INP // get number of terms from user
BRZ exit // exit if 0
STA max_i ... |
http://rosettacode.org/wiki/Calkin-Wilf_sequence | Calkin-Wilf sequence | The Calkin-Wilf sequence contains every nonnegative rational number exactly once.
It can be calculated recursively as follows:
a1 = 1
an+1 = 1/(2⌊an⌋+1-an) for n > 1
Task part 1
Show on this page terms 1 through 20 of the Calkin-Wilf sequence.
To avoid floating point error, you may want to ... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[a]
a[1] = 1;
a[n_?(GreaterThan[1])] := a[n] = 1/(2 Floor[a[n - 1]] + 1 - a[n - 1])
a /@ Range[20]
ClearAll[a]
a = 1;
n = 1;
Dynamic[n]
done = False;
While[! done,
a = 1/(2 Floor[a] + 1 - a);
n++;
If[a == 83116/51639,
Print[n];
Break[];
]
] |
http://rosettacode.org/wiki/Casting_out_nines | Casting out nines | Task (in three parts)
Part 1
Write a procedure (say
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
) which implements Casting Out Nines as described by returning the checksum for
x
{\displaystyle x}
. Demonstrate the procedure using the examples given there, or others you may consider lucky.
Par... | #Phix | Phix | with javascript_semantics
procedure co9(integer start, integer base, integer lim, sequence kaprekars)
integer c1=0,
c2=0
sequence s = {}
for k=start to lim do
c1 += 1
if mod(k,base-1)=mod(k*k,base-1) then
c2 += 1
s &= k
end if
end for
strin... |
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes | Carmichael 3 strong pseudoprimes | A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it.
The Miller Rabin Test uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this.
The purpose of this task is to investigate such numbers using a met... | #PARI.2FGP | PARI/GP | f(p)={
my(v=List(),q,r);
for(h=2,p-1,
for(d=1,h+p-1,
if((h+p)*(p-1)%d==0 && Mod(p,h)^2==-d && isprime(q=(p-1)*(h+p)/d+1) && isprime(r=p*q\h+1)&&q*r%(p-1)==1,
listput(v,p*q*r)
)
)
);
Set(v)
};
forprime(p=3,67,v=f(p); for(i=1,#v,print1(v[i]", "))) |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: ... | #J | J | / |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: ... | #Java | Java | import java.util.stream.Stream;
public class ReduceTask {
public static void main(String[] args) {
System.out.println(Stream.of(1, 2, 3, 4, 5).mapToInt(i -> i).sum());
System.out.println(Stream.of(1, 2, 3, 4, 5).reduce(1, (a, b) -> a * b));
}
} |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using onl... | #Rust | Rust |
fn main()
{let n=15usize;
let mut t= [0; 17];
t[1]=1;
let mut j:usize;
for i in 1..n+1
{
j=i;
loop{
if j==1{
break;
}
t[j]=t[j] + t[j-1];
j=j-1;
}
t[i+1]= t[i];
j=i+1;
loop{
if j==1{
break;
}
t[j]=t[j] + t[j-1];
j=j-1;
}
print!("{} ", t[i+1]-t[i]);
}
}
|
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using onl... | #Scala | Scala | def catalan(n: Int): Int =
if (n <= 1) 1
else (0 until n).map(i => catalan(i) * catalan(n - i - 1)).sum
(1 to 15).map(catalan(_)) |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language... | #Perl | Perl | # These variables are all different
$dog='Benjamin';
$Dog='Samba';
$DOG='Bernie';
print "The three dogs are named $dog, $Dog, and $DOG \n" |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language... | #Phix | Phix | sequence dog = "Benjamin",
Dog = "Samba",
DOG = "Bernie"
printf( 1, "The three dogs are named %s, %s and %s\n", {dog, Dog, DOG} )
|
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists | Cartesian product of two or more lists | Task
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.
Demonstrate that your function/method correctly returns:
{1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}
and, in contrast:
{3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}
Also demonstrate, using y... | #langur | langur | writeln X([1, 2], [3, 4]) == [[1, 3], [1, 4], [2, 3], [2, 4]]
writeln X([3, 4], [1, 2]) == [[3, 1], [3, 2], [4, 1], [4, 2]]
writeln X([1, 2], []) == []
writeln X([], [1, 2]) == []
writeln()
writeln X [1776, 1789], [7, 12], [4, 14, 23], [0, 1]
writeln()
writeln X [1, 2, 3], [30], [500, 100]
writeln()
writeln X [1,... |
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C... | #D | D | import std.stdio, std.algorithm, std.bigint, std.functional, std.range;
auto product(R)(R r) { return reduce!q{a * b}(1.BigInt, r); }
const cats1 = sequence!((a, n) => iota(n+2, 2*n+1).product / iota(1, n+1).product)(1);
BigInt cats2a(in uint n) {
alias mcats2a = memoize!cats2a;
if (n == 0) return 1.BigIn... |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance m... | #Lingo | Lingo | -- call static method
script("MyClass").foo()
-- call instance method
obj = script("MyClass").new()
obj.foo() |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance m... | #Logtalk | Logtalk |
% avoid infinite metaclass regression by
% making the metaclass an instance of itself
:- object(metaclass,
instantiates(metaclass)).
:- public(me/1).
me(Me) :-
self(Me).
:- end_object.
|
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance m... | #Lua | Lua | local object = { name = "foo", func = function (self) print(self.name) end }
object:func() -- with : sugar
object.func(object) -- without : sugar |
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library | Call a function in a shared library | Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.
This is a special case of calling a foreign language function where the focus is c... | #Lua | Lua | alien = require("alien")
msgbox = alien.User32.MessageBoxA
msgbox:types({ ret='long', abi='stdcall', 'long', 'string', 'string', 'long' })
retval = msgbox(0, 'Please press Yes, No or Cancel', 'The Title', 3)
print(retval) --> 6, 7 or 2 |
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library | Call a function in a shared library | Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.
This is a special case of calling a foreign language function where the focus is c... | #Maple | Maple | > cfloor := define_external( floor, s::float[8], RETURN::float[8], LIB = "libm.so" ):
> cfloor( 2.3 );
2. |
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #AppleScript | AppleScript | --------------- CALCULATING THE VALUE OF E ----------------
on run
sum(map(inverse, ¬
scanl(product, 1, enumFromTo(1, 16))))
--> 2.718281828459
end run
-- inverse :: Float -> Float
on inverse(x)
1 / x
end inverse
-- product :: Float -> Float -> Float
on product(a, b)
a * b
end product
... |
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers | Calendar - for "REAL" programmers | Task
Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented entirely without lowercase.
Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide.
(Hint: manually convert the code from the Calendar task to al... | #360_Assembly | 360 Assembly | * CALENDAR FOR REAL PROGRAMMERS 05/03/2017
CALENDAR CSECT
USING CALENDAR,R13 BASE REGISTER
B 72(R15) SKIP MY SAVEAREA
DC 17F'0' MY SAVEAREA
STM R14,R12,12(R13) SAVE CALLER'S REGISTERS
ST R13,4(R15) LINK BACK... |
http://rosettacode.org/wiki/Call_a_foreign-language_function | Call a foreign-language function | Task
Show how a foreign language function can be called from the language.
As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the... | #CMake | CMake | cmake_minimum_required(VERSION 2.6)
project("outer project" C)
# Compile cmDIV.
try_compile(
compiled_div # result variable
${CMAKE_BINARY_DIR}/div # bindir
${CMAKE_SOURCE_DIR}/div # srcDir
div) # projectName
if(NOT compiled_div)
message(FATAL_ERROR "Fai... |
http://rosettacode.org/wiki/Call_a_foreign-language_function | Call a foreign-language function | Task
Show how a foreign language function can be called from the language.
As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the... | #COBOL | COBOL | identification division.
program-id. foreign.
data division.
working-storage section.
01 hello.
05 value z"Hello, world".
01 duplicate usage pointer.
01 buffer pic x(16) based.
01 storage pic x(16).
procedure division.
cal... |
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
C... | #ALGOL_W | ALGOL W | % Note, in Algol W, functions are called procedures %
% calling a function with no parameters: %
f;
% calling a function with a fixed number of parameters %
g( 1, 2.3, "4" );
% Algol W does not support optional parameters in general, however constructors for records can %
% be called wither with parameters (one for... |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Go | Go | package main
import "fmt"
const (
width = 81
height = 5
)
var lines [height][width]byte
func init() {
for i := 0; i < height; i++ {
for j := 0; j < width; j++ {
lines[i][j] = '*'
}
}
}
func cantor(start, len, index int) {
seg := len / 3
if seg == 0 {
... |
http://rosettacode.org/wiki/Calkin-Wilf_sequence | Calkin-Wilf sequence | The Calkin-Wilf sequence contains every nonnegative rational number exactly once.
It can be calculated recursively as follows:
a1 = 1
an+1 = 1/(2⌊an⌋+1-an) for n > 1
Task part 1
Show on this page terms 1 through 20 of the Calkin-Wilf sequence.
To avoid floating point error, you may want to ... | #Nim | Nim | type Fraction = tuple[num, den: uint32]
iterator calkinWilf(): Fraction =
## Yield the successive values of the sequence.
var n, d = 1u32
yield (n, d)
while true:
n = 2 * (n div d) * d + d - n
swap n, d
yield (n, d)
proc `$`(fract: Fraction): string =
## Return the representation of a fraction... |
http://rosettacode.org/wiki/Calkin-Wilf_sequence | Calkin-Wilf sequence | The Calkin-Wilf sequence contains every nonnegative rational number exactly once.
It can be calculated recursively as follows:
a1 = 1
an+1 = 1/(2⌊an⌋+1-an) for n > 1
Task part 1
Show on this page terms 1 through 20 of the Calkin-Wilf sequence.
To avoid floating point error, you may want to ... | #Pascal | Pascal |
program CWTerms;
{-------------------------------------------------------------------------------
FreePascal command-line program.
Calculates the Calkin-Wilf sequence up to the specified maximum index,
where the first term 1/1 has index 1.
Command line format is: CWTerms <max_index>
The program demonstrates 3 a... |
http://rosettacode.org/wiki/Casting_out_nines | Casting out nines | Task (in three parts)
Part 1
Write a procedure (say
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
) which implements Casting Out Nines as described by returning the checksum for
x
{\displaystyle x}
. Demonstrate the procedure using the examples given there, or others you may consider lucky.
Par... | #Picat | Picat | go =>
Base10 = 10,
foreach(N in [2,6])
casting_out_nines(Base10,N)
end,
nl,
Base16 = 16,
foreach(N in [2,6])
casting_out_nines(Base16,N)
end,
nl.
casting_out_nines(Base,N) =>
println([base=Base,n=N]),
C1 = 0,
C2 = 0,
Ks = [],
LimitN = 3,
foreach(K in 1..Base**N-1)
C1 := C1 + ... |
http://rosettacode.org/wiki/Casting_out_nines | Casting out nines | Task (in three parts)
Part 1
Write a procedure (say
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
) which implements Casting Out Nines as described by returning the checksum for
x
{\displaystyle x}
. Demonstrate the procedure using the examples given there, or others you may consider lucky.
Par... | #PicoLisp | PicoLisp | (de kaprekar (N)
(let L (cons 0 (chop (* N N)))
(for ((I . R) (cdr L) R (cdr R))
(NIL (gt0 (format R)))
(T (= N (+ @ (format (head I L)))) N) ) ) )
(de co9 (N)
(until
(> 9
(setq N
(sum
'((N) (unless (= "9" N) (format N)))
(chop N) ... |
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes | Carmichael 3 strong pseudoprimes | A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it.
The Miller Rabin Test uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this.
The purpose of this task is to investigate such numbers using a met... | #Perl | Perl | use ntheory qw/forprimes is_prime vecprod/;
forprimes { my $p = $_;
for my $h3 (2 .. $p-1) {
my $ph3 = $p + $h3;
for my $d (1 .. $ph3-1) { # Jameseon procedure page 6
next if ((-$p*$p) % $h3) != ($d % $h3);
next if (($p-1)*$ph3) % $d;
my $q = 1 + ($p-1)*$ph3 / $... |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: ... | #JavaScript | JavaScript | var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function add(a, b) {
return a + b;
}
var summation = nums.reduce(add);
function mul(a, b) {
return a * b;
}
var product = nums.reduce(mul, 1);
var concatenation = nums.reduce(add, "");
console.log(summation, product, concatenation); |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using onl... | #Scilab | Scilab | n=15
t=zeros(1,n+2)
t(1)=1
for i=1:n
for j=i+1:-1:2
t(j)=t(j)+t(j-1)
end
t(i+1)=t(i)
for j=i+2:-1:2
t(j)=t(j)+t(j-1)
end
disp(t(i+1)-t(i))
end |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using onl... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: main is func
local
const integer: N is 15;
var array integer: t is [] (1) & N times 0;
var integer: i is 0;
var integer: j is 0;
begin
for i range 1 to N do
for j range i downto 2 do
t[j] +:= t[j - 1];
end for;
t[i + 1] := t[i];
... |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language... | #PicoLisp | PicoLisp | (let (dog "Benjamin" Dog "Samba" DOG "Bernie")
(prinl "The three dogs are named " dog ", " Dog " and " DOG) ) |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language... | #PL.2FI | PL/I | *process or(!) source xref attributes macro options;
/*********************************************************************
* Program to show that PL/I is case-insensitive
* 28.05.2013 Walter Pachl
*********************************************************************/
case: proc options(main);
Dcl dog Char(20) Va... |
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists | Cartesian product of two or more lists | Task
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.
Demonstrate that your function/method correctly returns:
{1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}
and, in contrast:
{3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}
Also demonstrate, using y... | #Lua | Lua | local pk,upk = table.pack, table.unpack
local getn = function(t)return #t end
local const = function(k)return function(e) return k end end
local function attachIdx(f)-- one-time-off function modifier
local idx = 0
return function(e)idx=idx+1 ; return f(e,idx)end
end
local function reduce(t,acc,f... |
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C... | #Delphi | Delphi | func catalan n . ans .
if n = 0
ans = 1
else
call catalan n - 1 h
ans = 2 * (2 * n - 1) * h div (1 + n)
.
.
for i range 15
call catalan i h
print h
. |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance m... | #M2000_Interpreter | M2000 Interpreter |
Module CheckIt {
\\ A class definition is a function which return a Group
\\ We can make groups and we can alter them using Group statement
\\ Groups may have other groups inside
Group Alfa {
Private:
myvalue=100
Public:
Group SetValue {
... |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance m... | #Maple | Maple | # Static
Method( obj, other, arg ); |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance m... | #MiniScript | MiniScript | Dog = {}
Dog.name = ""
Dog.help = function()
print "This class represents dogs."
end function
Dog.speak = function()
print self.name + " says Woof!"
end function
fido = new Dog
fido.name = "Fido"
Dog.help // calling a "class method"
fido.speak // calling an "instance method" |
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library | Call a function in a shared library | Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.
This is a special case of calling a foreign language function where the focus is c... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Needs["NETLink`"];
externalFloor = DefineDLLFunction["floor", "msvcrt.dll", "double", { "double" }];
externalFloor[4.2]
-> 4. |
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library | Call a function in a shared library | Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.
This is a special case of calling a foreign language function where the focus is c... | #Nim | Nim | proc openimage(s: cstring): cint {.importc, dynlib: "./fakeimglib.so".}
echo openimage("foo")
echo openimage("bar")
echo openimage("baz") |
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #Applesoft_BASIC | Applesoft BASIC | ?"E = "EXP(1) |
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #Arturo | Arturo | fact: 1
e: 2.0
e0: 0.0
n: 2
lim: 0.0000000000000010
while [lim =< abs e-e0][
e0: e
fact: fact * n
n: n + 1
e: e + 1.0 / fact
]
print e |
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers | Calendar - for "REAL" programmers | Task
Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented entirely without lowercase.
Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide.
(Hint: manually convert the code from the Calendar task to al... | #Ada | Ada | WITH PRINTABLE_CALENDAR;
PROCEDURE REAL_CAL IS
C: PRINTABLE_CALENDAR.CALENDAR := PRINTABLE_CALENDAR.INIT_132
((WEEKDAY_REP =>
"MO TU WE TH FR SA SO",
MONTH_REP =>
(" JANUARY ", " FEBRUARY ",
" MARCH ", " APRIL ",
... |
http://rosettacode.org/wiki/Call_a_foreign-language_function | Call a foreign-language function | Task
Show how a foreign language function can be called from the language.
As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the... | #Common_Lisp | Common Lisp | CL-USER> (let* ((string "Hello World!")
(c-string (cffi:foreign-funcall "strdup" :string string :pointer)))
(unwind-protect (write-line (cffi:foreign-string-to-lisp c-string))
(cffi:foreign-funcall "free" :pointer c-string :void))
(values))
Hello World!
; No value |
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
C... | #AntLang | AntLang | 2*2+9 |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Groovy | Groovy | class App {
private static final int WIDTH = 81
private static final int HEIGHT = 5
private static char[][] lines
static {
lines = new char[HEIGHT][WIDTH]
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
lines[i][j] = '*'
}
... |
http://rosettacode.org/wiki/Calkin-Wilf_sequence | Calkin-Wilf sequence | The Calkin-Wilf sequence contains every nonnegative rational number exactly once.
It can be calculated recursively as follows:
a1 = 1
an+1 = 1/(2⌊an⌋+1-an) for n > 1
Task part 1
Show on this page terms 1 through 20 of the Calkin-Wilf sequence.
To avoid floating point error, you may want to ... | #Perl | Perl | use strict;
use warnings;
use feature qw(say state);
use ntheory 'fromdigits';
use List::Lazy 'lazy_list';
use Math::AnyNum ':overload';
my $calkin_wilf = lazy_list { state @cw = 1; push @cw, 1 / ( (2 * int $cw[0]) + 1 - $cw[0] ); shift @cw };
sub r2cf {
my($num, $den) = @_;
my($n, @cf);
my $f = sub ... |
http://rosettacode.org/wiki/Casting_out_nines | Casting out nines | Task (in three parts)
Part 1
Write a procedure (say
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
) which implements Casting Out Nines as described by returning the checksum for
x
{\displaystyle x}
. Demonstrate the procedure using the examples given there, or others you may consider lucky.
Par... | #Python | Python | # Casting out Nines
#
# Nigel Galloway: June 27th., 2012,
#
def CastOut(Base=10, Start=1, End=999999):
ran = [y for y in range(Base-1) if y%(Base-1) == (y*y)%(Base-1)]
x,y = divmod(Start, Base-1)
while True:
for n in ran:
k = (Base-1)*x + n
if k < Start:
continue
if k > End:
... |
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes | Carmichael 3 strong pseudoprimes | A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it.
The Miller Rabin Test uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this.
The purpose of this task is to investigate such numbers using a met... | #Phix | Phix | with javascript_semantics
integer count = 0
for p1=1 to 61 do
if is_prime(p1) then
for h3=1 to p1 do
atom h3p1 = h3 + p1
for d=1 to h3p1-1 do
if mod(h3p1*(p1-1),d)=0
and mod(-(p1*p1),h3) = mod(d,h3) then
atom p2 := 1 + floor(((p1-1)... |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: ... | #jq | jq | def factorial: reduce range(2;.+1) as $i (1; . * $i);
|
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: ... | #Julia | Julia | println([reduce(op, 1:5) for op in [+, -, *]])
println([foldl(op, 1:5) for op in [+, -, *]])
println([foldr(op, 1:5) for op in [+, -, *]]) |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using onl... | #Sidef | Sidef | func catalan(num) {
var t = [0, 1]
(1..num).map { |i|
flip(^i ).each {|j| t[j+1] += t[j] }
t[i+1] = t[i]
flip(^i.inc).each {|j| t[j+1] += t[j] }
t[i+1] - t[i]
}
}
say catalan(15).join(' ') |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using onl... | #smart_BASIC | smart BASIC | PRINT "Catalan Numbers from Pascal's Triangle"!PRINT
x = 15
DIM t(x+2)
t(1) = 1
FOR n = 1 TO x
FOR m = n TO 1 STEP -1
t(m) = t(m) + t(m-1)
NEXT m
t(n+1) = t(n)
FOR m = n+1 TO 1 STEP -1
t(m) = t(m) + t(m-1)
NEXT m
PRINT n,"#######":t(n+1) - t(n)
NEXT n |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language... | #Plain_English | Plain English | To run:
Start up.
Put "Benjamin" into a DOG string.
Put "Samba" into the Dog string.
Put "Bernie" into the dog string.
Write "There is just one dog named " then the DOG on the console.
Wait for the escape key.
Shut down. |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language... | #PowerShell | PowerShell |
$dog = "Benjamin"
$Dog = "Samba"
$DOG = "Bernie"
"There is just one dog named {0}." -f $dOg
|
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language... | #Prolog | Prolog | three_dogs :-
DoG = 'Benjamin',
Dog = 'Samba',
DOG = 'Bernie',
format('The three dogs are named ~w, ~w and ~w.~n', [DoG, Dog, DOG]).
|
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists | Cartesian product of two or more lists | Task
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.
Demonstrate that your function/method correctly returns:
{1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}
and, in contrast:
{3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}
Also demonstrate, using y... | #Maple | Maple |
cartmulti := proc ()
local m, v;
if [] in {args} then
return [];
else
m := Iterator:-CartesianProduct(args);
for v in m do
printf("%{}a\n", v);
end do;
end if;
end proc;
|
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C... | #EasyLang | EasyLang | func catalan n . ans .
if n = 0
ans = 1
else
call catalan n - 1 h
ans = 2 * (2 * n - 1) * h div (1 + n)
.
.
for i range 15
call catalan i h
print h
. |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance m... | #Nanoquery | Nanoquery | class MyClass
declare static id = 5
declare MyName
// constructor
def MyClass(MyName)
this.MyName = MyName
end
// class method
def getName()
return this.MyName
end
// static method
def static getID()
return id
end
end
// call the static method
println MyClass.getID()
// instantiate a new MyCl... |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance m... | #Nemerle | Nemerle | // Static
MyClass.Method(someParameter);
// Instance
myInstance.Method(someParameter); |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance m... | #NetRexx | NetRexx | SomeClass.staticMethod() |
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library | Call a function in a shared library | Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.
This is a special case of calling a foreign language function where the focus is c... | #OCaml | OCaml | open Dlffi
let get_int = function Int v -> v | _ -> failwith "get_int"
let get_ptr = function Ptr v -> v | _ -> failwith "get_ptr"
let get_float = function Float v -> v | _ -> failwith "get_float"
let get_double = function Double v -> v | _ -> failwith "get_double"
let get_string = function String v -> v | _ -> failw... |
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #Asymptote | Asymptote | real n, n1;
real e1, e;
n = 1.0;
n1 = 1.0;
e1 = 0.0;
e = 1.0;
while (e != e1){
e1 = e;
e += (1.0 / n);
n1 += 1;
n *= n1;
}
write("The value of e = ", e); |
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers | Calendar - for "REAL" programmers | Task
Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented entirely without lowercase.
Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide.
(Hint: manually convert the code from the Calendar task to al... | #ALGOL_68 | ALGOL 68 | 'PR' QUOTE 'PR'
'PROC' PRINT CALENDAR = ('INT' YEAR, PAGE WIDTH)'VOID': 'BEGIN'
()'STRING' MONTH NAMES = (
"JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE",
"JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"),
WEEKDAY NAMES = ("SU","MO","TU","WE","TH","FR","SA");
'FORMAT' WEEKDAY FMT =... |
http://rosettacode.org/wiki/Call_a_foreign-language_function | Call a foreign-language function | Task
Show how a foreign language function can be called from the language.
As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the... | #Crystal | Crystal | @[Link("c")] # name of library that is passed to linker. Not needed as libc is linked by stdlib.
lib LibC
fun free(ptr : Void*) : Void
fun strdup(ptr : Char*) : Char*
end
s1 = "Hello World!"
p = LibC.strdup(s1) # returns Char* allocated by LibC
s2 = String.new(p)
LibC.free p # pointer can be freed as String.new(... |
http://rosettacode.org/wiki/Call_a_foreign-language_function | Call a foreign-language function | Task
Show how a foreign language function can be called from the language.
As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the... | #D | D | import std.stdio: writeln;
import std.string: toStringz;
import std.conv: to;
extern(C) {
char* strdup(in char* s1);
void free(void* ptr);
}
void main() {
// We could use char* here (as in D string literals are
// null-terminated) but we want to comply with the "of the
// string type typical to ... |
http://rosettacode.org/wiki/Call_a_function | Call a function | Task
Demonstrate the different syntax and semantics provided for calling a function.
This may include:
Calling a function that requires no arguments
Calling a function with a fixed number of arguments
Calling a function with optional arguments
Calling a function with a variable number of arguments
C... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program callfonct.s */
/* Constantes */
.equ STDOUT, 1
.equ WRITE, 4
.equ EXIT, 1
/***********************/
/* Initialized data */
/***********************/
.data
szMessage: .asciz "Hello. \n" @ message
szRetourLigne: .asciz "\n"
szMessResult: .ascii "Res... |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Haskell | Haskell | -------------------------- CANTOR ------------------------
cantor :: [(Bool, Int)] -> [(Bool, Int)]
cantor = concatMap go
where
go (bln, n)
| bln && 1 < n =
let m = quot n 3
in [(True, m), (False, m), (True, m)]
| otherwise = [(bln, n)]
--------------------------- TEST -------... |
http://rosettacode.org/wiki/Calkin-Wilf_sequence | Calkin-Wilf sequence | The Calkin-Wilf sequence contains every nonnegative rational number exactly once.
It can be calculated recursively as follows:
a1 = 1
an+1 = 1/(2⌊an⌋+1-an) for n > 1
Task part 1
Show on this page terms 1 through 20 of the Calkin-Wilf sequence.
To avoid floating point error, you may want to ... | #Phix | Phix | with javascript_semantics
requires("1.0.0") -- (new even() builtin)
function calkin_wilf(integer len)
sequence cw = repeat(0,len)
integer n=0, d=1
for i=1 to len do
{n,d} = {d,(floor(n/d)*2+1)*d-n}
cw[i] = {n,d}
end for
return cw
end function
function odd_length(sequence cf)
... |
http://rosettacode.org/wiki/Casting_out_nines | Casting out nines | Task (in three parts)
Part 1
Write a procedure (say
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
) which implements Casting Out Nines as described by returning the checksum for
x
{\displaystyle x}
. Demonstrate the procedure using the examples given there, or others you may consider lucky.
Par... | #Quackery | Quackery | [ true unrot swap
witheach
[ over find
over found not if
[ dip not
conclude ] ]
drop ] is subset ( [ [ --> [ )
[ abs 0 swap
[ 10 /mod rot +
dup 8 > if [ 9 - ]
swap dup 0 = until ]
drop ] is co9 ( n --> n )
sa... |
http://rosettacode.org/wiki/Casting_out_nines | Casting out nines | Task (in three parts)
Part 1
Write a procedure (say
c
o
9
(
x
)
{\displaystyle {\mathit {co9}}(x)}
) which implements Casting Out Nines as described by returning the checksum for
x
{\displaystyle x}
. Demonstrate the procedure using the examples given there, or others you may consider lucky.
Par... | #Racket | Racket | #lang racket
(require math)
(define (digits n)
(map (compose1 string->number string)
(string->list (number->string n))))
(define (cast-out-nines n)
(with-modulus 9
(for/fold ([sum 0]) ([d (digits n)])
(mod+ sum d)))) |
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes | Carmichael 3 strong pseudoprimes | A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it.
The Miller Rabin Test uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this.
The purpose of this task is to investigate such numbers using a met... | #PicoLisp | PicoLisp | (de modulo (X Y)
(% (+ Y (% X Y)) Y) )
(de prime? (N)
(let D 0
(or
(= N 2)
(and
(> N 1)
(bit? 1 N)
(for (D 3 T (+ D 2))
(T (> D (sqrt N)) T)
(T (=0 (% N D)) NIL) ) ) ) ) )
(for P1 61
(when (prime? P1)
(for (H3... |
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes | Carmichael 3 strong pseudoprimes | A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it.
The Miller Rabin Test uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this.
The purpose of this task is to investigate such numbers using a met... | #PL.2FI | PL/I | Carmichael: procedure options (main, reorder); /* 24 January 2014 */
declare (Prime1, Prime2, Prime3, h3, d) fixed binary (31);
put ('Carmichael numbers are:');
do Prime1 = 1 to 61;
do h3 = 2 to Prime1;
d_loop: do d = 1 to h3+Prime1-1;
if (mod((h3+Prime1)*(Prime1-1), d) = 0) &
... |
http://rosettacode.org/wiki/Catamorphism | Catamorphism | Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.
Task
Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.
See also
Wikipedia article: ... | #Kotlin | Kotlin | fun main(args: Array<String>) {
val a = intArrayOf(1, 2, 3, 4, 5)
println("Array : ${a.joinToString(", ")}")
println("Sum : ${a.reduce { x, y -> x + y }}")
println("Difference : ${a.reduce { x, y -> x - y }}")
println("Product : ${a.reduce { x, y -> x * y }}")
println("Minimum... |
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle | Catalan numbers/Pascal's triangle | Task
Print out the first 15 Catalan numbers by extracting them from Pascal's triangle.
See
Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.
Catalan's Triangle for a Number Triangle that generates Catalan Numbers using onl... | #Tcl | Tcl | proc catalan n {
set result {}
array set t {0 0 1 1}
for {set i 1} {[set k $i] <= $n} {incr i} {
for {set j $i} {$j > 1} {} {incr t($j) $t([incr j -1])}
set t([incr k]) $t($i)
for {set j $k} {$j > 1} {} {incr t($j) $t([incr j -1])}
lappend result [expr {$t($k) - $t($i)}]
}
return $result
}
put... |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language... | #PureBasic | PureBasic | dog$="Benjamin"
Dog$="Samba"
DOG$="Bernie"
Debug "There is just one dog named "+dog$ |
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers | Case-sensitivity of identifiers | Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output:
The three dogs are named Benjamin, Samba and Bernie.
For a language... | #Python | Python | >>> dog = 'Benjamin'; Dog = 'Samba'; DOG = 'Bernie'
>>> print ('The three dogs are named ',dog,', ',Dog,', and ',DOG)
The three dogs are named Benjamin , Samba , and Bernie
>>> |
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists | Cartesian product of two or more lists | Task
Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.
Demonstrate that your function/method correctly returns:
{1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}
and, in contrast:
{3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}
Also demonstrate, using y... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | cartesianProduct[args__] := Flatten[Outer[List, args], Length[{args}] - 1] |
http://rosettacode.org/wiki/Catalan_numbers | Catalan numbers | Catalan numbers
You are encouraged to solve this task according to the task description, using any language you may know.
Catalan numbers are a sequence of numbers which can be defined directly:
C
n
=
1
n
+
1
(
2
n
n
)
=
(
2
n
)
!
(
n
+
1
)
!
n
!
for
n
≥
0.
{\displaystyle C... | #EchoLisp | EchoLisp |
(lib 'sequences)
(lib 'bigint)
(lib 'math)
;; function definition
(define (C1 n) (/ (factorial (* n 2)) (factorial (1+ n)) (factorial n)))
(for ((i [1 .. 16])) (write (C1 i)))
→ 1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845
;; using a recursive procedure with memoization
(define (C2... |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance m... | #Nim | Nim | var x = @[1, 2, 3]
add(x, 4)
x.add(5) |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance m... | #OASYS_Assembler | OASYS Assembler | +&GO |
http://rosettacode.org/wiki/Call_an_object_method | Call an object method | In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class.
Show how to call a static or class method, and an instance m... | #Objeck | Objeck |
ClassName->some_function(); # call class function
instance->some_method(); # call instance method |
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library | Call a function in a shared library | Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.
This is a special case of calling a foreign language function where the focus is c... | #Ol | Ol |
(import (otus ffi))
(define self (load-dynamic-library #f))
(define strdup
(self type-string "strdup" type-string))
(print (strdup "Hello World!"))
|
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library | Call a function in a shared library | Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function.
This is a special case of calling a foreign language function where the focus is c... | #OxygenBasic | OxygenBasic |
'Loading a shared library at run time and calling a function.
declare MessageBox(sys hWnd, String text,caption, sys utype)
sys user32 = LoadLibrary "user32.dll"
if user32 then @Messagebox = getProcAddress user32,"MessageBoxA"
if @MessageBox then MessageBox 0,"Hello","OxygenBasic",0
'...
FreeLibrary user32... |
http://rosettacode.org/wiki/Burrows%E2%80%93Wheeler_transform | Burrows–Wheeler transform |
This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. 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)
The Burrows–Wheeler transform (BWT, also called block-s... | #11l | 11l | F bwt(String =s)
‘Apply Burrows-Wheeler transform to input string.’
assert("\002" !C s & "\003" !C s, ‘Input string cannot contain STX and ETX characters’)
s = "\002"s"\003"
V table = sorted((0 .< s.len).map(i -> @s[i..]‘’@s[0 .< i]))
V last_column = table.map(row -> row[(len)-1..])
R last_column.join... |
http://rosettacode.org/wiki/Calculating_the_value_of_e | Calculating the value of e | Task
Calculate the value of e.
(e is also known as Euler's number and Napier's constant.)
See details: Calculating the value of e
| #AWK | AWK |
# syntax: GAWK -f CALCULATING_THE_VALUE_OF_E.AWK
BEGIN {
epsilon = 1.0e-15
fact = 1
e = 2.0
n = 2
do {
e0 = e
fact *= n++
e += 1.0 / fact
} while (abs(e-e0) >= epsilon)
printf("e=%.15f\n",e)
exit(0)
}
function abs(x) { if (x >= 0) { return x } else { return -x } }
|
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.
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.