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/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... | #FreeBASIC | FreeBASIC |
' FB 1.05.0 Win64
Type MyType
Public:
Declare Sub InstanceMethod(s As String)
Declare Static Sub StaticMethod(s As String)
Private:
dummy_ As Integer ' types cannot be empty in FB
End Type
Sub MyType.InstanceMethod(s As String)
Print s
End Sub
Static Sub MyType.StaticMethod(s As String)
Prin... |
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... | #Delphi | Delphi | procedure DoSomething; external 'MYLIB.DLL'; |
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... | #Forth | Forth |
c-library math
s" m" add-lib
\c #include <math.h>
c-function gamma tgamma r -- r
end-c-library
|
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... | #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with Interfaces.C; use Interfaces.C;
with Interfaces.C.Strings; use Interfaces.C.Strings;
procedure Test_C_Interface is
function strdup (s1 : Char_Array) return Chars_Ptr;
pragma Import (C, strdup, "_strdup");
S1 : constant String := "Hello World!";
... |
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... | #Aikido | Aikido | #include <aikido.h>
extern "C" { // need C linkage
// define the function using a macro defined in aikido.h
AIKIDO_NATIVE(strdup) {
aikido::string *s = paras[0].str;
char *p = strdup (s->c_str());
aikido::string *result = new aikido::string(p);
free (p);
return result;
}
} |
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... | #68000_Assembly | 68000 Assembly | JSR myFunction |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #CLU | CLU | cantor = cluster is make
rep = null
ac = array[char]
aac = array[array[char]]
make = proc (width, height: int, ch: char) returns (string)
lines: aac := aac$fill_copy(0, height, ac$fill(0, width, ch))
cantor_step(lines, 0, width, 1)
s: stream := stream$create_output()
fo... |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. CANTOR.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 SETTINGS.
03 NUM-LINES PIC 9 VALUE 5.
03 FILL-CHAR PIC X VALUE '#'.
01 VARIABLES.
03 CUR-LINE.
05 CHAR PIC X OCCURS 81 TIMES.
... |
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 ... | #FreeBASIC | FreeBASIC | #include "gcd.bas"
type rational
num as integer
den as integer
end type
dim shared as rational ONE, TWO
ONE.num = 1 : ONE.den = 1
TWO.num = 2 : TWO.den = 1
function simplify( byval a as rational ) as rational
dim as uinteger g = gcd( a.num, a.den )
a.num /= g : a.den /= g
if a.den < 0 then
... |
http://rosettacode.org/wiki/Canny_edge_detector | Canny edge detector | Task
Write a program that performs so-called canny edge detection on an image.
A possible algorithm consists of the following steps:
Noise reduction. May be performed by Gaussian filter.
Compute intensity gradient (matrices
G
x
{\displaystyle G_{x}}
and
G
y
{\displaystyle G_{y}}
) ... | #Tcl | Tcl | package require crimp
package require crimp::pgm
proc readPGM {filename} {
set f [open $filename rb]
set data [read $f]
close $f
return [crimp read pgm $data]
}
proc writePGM {filename image} {
crimp write 2file pgm-raw $filename $image
}
proc cannyFilterFile {{inputFile "lena.pgm"} {outputFile ... |
http://rosettacode.org/wiki/Canny_edge_detector | Canny edge detector | Task
Write a program that performs so-called canny edge detection on an image.
A possible algorithm consists of the following steps:
Noise reduction. May be performed by Gaussian filter.
Compute intensity gradient (matrices
G
x
{\displaystyle G_{x}}
and
G
y
{\displaystyle G_{y}}
) ... | #Wren | Wren | import "dome" for Window
import "graphics" for Canvas, Color, ImageData
import "math" for Math
import "./check" for Check
var MaxBrightness = 255
class Canny {
construct new(inFile, outFile) {
Window.title = "Canny edge detection"
var image1 = ImageData.loadFromFile(inFile)
var w = image... |
http://rosettacode.org/wiki/Canonicalize_CIDR | Canonicalize CIDR | Task
Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form.
That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address.
Example
Given ... | #Python | Python | #!/usr/bin/env python
# canonicalize a CIDR block specification:
# make sure none of the host bits are set
import sys
from socket import inet_aton, inet_ntoa
from struct import pack, unpack
args = sys.argv[1:]
if len(args) == 0:
args = sys.stdin.readlines()
for cidr in args:
# IP in dotted-decimal / bits i... |
http://rosettacode.org/wiki/Canonicalize_CIDR | Canonicalize CIDR | Task
Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form.
That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address.
Example
Given ... | #Raku | Raku | #!/usr/bin/env raku
# canonicalize a CIDR block: make sure none of the host bits are set
if (!@*ARGS) {
@*ARGS = $*IN.lines;
}
for @*ARGS -> $cidr {
# dotted-decimal / bits in network part
my ($dotted, $size) = $cidr.split('/');
# get IP as binary string
my $binary = $dotted.split('.').map(*.fmt("%08... |
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... | #Lua | Lua | local N = 2
local base = 10
local c1 = 0
local c2 = 0
for k = 1, math.pow(base, N) - 1 do
c1 = c1 + 1
if k % (base - 1) == (k * k) % (base - 1) then
c2 = c2 + 1
io.write(k .. ' ')
end
end
print()
print(string.format("Trying %d numbers instead of %d numbers saves %f%%", c2, c1, 100.0 - 10... |
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... | #J | J |
q =: (,"0 1~ >:@i.@<:@+/"1)&.>@(,&.>"0 1~ >:@i.)&.>@I.@(1&p:@i.)@>:
f1 =: (0: = {. | <:@{: * 1&{ + {:) *. ((1&{ | -@*:@{:) = 1&{ | {.)
f2 =: 1: = <:@{. | ({: * 1&{)
p2 =: 0:`((* 1&p:)@(<.@(1: + <:@{: * {. %~ 1&{ + {:)))@.f1
p3 =: 3:$0:`((* 1&p:)@({: , {. , (<.@>:@(1&{ %~ {. * {:))))@.(*@{.)@(p2 , }.)
(-. 3:$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: ... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Type IntFunc As Function(As Integer, As Integer) As Integer
Function reduce(a() As Integer, f As IntFunc) As Integer
'' if array is empty or function pointer is null, return 0 say
If UBound(a) = -1 OrElse f = 0 Then Return 0
Dim result As Integer = a(LBound(a))
For i As Integer = LB... |
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... | #PureBasic | PureBasic | #MAXNUM = 15
Declare catalan()
If OpenConsole("Catalan numbers")
catalan()
Input()
End 0
Else
End -1
EndIf
Procedure catalan()
Define k.i, n.i, num.d, den.d, cat.d
Print("1 ")
For n=2 To #MAXNUM
num=1 : den =1
For k=2 To n
num * (n+k)
den * k
cat = num / den
Next
... |
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... | #Python | Python | >>> n = 15
>>> t = [0] * (n + 2)
>>> t[1] = 1
>>> for i in range(1, n + 1):
for j in range(i, 1, -1): t[j] += t[j - 1]
t[i + 1] = t[i]
for j in range(i + 1, 1, -1): t[j] += t[j - 1]
print(t[i+1] - t[i], end=' ')
1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845
>>> |
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... | #NESL | NESL | dog = "Benjamin";
Dog = "Samba";
DOG = "Bernie";
"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... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
dog = "Benjamin";
Dog = "Samba";
DOG = "Bernie";
if dog == Dog & Dog == DOG & dog == DOG then do
say 'There is just one dog named' dog'.'
end
else do
say 'The three dogs are named' dog',' Dog 'and' DOG'.'
end
return
|
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... | #Nim | Nim | var dog, Dog: string
(dog, Dog, DOG) = ("Benjamin", "Samba", "Bernie")
if dog == Dog:
if dog == DOG:
echo "There is only one dog, ", DOG)
else:
echo "There are two dogs: ", dog, " and ", DOG
elif Dog == DOG :
echo "There are two dogs: ", dog, " and ", DOG
else:
echo "There are three dogs: ", 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... | #Java | Java |
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Optional.of;
import static java.util.stream.Collectors.toList;
import java.util.List;
public class CartesianProduct {
public List<?> product(List<?>... a) {
if (a.length >= 2) {
... |
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... | #C.23 | C# | namespace CatalanNumbers
{
/// <summary>
/// Class that holds all options.
/// </summary>
public class CatalanNumberGenerator
{
private static double Factorial(double n)
{
if (n == 0)
return 1;
return n * Factorial(n - 1);
}
... |
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... | #Go | Go | type Foo int // some custom type
// method on the type itself; can be called on that type or its pointer
func (self Foo) ValueMethod(x int) { }
// method on the pointer to the type; can be called on pointers
func (self *Foo) PointerMethod(x int) { }
var myValue Foo
var myPointer *Foo = new(Foo)
// Calling val... |
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... | #Icon_and_Unicon | Icon and Unicon | procedure main()
bar := foo() # create instance
bar.m2() # call method m2 with self=bar, an implicit first parameter
foo_m1( , "param1", "param2") # equivalent of static class method, first (self) parameter is null
end
class foo(cp1,cp2)
method m1(m1p1,m1p2)
local ml1
static ms1
... |
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... | #Fortran | Fortran |
double add_n(double* a, double* b)
{
return *a + *b;
}
|
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... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
' Attempt to call Beep function in Win32 API
Dim As Any Ptr library = DyLibLoad("kernel32.dll") '' load dll
If library = 0 Then
Print "Unable to load kernel32.dll - calling built in Beep function instead"
Beep : Beep : Beep
Else
Dim beep_ As Function (ByVal As ULong, ByVal As ULong) As Long... |
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... | #ALGOL_68 | ALGOL 68 |
BEGIN
MODE PASSWD = STRUCT (STRING name, passwd, INT uid, gid, STRING gecos, dir, shell);
PROC getpwnam = (STRING name) PASSWD :
BEGIN
FILE c source;
create (c source, stand out channel);
putf (c source, ($gl$,
"#include <sys/types.h>",
"#include <pwd.h>",
"#include <stdio.h>",
"main ()",
"... |
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... | #8086_Assembly | 8086 Assembly | call foo |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #D | D | import std.stdio;
enum WIDTH = 81;
enum HEIGHT = 5;
char[WIDTH*HEIGHT] lines;
void cantor(int start, int len, int index) {
int seg = len / 3;
if (seg == 0) return;
for (int i=index; i<HEIGHT; i++) {
for (int j=start+seg; j<start+seg*2; j++) {
int pos = i*WIDTH + j;
line... |
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 ... | #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import (
"fmt"
"math"
"math/big"
"strconv"
"strings"
)
func calkinWilf(n int) []*big.Rat {
cw := make([]*big.Rat, n+1)
cw[0] = big.NewRat(1, 1)
one := big.NewRat(1, 1)
two := big.NewRat(2, 1)
for i := 1; i < n; i++ {
t := new(big.Rat).Set(cw[i-1])
... |
http://rosettacode.org/wiki/Canny_edge_detector | Canny edge detector | Task
Write a program that performs so-called canny edge detection on an image.
A possible algorithm consists of the following steps:
Noise reduction. May be performed by Gaussian filter.
Compute intensity gradient (matrices
G
x
{\displaystyle G_{x}}
and
G
y
{\displaystyle G_{y}}
) ... | #Yabasic | Yabasic | // Rosetta Code problem: http://rosettacode.org/wiki/Canny_edge_detector
// Adapted from Phix to Yabasic by Galileo, 01/2022
import ReadFromPPM2
MaxBrightness = 255
readPPM("Valve.ppm")
print "Be patient, please ..."
width = peek("winwidth")
height = peek("winheight")
dim pixels(width, height), C_E_D(3, 3)
da... |
http://rosettacode.org/wiki/Canonicalize_CIDR | Canonicalize CIDR | Task
Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form.
That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address.
Example
Given ... | #REXX | REXX | /*REXX pgm canonicalizes IPv4 addresses that are in CIDR notation (dotted─dec/network).*/
parse arg a . /*obtain optional argument from the CL.*/
if a=='' | a=="," then a= '87.70.141.1/22' , /*Not specified? Then use the defaults*/
'36.18.154.103/12' ... |
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... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Co9[n_, b_: 10] :=
With[{ans = FixedPoint[Total@IntegerDigits[#, b] &, n]},
If[ans == b - 1, 0, ans]]; |
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... | #Nim | Nim | import sequtils
iterator castOut(base = 10, start = 1, ending = 999_999): int =
var ran: seq[int] = @[]
for y in 0 ..< base-1:
if y mod (base - 1) == (y*y) mod (base - 1):
ran.add(y)
var x = start div (base - 1)
var y = start mod (base - 1)
block outer:
while true:
for n in ran:
... |
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... | #Java | Java | public class Test {
static int mod(int n, int m) {
return ((n % m) + m) % m;
}
static boolean isPrime(int n) {
if (n == 2 || n == 3)
return true;
else if (n < 2 || n % 2 == 0 || n % 3 == 0)
return false;
for (int div = 5, inc = 2; Math.pow(div, 2) ... |
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: ... | #Go | Go | package main
import (
"fmt"
)
func main() {
n := []int{1, 2, 3, 4, 5}
fmt.Println(reduce(add, n))
fmt.Println(reduce(sub, n))
fmt.Println(reduce(mul, n))
}
func add(a int, b int) int { return a + b }
func sub(a int, b int) int { return a - b }
func mul(a int, b int) int { return a * b }
func reduce(rf fu... |
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... | #Quackery | Quackery | [ [] 0 rot 0 join
witheach
[ tuck +
rot join swap ]
drop ] is nextline ( [ --> [ )
[ ' [ 1 ] swap times
[ nextline nextline
dup dup size 2 /
split nip
2 split drop
do - echo sp ]
drop ] is catalan ( n --> )
15 ca... |
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... | #Oberon-2 | Oberon-2 |
MODULE CaseSensitivity;
IMPORT
Out;
VAR
dog, Dog, DOG: STRING;
BEGIN
dog := "Benjamin";
Dog := "Samba";
DOG := "Bernie";
Out.Object("The three dogs are named " + dog + ", " + Dog + " and " + DOG);
Out.Ln
END CaseSensitivity.
|
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... | #JavaScript | JavaScript | (() => {
// CARTESIAN PRODUCT OF TWO LISTS ---------------------
// cartProd :: [a] -> [b] -> [[a, b]]
const cartProd = xs => ys =>
xs.flatMap(x => ys.map(y => [x, y]))
// TEST -----------------------------------------------
return [
cartProd([1, 2])([3, 4]),
cartProd([... |
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... | #C.2B.2B | C++ | #if !defined __ALGORITHMS_H__
#define __ALGORITHMS_H__
namespace rosetta
{
namespace catalanNumbers
{
namespace detail
{
class Factorial
{
public:
unsigned long long operator()(unsigned n)const;
};
class BinomialCoefficient
{
public:
... |
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... | #Haskell | Haskell | data Obj = Obj { field :: Int, method :: Int -> Int }
-- smart constructor
mkAdder :: Int -> Obj
mkAdder x = Obj x (+x)
-- adding method from a type class
instanse Show Obj where
show o = "Obj " ++ show (field o) |
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... | #J | J | methodName_className_ parameters |
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... | #Java | Java | ClassWithStaticMethod.staticMethodName(argument1, argument2);//for methods with no arguments, use empty parentheses |
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... | #Go | Go | #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... | #Haskell | Haskell | #!/usr/bin/env stack
-- stack --resolver lts-6.33 --install-ghc runghc --package unix
import Control.Exception ( try )
import Foreign ( FunPtr, allocaBytes )
import Foreign.C
( CSize(..), CString, withCAStringLen, peekCAStringLen )
import System.Info ( os )
import System.IO.Error ( ioeGetErrorString )
import Syst... |
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
| #11l | 11l | V e0 = 0.0
V e = 2.0
V n = 0
V fact = 1
L (e - e0 > 1e-15)
e0 = e
n++
fact *= 2 * n * (2 * n + 1)
e += (2.0 * n + 2) / fact
print(‘Computed e = ’e)
print(‘Real e = ’math:e)
print(‘Error = ’(math:e - e))
print(‘Number of iterations = ’n) |
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... | #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program forfunction.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/* Initialized data */
.data
szString: .asciz "Hello word\n"
/* UnInitialized data */
.bss
/* code section */
.t... |
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... | #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program callfonct.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM6... |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Delphi | Delphi |
program Cantor_set;
{$APPTYPE CONSOLE}
const
WIDTH: Integer = 81;
HEIGHT: Integer = 5;
var
Lines: TArray<TArray<Char>>;
procedure Init;
var
i, j: Integer;
begin
SetLength(lines, HEIGHT, WIDTH);
for i := 0 to HEIGHT - 1 do
for j := 0 to WIDTH - 1 do
lines[i, j] := '*';
end;
procedure Ca... |
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 ... | #Go | Go | package main
import (
"fmt"
"math"
"math/big"
"strconv"
"strings"
)
func calkinWilf(n int) []*big.Rat {
cw := make([]*big.Rat, n+1)
cw[0] = big.NewRat(1, 1)
one := big.NewRat(1, 1)
two := big.NewRat(2, 1)
for i := 1; i < n; i++ {
t := new(big.Rat).Set(cw[i-1])
... |
http://rosettacode.org/wiki/Canonicalize_CIDR | Canonicalize CIDR | Task
Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form.
That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address.
Example
Given ... | #Ruby | Ruby | #!/usr/bin/env ruby
# canonicalize a CIDR block: make sure none of the host bits are set
if ARGV.length == 0 then
ARGV = $stdin.readlines.map(&:chomp)
end
ARGV.each do |cidr|
# dotted-decimal / bits in network part
dotted, size_str = cidr.split('/')
size = size_str.to_i
# get IP as binary string
b... |
http://rosettacode.org/wiki/Canonicalize_CIDR | Canonicalize CIDR | Task
Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form.
That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address.
Example
Given ... | #Rust | Rust | use std::net::Ipv4Addr;
fn canonical_cidr(cidr: &str) -> Result<String, &str> {
let mut split = cidr.splitn(2, '/');
if let (Some(addr), Some(mask)) = (split.next(), split.next()) {
let addr = addr.parse::<Ipv4Addr>().map(u32::from).map_err(|_| cidr)?;
let mask = mask.parse::<u8>().map_err(|_|... |
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... | #Objeck | Objeck | class CastingNines {
function : Main(args : String[]) ~ Nil {
base := 10;
N := 2;
c1 := 0;
c2 := 0;
for (k:=1; k<base->As(Float)->Power(N->As(Float)); k+=1;){
c1+=1;
if (k%(base-1) = (k*k)%(base-1)){
c2+=1;
IO.Console->Print(k)->Print(" ");
};
};
IO.Co... |
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... | #Julia | Julia | using Primes
function carmichael(pmax::Integer)
if pmax ≤ 0 throw(DomainError("pmax must be strictly positive")) end
car = Vector{typeof(pmax)}(0)
for p in primes(pmax)
for h₃ in 2:(p-1)
m = (p - 1) * (h₃ + p)
pmh = mod(-p ^ 2, h₃)
for Δ in 1:(h₃+p-1)
... |
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... | #Kotlin | Kotlin | fun Int.isPrime(): Boolean {
return when {
this == 2 -> true
this <= 1 || this % 2 == 0 -> false
else -> {
val max = Math.sqrt(toDouble()).toInt()
(3..max step 2)
.filter { this % it == 0 }
.forEach { return false }
true
... |
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: ... | #Groovy | Groovy | def vector1 = [1,2,3,4,5,6,7]
def vector2 = [7,6,5,4,3,2,1]
def map1 = [a:1, b:2, c:3, d:4]
println vector1.inject { acc, val -> acc + val } // sum
println vector1.inject { acc, val -> acc + val*val } // sum of squares
println vector1.inject { acc, val -> acc * val } // product
println vector1.inject { ... |
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... | #Racket | Racket |
#lang racket
(define (next-half-row r)
(define r1 (for/list ([x r] [y (cdr r)]) (+ x y)))
`(,(* 2 (car r1)) ,@(for/list ([x r1] [y (cdr r1)]) (+ x y)) 1 0))
(let loop ([n 15] [r '(1 0)])
(cons (- (car r) (cadr r))
(if (zero? n) '() (loop (sub1 n) (next-half-row r)))))
;; -> '(1 1 2 5 14 42 132 429 1... |
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... | #Raku | Raku | constant @pascal = [1], -> @p { [0, |@p Z+ |@p, 0] } ... *;
constant @catalan = gather for 2, 4 ... * -> $ix {
my @row := @pascal[$ix];
my $mid = +@row div 2;
take [-] @row[$mid, $mid+1]
}
.say for @catalan[^20]; |
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... | #Objeck | Objeck | class Program {
function : Main(args : String[]) ~ Nil {
dog := "Benjamin";
Dog := "Samba";
DOG := "Bernie";
"The three dogs are named {$dog}, {$Dog}, and {$DOG}."->PrintLine();
}
} |
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... | #OCaml | OCaml | let () =
let dog = "Benjamin" in
let dOG = "Samba" in
let dOg = "Bernie" in
Printf.printf "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... | #jq | jq |
def products: .[0][] as $x | .[1][] as $y | [$x,$y];
|
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... | #Clojure | Clojure | (def ! (memoize #(apply * (range 1 (inc %)))))
(defn catalan-numbers-direct []
(map #(/ (! (* 2 %))
(* (! (inc %)) (! %))) (range)))
(def catalan-numbers-recursive
#(->> [1 1] ; [c0 n1]
(iterate (fn [[c n]]
[(* 2 (dec (* 2 n)) (/ (inc n)) c) (inc n)]) ,)
(map first ,)))
user> (take 15 (... |
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... | #JavaScript | JavaScript | x.y() |
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... | #Julia | Julia | module Animal
|
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... | #J | J | require 'dll'
strdup=: 'msvcrt.dll _strdup >x *' cd <
free=: 'msvcrt.dll free n x' cd <
getstr=: free ] memr@,&0 _1
DupStr=:verb define
try.
getstr@strdup y
catch.
y
end.
) |
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... | #Java | Java | /* TrySort.java */
import java.util.Collections;
import java.util.Random;
public class TrySort {
static boolean useC;
static {
try {
System.loadLibrary("TrySort");
useC = true;
} catch(UnsatisfiedLinkError e) {
useC = false;
}
}
static native void sortInC(int[] ary);
static... |
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
| #360_Assembly | 360 Assembly | * Calculating the value of e - 21/07/2018
CALCE PROLOG
LE F0,=E'0'
STE F0,EOLD eold=0
LE F2,=E'1' e=1
LER F4,F2 xi=1
LER F6,F2 facti=1
BWHILE CE F2,EOLD while e<>eold
BE E... |
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... | #Arturo | Arturo | // compile with:
// clang -c -w mylib.c
// clang -shared -o libmylib.dylib mylib.o
#include <stdio.h>
void sayHello(char* name){
printf("Hello %s!\n", name);
}
int doubleNum(int num){
return num * 2;
} |
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... | #AutoHotkey | AutoHotkey | ; Example: Calls the Windows API function "MessageBox" and report which button the user presses.
WhichButton := DllCall("MessageBox", "int", "0", "str", "Press Yes or No", "str", "Title of box", "int", 4)
MsgBox You pressed button #%WhichButton%. |
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... | #ActionScript | ActionScript | myfunction(); /* function with no arguments in statement context */
myfunction(6,b); // function with two arguments in statement context
stringit("apples"); //function with a string argument |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Excel | Excel | CANTOR
=LAMBDA(n,
APPLYN(n)(
LAMBDA(grid,
APPENDROWS(grid)(
CANTOROW(
LASTROW(grid)
)
)
)
)({0,1})
)
CANTOROW
=LAMBDA(xys,
LET(
nCols, COLUMNS(xys),
IF(2 > nCols,
xys,
IF... |
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 ... | #Haskell | Haskell | import Control.Monad (forM_)
import Data.Bool (bool)
import Data.List.NonEmpty (NonEmpty, fromList, toList, unfoldr)
import Text.Printf (printf)
-- The infinite Calkin-Wilf sequence, a(n), starting with a(1) = 1.
calkinWilfs :: [Rational]
calkinWilfs = iterate (recip . succ . ((-) =<< (2 *) . fromIntegral . floor)) 1... |
http://rosettacode.org/wiki/Canonicalize_CIDR | Canonicalize CIDR | Task
Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form.
That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address.
Example
Given ... | #Wren | Wren | import "/fmt" for Fmt, Conv
import "/str" for Str
// canonicalize a CIDR block: make sure none of the host bits are set
var canonicalize = Fn.new { |cidr|
// dotted-decimal / bits in network part
var split = cidr.split("/")
var dotted = split[0]
var size = Num.fromString(split[1])
// get IP as b... |
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... | #PARI.2FGP | PARI/GP | {base=10;
N=2;
c1=c2=0;
for(k=1,base^N-1,
c1++;
if (k%(base-1) == k^2%(base-1),
c2++;
print1(k" ")
);
);
print("\nTrying "c2" numbers instead of "c1" numbers saves " 100.-(c2/c1)*100 "%")}
|
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... | #Lua | Lua | local function isprime(n)
if n < 2 then return false end
if n % 2 == 0 then return n==2 end
if n % 3 == 0 then return n==3 end
local f, limit = 5, math.sqrt(n)
while (f <= limit) do
if n % f == 0 then return false end; f=f+2
if n % f == 0 then return false end; f=f+4
end
return true
end
local fu... |
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: ... | #Haskell | Haskell | main :: IO ()
main =
putStrLn . unlines $
[ show . foldr (+) 0 -- sum
, show . foldr (*) 1 -- product
, foldr ((++) . show) "" -- concatenation
] <*>
[[1 .. 10]] |
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... | #REXX | REXX | /*REXX program obtains and displays Catalan numbers from a Pascal's triangle. */
parse arg N . /*Obtain the optional argument from CL.*/
if N=='' | N=="," then N=15 /*Not specified? Then use the default.*/
numeric digits max(9, N%2 + N%8) ... |
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... | #Ring | Ring |
n=15
cat = list(n+2)
cat[1]=1
for i=1 to n
for j=i+1 to 2 step -1
cat[j]=cat[j]+cat[j-1]
next
cat[i+1]=cat[i]
for j=i+2 to 2 step -1
cat[j]=cat[j]+cat[j-1]
next
see "" + (cat[i+1]-cat[i]) + " "
next
|
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... | #Oforth | Oforth | : threeDogs
| dog Dog DOG |
"Benjamin" ->dog
"Samba" ->Dog
"Bernie" ->DOG
System.Out "The three dogs are named " << dog << ", " << Dog << " and " << DOG << "." << cr ; |
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... | #Ol | Ol |
(define dog "Benjamin")
(define Dog "Samba")
(define 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... | #Julia | Julia |
# Product {1, 2} × {3, 4}
collect(Iterators.product([1, 2], [3, 4]))
# Product {3, 4} × {1, 2}
collect(Iterators.product([3, 4], [1, 2]))
# Product {1, 2} × {}
collect(Iterators.product([1, 2], []))
# Product {} × {1, 2}
collect(Iterators.product([], [1, 2]))
# Product {1776, 1789} × {7, 12} × {4, 14, 23} × {0, 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... | #Common_Lisp | Common Lisp | (defun catalan1 (n)
;; factorial. CLISP actually has "!" defined for this
(labels ((! (x) (if (zerop x) 1 (* x (! (1- x))))))
(/ (! (* 2 n)) (! (1+ n)) (! n))))
;; cache
(defparameter *catalans* (make-array 5
:fill-pointer 0
:adjustable t
:element-type 'integer))
(defun catalan2 (n)... |
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... | #Kotlin | Kotlin | class MyClass {
fun instanceMethod(s: String) = println(s)
companion object {
fun staticMethod(s: String) = println(s)
}
}
fun main(args: Array<String>) {
val mc = MyClass()
mc.instanceMethod("Hello instance world!")
MyClass.staticMethod("Hello static world!")
} |
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... | #Latitude | Latitude | myObject someMethod (arg1, arg2, arg3).
MyClass someMethod (arg1, arg2, arg3). |
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... | #Jsish | Jsish | #!/usr/local/bin/jsish
load('byjsi.so'); |
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... | #Julia | Julia |
#this example works on Windows
ccall( (:GetDoubleClickTime, "User32"), stdcall,
Uint, (), )
ccall( (:clock, "libc"), Int32, ()) |
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
| #Action.21 | Action! | INCLUDE "H6:REALMATH.ACT"
PROC Euler(REAL POINTER e)
REAL e0,fact,tmp,tmp2,one
INT n
IntToReal(1,one)
IntToReal(2,e)
IntToReal(1,fact)
n=2
DO
RealAssign(e,e0)
IntToReal(n,tmp)
RealMult(fact,tmp,tmp2)
RealAssign(tmp2,fact)
n==+1
RealDiv(one,fact,tmp)
RealAdd(e,tmp,tmp2)
... |
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
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Long_Float_Text_IO; use Ada.Long_Float_Text_IO;
procedure Euler is
Epsilon : constant := 1.0E-15;
Fact : Long_Integer := 1;
E : Long_Float := 2.0;
E0 : Long_Float := 0.0;
N : Long_Integer := 2;
begin
loop
E0... |
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... | #BBC_BASIC | BBC BASIC | SYS "LoadLibrary", "MSVCRT.DLL" TO msvcrt%
SYS "GetProcAddress", msvcrt%, "_strdup" TO `strdup`
SYS "GetProcAddress", msvcrt%, "free" TO `free`
SYS `strdup`, "Hello World!" TO address%
PRINT $$address%
SYS `free`, address%
|
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 | C |
#include <stdlib.h>
#include <stdio.h>
int main(int argc,char** argv) {
int arg1 = atoi(argv[1]), arg2 = atoi(argv[2]), sum, diff, product, quotient, remainder ;
__asm__ ( "addl %%ebx, %%eax;" : "=a" (sum) : "a" (arg1) , "b" (arg2) );
__asm__ ( "subl %%ebx, %%eax;" : "=a" (diff) : "a" (arg1) , "b" (... |
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... | #Ada | Ada | # 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
| #Factor | Factor | USING: grouping.extras io kernel math sequences
sequences.repeating ;
IN: rosetta-code.cantor-set
CONSTANT: width 81
CONSTANT: depth 5
: cantor ( n -- seq )
dup 0 = [ drop { 0 1 } ]
[ 1 - cantor [ 3 / ] map dup [ 2/3 + ] map append ] if ;
! Produces a sequence of lengths from a Cantor set, depending on
! ... |
http://rosettacode.org/wiki/Cantor_set | Cantor set | Task
Draw a Cantor set.
See details at this Wikipedia webpage: Cantor set
| #Forth | Forth | warnings off
4 \ iterations
: ** 1 swap 0 ?DO over * LOOP nip ;
3 swap ** constant width \ Make smallest step 1
create string here width char # fill width allot
: print string width type cr ;
\ Overwrite string with new holes of size 'length'.
\ Pointer into string at TOS.
create length width... |
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 ... | #J | J | cw_next_term^:(<20)1x
1 1r2 2 1r3 3r2 2r3 3 1r4 4r3 3r5 5r2 2r5 5r3 3r4 4 1r5 5r4 4r7 7r3 3r8
(,. index_cw_term&>) 3r4 53r37 83116r51639
3r4 14
53r37 1081
83116r51639 123456789
|
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 ... | #Julia | Julia | function calkin_wilf(n)
cw = zeros(Rational, n + 1)
for i in 2:n + 1
t = Int(floor(cw[i - 1])) * 2 - cw[i - 1] + 1
cw[i] = 1 // t
end
return cw[2:end]
end
function continued(r::Rational)
a, b = r.num, r.den
res = []
while true
push!(res, Int(floor(a / b)))
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... | #Perl | Perl | sub co9 { # Follows the simple procedure asked for in Part 1
my $n = shift;
return $n if $n < 10;
my $sum = 0; $sum += $_ for split(//,$n);
co9($sum);
}
sub showadd {
my($n,$m) = @_;
print "( $n [",co9($n),"] + $m [",co9($m),"] ) [",co9(co9($n)+co9($m)),"]",
" = ", $n+$m," [",co9($n+$m),"]\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... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | Cases[Cases[
Cases[Table[{p1, h3, d}, {p1, Array[Prime, PrimePi@61]}, {h3, 2,
p1 - 1}, {d, 1, h3 + p1 - 1}], {p1_Integer, h3_, d_} /;
PrimeQ[1 + (p1 - 1) (h3 + p1)/d] &&
Divisible[p1^2 + d, h3] :> {p1, 1 + (p1 - 1) (h3 + p1)/d, h3},
Infinity], {p1_, p2_, h3_} /; PrimeQ[1 + Floor[p1 p2/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... | #Nim | Nim | import strformat
func isPrime(n: int64): bool =
if n == 2 or n == 3:
return true
elif n < 2 or n mod 2 == 0 or n mod 3 == 0:
return false
var `div` = 5i64
var `inc` = 2i64
while `div` * `div` <= n:
if n mod `div` == 0:
return false
`div` += `inc`
`inc` = 6 - `inc`
return true
f... |
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: ... | #Icon_and_Unicon | Icon and Unicon | procedure main(A)
write(A[1],": ",curry(A[1],A[2:0]))
end
procedure curry(f,A)
r := A[1]
every r := f(r, !A[2:0])
return r
end |
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.