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/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: ...
#Elena
Elena
import system'collections; import system'routines; import extensions; import extensions'text;   public program() { var numbers := new Range(1,10).summarize(new ArrayList());   var summary := numbers.accumulate(new Variable(0), (a,b => a + b));   var product := numbers.accumulate(new Variable(1), (a,b => a *...
http://rosettacode.org/wiki/Chaocipher
Chaocipher
Description The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010. The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here. ...
#Tailspin
Tailspin
  templates chaocipher&{left:,right:,decode:} templates permute def ctshift: [ $@chaocipher.ct($..last)..., $@chaocipher.ct(1..$-1)...]; def p1: $ mod 26 + 1; def ptshift: [ $@chaocipher.pt($p1..last)..., $@chaocipher.pt(1..$p1-1)...]; ..|@chaocipher: { ct: [ $ctshift(1), $ctshift(3..14)..., $ctshift(...
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...
#Nim
Nim
const n = 15 var t = newSeq[int](n + 2)   t[1] = 1 for i in 1..n: for j in countdown(i, 1): t[j] += t[j-1] t[i+1] = t[i] for j in countdown(i+1, 1): t[j] += t[j-1] stdout.write t[i+1] - t[i], " " stdout.write '\n'
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...
#OCaml
OCaml
  let catalan : int ref = ref 0 in Printf.printf "%d ," 1 ; for i = 2 to 9 do let nm : int ref = ref 1 in let den : int ref = ref 1 in for k = 2 to i do nm := (!nm)*(i+k); den := (!den)*k; catalan := (!nm)/(!den) ; done; print_int (!catalan); print_string "," ; done;;  
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...
#Liberty_BASIC
Liberty BASIC
  dog$ = "Benjamin" Dog$ = "Samba" DOG$ = "Bernie" print "The three dogs are "; dog$; ", "; Dog$; " and "; DOG$; "."   end  
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...
#Lua
Lua
dog = "Benjamin" Dog = "Samba" DOG = "Bernie"   print( "There are three dogs named "..dog..", "..Dog.." and "..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...
#Fortran
Fortran
  ! Created by simon on 29/04/2021.   ! ifort -o cartesian_product cartesian_product.f90 -check all   module tuple implicit none private public :: tuple_t, operator(*), print   type tuple_t(n) integer, len :: n integer, private :: v(n) contains procedure, public :: pri...
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...
#Befunge
Befunge
0>:.:000p1>\:00g-#v_v v 2-1*2p00 :+1g00\< $ > **00g1+/^v,*84,"="< _^#<`*53:+1>#,.#+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...
#COBOL
COBOL
*> INVOKE INVOKE FooClass "someMethod" RETURNING bar *> Factory object INVOKE foo-instance "anotherMethod" RETURNING bar *> Instance object   *> Inline method invocation MOVE FooClass::"someMethod" TO bar *> Factory object MOVE foo-instance::"anotherMethod" TO bar *> Instance 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...
#CoffeeScript
CoffeeScript
class Foo @staticMethod: -> 'Bar'   instanceMethod: -> 'Baz'   foo = new Foo   foo.instanceMethod() #=> 'Baz' Foo.staticMethod() #=> 'Bar'
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...
#Common_Lisp
Common Lisp
(defclass my-class () ((x :accessor get-x ;; getter function :initarg :x ;; arg name :initform 0))) ;; initial value   ;; declaring a public class method (defmethod square-x ((class-instance my-class)) (* (get-x class-instance) (get-x class-instance)))   ;; create an instance of my-class (defva...
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...
#C
C
#include <stdio.h> #include <stdlib.h> #include <dlfcn.h>   int myopenimage(const char *in) { static int handle=0; fprintf(stderr, "internal openimage opens %s...\n", in); return handle++; }   int main() { void *imglib; int (*extopenimage)(const char *); int imghandle;   imglib = dlopen("./fakeimglib.so",...
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#BASIC256
BASIC256
  global ancho, alto, intervalo ancho = 81 : alto = 5 dim intervalo(alto, ancho)   subroutine Cantor() for i = 0 to alto - 1 for j = 0 to ancho - 1 intervalo[i, j] = "■" next j next i end subroutine   subroutine ConjCantor(inicio, longitud, indice) segmento = longitud / 3 if segmento = 0 then return for i =...
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#BQN
BQN
Cantor ← {" •" ⊏˜ >⥊¨(¯1⊸⊏⊢¨¨⊢)1‿0‿1∧⌜⍟(↕𝕩)1}
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 ...
#Arturo
Arturo
n: new 1 d: new 1 calkinWilf: function [] .export:[n,d] [ n: (d - n) + 2 * (n/d) * d tmp: d d: n n: tmp return @[n d] ]   first20: [[1 1]] ++ map 1..19 => calkinWilf print "The first 20 terms of the Calkwin-Wilf sequence are:" print map first20 'f -> ~"|f\0|/|f\1|"   n: new 1 d: new 1 indx: new 1  ...
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 ...
#BQN
BQN
GCD ← {m 𝕊⍟(0<m←𝕨|𝕩) 𝕨} _while_ ← {𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩} Sim ← { # Simplify a fraction x𝕊1: 𝕨‿1; 0𝕊y: 0‿𝕩; ⌊𝕨‿𝕩 ÷ 𝕨 GCD 𝕩 } Add ← { # Add two fractions 0‿b 𝕊 𝕩: 𝕩; 𝕨 𝕊 0‿y: 𝕨; a‿b 𝕊 x‿y: ((a×y)+x×b) Sim b×y } Next ← {n‿d: ⌽(2×⌊÷´n‿d)‿1 Add (d-n)‿d} # Next term Cal ← {Next⍟𝕩 1‿1}   •S...
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}} ) ...
#Perl
Perl
# 20220120 Perl programming solution   use strict; use warnings;   use lib '/home/hkdtam/lib'; use Image::EdgeDetect;   my $detector = Image::EdgeDetect->new(); $detector->process('./input.jpg', './output.jpg') or die; # na.cx/i/pHYdUrV.jpg
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}} ) ...
#PHP
PHP
  // input: r,g,b in range 0..255 function RGBtoHSV($r, $g, $b) { $r = $r/255.; // convert to range 0..1 $g = $g/255.; $b = $b/255.; $cols = array("r" => $r, "g" => $g, "b" => $b); asort($cols, SORT_NUMERIC); $min = key(array_slice($cols, 1)); // "r", "g" or "b" $max = key(array_slice($cols, -1)); // "r", "g" or...
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 ...
#JavaScript
JavaScript
const canonicalize = s => {   // Prepare a DataView over a 16 Byte Array buffer. // Initialised to all zeros. const dv = new DataView(new ArrayBuffer(16));   // Get the ip-address and cidr components const [ip, cidr] = s.split('/');   // Make sure the cidr component is a usable int, and // d...
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...
#Java
Java
import java.util.*; import java.util.stream.IntStream;   public class CastingOutNines {   public static void main(String[] args) { System.out.println(castOut(16, 1, 255)); System.out.println(castOut(10, 1, 99)); System.out.println(castOut(17, 1, 288)); }   static List<Integer> castOu...
http://rosettacode.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
Catmull–Clark subdivision surface
Implement the Catmull-Clark surface subdivision (description on Wikipedia), which is an algorithm that maps from a surface (described as a set of points and a set of polygons with vertices at those points) to another more refined surface. The resulting surface will always consist of a mesh of quadrilaterals. The proce...
#Wren
Wren
import "/dynamic" for Tuple, Struct import "/sort" for Sort import "/math" for Int import "/fmt" for Fmt   var Point = Tuple.create("Point", ["x", "y", "z"]) var fields = [ "pn1", // point number 1 "pn2", // point number 2 "fn1", // face number 1 "fn2", // face number 2 "cp" // center point ]...
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...
#FreeBASIC
FreeBASIC
' version 17-10-2016 ' compile with: fbc -s console   ' using a sieve for finding primes   #Define max_sieve 10000000 ' 10^7 ReDim Shared As Byte isprime(max_sieve)   ' translated the pseudo code to FreeBASIC Sub carmichael3(p1 As Integer)   If isprime(p1) = 0 Then Exit Sub   Dim As Integer h3, d, p2, p3, t1, t2 ...
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: ...
#Elixir
Elixir
iex(1)> Enum.reduce(1..10, fn i,acc -> i+acc end) 55 iex(2)> Enum.reduce(1..10, fn i,acc -> i*acc end) 3628800 iex(3)> Enum.reduce(10..-10, "", fn i,acc -> acc <> to_string(i) end) "109876543210-1-2-3-4-5-6-7-8-9-10"
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: ...
#Erlang
Erlang
  -module(catamorphism).   -export([test/0]).   test() -> Nums = lists:seq(1,10), Summation = lists:foldl(fun(X, Acc) -> X + Acc end, 0, Nums), Product = lists:foldl(fun(X, Acc) -> X * Acc end, 1, Nums), Concatenation = lists:foldr( fun(X, Acc) -> integer_to_list(X) ++ Acc end, "", Nums), {Summ...
http://rosettacode.org/wiki/Chaocipher
Chaocipher
Description The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010. The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here. ...
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   ReadOnly L_ALPHABET As String = "HXUCZVAMDSLKPEFJRIGTWOBNYQ" ReadOnly R_ALPHABET As String = "PTLNBQDEOYSFAVZKGJRIHWXUMC"   Enum Mode ENCRYPT DECRYPT End Enum   Function Exec(text As String, mode As Mode, Optional showSteps As Boolean = False) As String Dim l...
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...
#Oforth
Oforth
import: mapping   : pascal( n -- [] ) [ 1 ] n #[ dup [ 0 ] + [ 0 ] rot + zipWith( #+ ) ] times ;   : catalan( n -- m ) n 2 * pascal at( n 1+ ) n 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...
#PARI.2FGP
PARI/GP
vector(15,n,binomial(2*n,n)-binomial(2*n,n+1))
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...
#M2000_Interpreter
M2000 Interpreter
  MoDuLe CheckIT { \\ keys as case sensitive if they are strings Inventory A= "Dog":=1, "dog":=2,"DOG":="Hello", 100:="Dog" Print A("Dog"), A("dog"), A$("DOG"), A$(100)   \\ Enumeration get type as defined (same case) Enum Dogs {Benjamin, Samba, Bernie} Print Type$(Bernie)="Dogs" ...
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...
#Maple
Maple
> dog, Dog, DOG := "Benjamin", "Samba", "Bernie": > if nops( { dog, Dog, DOG } ) = 3 then > printf( "There are three dogs named %s, %s and %s.\n", dog, Dog, DOG ) > elif nops( { dog, Dog, DOG } ) = 2 then > printf( "WTF? There are two dogs named %s and %s.\n", op( { dog, Dog, DOG } ) ) > else > printf( "There is ...
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...
#Go
Go
package main   import "fmt"   type pair [2]int   func cart2(a, b []int) []pair { p := make([]pair, len(a)*len(b)) i := 0 for _, a := range a { for _, b := range b { p[i] = pair{a, b} i++ } } return p }   func main() { fmt.Println(cart2([]int{1, 2}, []int{3...
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...
#Bracmat
Bracmat
( out$straight & ( C = . ( F = i prod .  !arg:0&1 | 1:?prod & 0:?i & whl ' ( 1+!i:~>!arg:?i & !i*!prod:?prod ) & !prod ) & F$(2*!arg)*(F$(!arg+1)*F$!arg)^-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...
#D
D
struct Cat { static int staticMethod() { return 2; }   string dynamicMethod() { // Never virtual. return "Mew!"; } }   class Dog { static int staticMethod() { return 5; }   string dynamicMethod() { // Virtual method. return "Woof!"; } }   void main() { ...
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...
#Dragon
Dragon
r = new run() r.val()
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...
#C.23
C#
using System.Runtime.InteropServices;   class Program { [DllImport("fakelib.dll")] public static extern int fakefunction(int args);   static void Main(string[] args) { int r = fakefunction(10); } }
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...
#COBOL
COBOL
identification division. program-id. callsym.   data division. working-storage section. 01 handle usage pointer. 01 addr usage program-pointer.   procedure division. call "dlopen" using by reference null by value 1 returning hand...
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...
#11l
11l
F no_args() {} // call no_args()   F fixed_args(x, y) print(‘x=#., y=#.’.format(x, y)) // call fixed_args(1, 2) // x=1, y=2   // named arguments fixed_args(x' 1, y' 2)   F opt_args(x = 1) print(x) // calls opt_args() // 1 opt_args(3.141) // 3.141
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#C
C
#include <stdio.h>   #define WIDTH 81 #define HEIGHT 5   char lines[HEIGHT][WIDTH];   void init() { int i, j; for (i = 0; i < HEIGHT; ++i) { for (j = 0; j < WIDTH; ++j) lines[i][j] = '*'; } }   void cantor(int start, int len, int index) { int i, j, seg = len / 3; if (seg == 0) return; fo...
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 ...
#Bracmat
Bracmat
( 1:?a & 0:?i & whl ' ( 1+!i:<20:?i & (2*div$(!a,1)+1+-1*!a)^-1:?a & out$!a ) & ( r2cf = floor . div$(!arg,1):?floor & ( !floor:!arg | !floor r2cf$((!arg+-1*!floor)^-1) ) ) & ( get-term-num = ans dig pwr . (0,1,1):(?ans,?dig,?pwr) & r2cf$!arg:?n & ...
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 ...
#C.2B.2B
C++
#include <iostream> #include <vector> #include <boost/rational.hpp>   using rational = boost::rational<unsigned long>;   unsigned long floor(const rational& r) { return r.numerator()/r.denominator(); }   rational calkin_wilf_next(const rational& term) { return 1UL/(2UL * floor(term) + 1UL - term); }   std::vect...
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}} ) ...
#Phix
Phix
-- -- demo\rosetta\Canny_Edge_Detection.exw -- ===================================== -- without js -- imImage, im_width, im_height, im_pixel, IupImageRGB, -- imFileImageLoadBitmap, and IupImageFromImImage() include pGUI.e constant TITLE = "Canny Edge Detection", IMGFILE = "Valve.png", C_E...
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 ...
#Julia
Julia
using Sockets   function canonCIDR(cidr::String) cidr = replace(cidr, r"\.(\.|\/)" => s".0\1") # handle .. cidr = replace(cidr, r"\.(\.|\/)" => s".0\1") # handle ... ip = split(cidr, "/") dig = length(ip) > 1 ? 2^(32 - parse(UInt8, ip[2])) : 1 ip4 = IPv4(UInt64(IPv4(ip[1])) & (0xffffffff - dig + 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 ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[CanonicalizeCIDR] CanonicalizeCIDR[str_String] := Module[{i, ip, chop, keep, change}, If[StringMatchQ[str, "*.*.*.*/*"], i = StringSplit[str, "." | "/"]; i = Interpreter["Integer"] /@ i; If[MatchQ[i, {_Integer, _Integer, _Integer, _Integer, _Integer}], If[AllTrue[i, Between[{0, 255}]], {ip,...
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 ...
#Nim
Nim
import net import strutils     proc canonicalize*(address: var IpAddress; nbits: Positive) = ## Canonicalize an IP address.   var zbits = 32 - nbits # Number of bits to reset.   # We process byte by byte which avoids byte order issues. for idx in countdown(address.address_v4.high, address.address_v4.low): ...
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...
#JavaScript
JavaScript
function main(s, e, bs, pbs) { bs = bs || 10; pbs = pbs || 10 document.write('start:', toString(s), ' end:', toString(e), ' base:', bs, ' printBase:', pbs) document.write('<br>castOutNine: '); castOutNine() document.write('<br>kaprekar: '); kaprekar() document.write('<br><br>')  ...
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...
#Go
Go
package main   import "fmt"   // Use this rather than % for negative integers func mod(n, m int) int { return ((n % m) + m) % m }   func isPrime(n int) bool { if n < 2 { return false } if n % 2 == 0 { return n == 2 } if n % 3 == 0 { return n == 3 } d := 5 for d * d <= n { if n % 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: ...
#Excel
Excel
FOLDROW =LAMBDA(op, LAMBDA(a, LAMBDA(xs, LET( b, op(a)(HEADROW(xs)),   IF(1 < COLUMNS(xs), FOLDROW(op)(b)( TAILROW(xs) ), b ) ) ) ) )     up...
http://rosettacode.org/wiki/Chaocipher
Chaocipher
Description The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010. The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here. ...
#Vlang
Vlang
type Mode = int const( encrypt = Mode(0) decrypt = Mode(1) )   const( l_alphabet = "HXUCZVAMDSLKPEFJRIGTWOBNYQ" r_alphabet = "PTLNBQDEOYSFAVZKGJRIHWXUMC" )   fn chao(text string, mode Mode, show_steps bool) string { len := text.len if text.bytes().len != len { println("Text contains non-...
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...
#Pascal
Pascal
  Program CatalanNumbers type tElement = Uint64; var Catalan : array[0..50] of tElement; procedure GetCatalan(L:longint); var PasTri : array[0..100] of tElement; j,k: longInt; begin l := l*2; PasTri[0] := 1; j := 0; while (j<L) do begin inc(j); k := (j+1) div 2; PasTri[k] :=PasTri[k-1];...
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...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
dog = "Benjamin"; Dog = "Samba"; DOG = "Bernie"; "The three dogs are named "<> dog <>", "<> Dog <>" and "<> DOG   -> "The three dogs are named Benjamin, Samba and Bernie"
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...
#MATLAB_.2F_Octave
MATLAB / Octave
dog = 'Benjamin'; Dog = 'Samba'; DOG = 'Bernie';   printf('There are three dogs %s, %s, %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...
#Groovy
Groovy
class CartesianCategory { static Iterable multiply(Iterable a, Iterable b) { assert [a,b].every { it != null } def (m,n) = [a.size(),b.size()] (0..<(m*n)).inject([]) { prod, i -> prod << [a[i.intdiv(n)], b[i%n]].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...
#Brat
Brat
catalan = { n | true? n == 0 { 1 } { (2 * ( 2 * n - 1) / ( n + 1 )) * catalan(n - 1) } }   0.to 15 { n | p "#{n} - #{catalan 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...
#Dyalect
Dyalect
//Static method on a built-in type Integer static func Integer.Div(x, y) { x / y }   //Instance method func Integer.Div(n) { this / n }   print(Integer.Div(12, 3)) print(12.Div(3))
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...
#E
E
someObject.someMethod(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...
#Elena
Elena
  console.printLine("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...
#Common_Lisp
Common Lisp
CL-USER> (cffi:load-foreign-library "libX11.so") #<CFFI::FOREIGN-LIBRARY {1004F4ECC1}> CL-USER> (cffi:foreign-funcall "XOpenDisplay" :string #+sbcl (sb-posix:getenv "DISPLAY") #-sbcl ":0.0" :pointer) #.(SB-SYS:INT-SAP #...
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...
#Crystal
Crystal
libm = LibC.dlopen("libm.so.6", LibC::RTLD_LAZY) sqrtptr = LibC.dlsym(libm, "sqrt") unless libm.null?   if sqrtptr sqrtproc = Proc(Float64, Float64).new sqrtptr, Pointer(Void).null at_exit { LibC.dlclose(libm) } else sqrtproc = ->Math.sqrt(Float64) end   puts "the sqrt of 4 is #{sqrtproc.call(4.0)}"
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...
#360_Assembly
360 Assembly
X DS F Y DS F Z DS F
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#C.23
C#
using System;   namespace CantorSet { class Program { const int WIDTH = 81; const int HEIGHT = 5; private static char[,] lines = new char[HEIGHT, WIDTH];   static Program() { for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; 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 ...
#EDSAC_order_code
EDSAC order code
  [For Rosetta Code. EDSAC program, Initial Orders 2. Prints the first 20 terms of the Calkin-Wilf sequence. Uses term{n} to calculate term{n + 1}.]   [Print subroutine for non-negative 17-bit integers. Parameters: 0F = integer to be printed (not preserved) 1F = character for leading zero (preserved) W...
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.23
F#
  // Calkin Wilf Sequence. Nigel Galloway: January 9th., 2021 let cW=Seq.unfold(fun(n)->Some(n,seq{for n,g in n do yield (n,n+g); yield (n+g,g)}))(seq[(1,1)])|>Seq.concat  
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}} ) ...
#Python
Python
#!/bin/python import numpy as np from scipy.ndimage.filters import convolve, gaussian_filter from scipy.misc import imread, imshow   def CannyEdgeDetector(im, blur = 1, highThreshold = 91, lowThreshold = 31): im = np.array(im, dtype=float) #Convert to float to prevent clipping values   #Gaussian blur to reduce noise ...
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 ...
#Perl
Perl
#!/usr/bin/env perl use v5.16; use Socket qw(inet_aton inet_ntoa);   # canonicalize a CIDR block: make sure none of the host bits are set if (!@ARGV) { chomp(@ARGV = <>); }   for (@ARGV) {   # dotted-decimal / bits in network part my ($dotted, $size) = split m#/#;   # get IP as binary string my $binary = spr...
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...
#jq
jq
def co9: def digits: tostring | explode | map(. - 48); # "0" is 48 if . == 9 then 0 elif 0 <= . and . <= 8 then . else digits | add | co9 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...
#Haskell
Haskell
#!/usr/bin/runhaskell   import Data.Numbers.Primes import Control.Monad (guard)   carmichaels = do p <- takeWhile (<= 61) primes h3 <- [2..(p-1)] let g = h3 + p d <- [1..(g-1)] guard $ (g * (p - 1)) `mod` d == 0 && (-1 * p * p) `mod` h3 == d `mod` h3 let q = 1 + (((p - 1) * g) `div` d) guard $ isPrime q ...
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: ...
#F.23
F#
> let nums = [1 .. 10];; val nums : int list = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10] > let summation = List.fold (+) 0 nums;; val summation : int = 55 > let product = List.fold (*) 1 nums;; val product : int = 3628800 > let concatenation = List.foldBack (fun x y -> x + y) (List.map (fun i -> i.ToString()) nums) "";; v...
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: ...
#Factor
Factor
{ 1 2 4 6 10 } 0 [ + ] reduce .
http://rosettacode.org/wiki/Chaocipher
Chaocipher
Description The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010. The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here. ...
#Wren
Wren
class Chao { static encrypt { 0 } static decrypt { 1 }   static exec(text, mode, showSteps) { var len = text.count if (len != text.bytes.count) Fiber.abort("Text contains non-ASCII characters.") var left = "HXUCZVAMDSLKPEFJRIGTWOBNYQ" var right = "PTLNBQDEOYSFAVZKGJRIHWXUMC"...
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...
#Perl
Perl
use constant N => 15; my @t = (0, 1); for(my $i = 1; $i <= N; $i++) { for(my $j = $i; $j > 1; $j--) { $t[$j] += $t[$j-1] } $t[$i+1] = $t[$i]; for(my $j = $i+1; $j>1; $j--) { $t[$j] += $t[$j-1] } print $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...
#Maxima
Maxima
/* Maxima is case sensitive */ a: 1$ A: 2$   is(a = A); false
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...
#min
min
"Benjamin" :dog "Samba" :Dog "Bernie" :DOG   "There are three dogs named $1, $2, and $3." (dog Dog DOG)=> % print
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...
#MiniScript
MiniScript
dog = "Benjamin" Dog = "Samba" DOG = "Bernie"   print "There are three dogs named " + dog + ", " + Dog + " and " + 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...
#Haskell
Haskell
cartProd :: [a] -> [b] -> [(a, b)] cartProd xs ys = [ (x, y) | x <- xs , y <- ys ]
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...
#BQN
BQN
Cat←{ 0⊸<◶⟨1, (𝕊-⟜1)×(¯2+4×⊢)÷1+⊢⟩ 𝕩 } Fact ← ×´1+↕ Cat1 ← { # direct formula ⌊0.5 + (Fact 2×𝕩) ÷ (Fact 𝕩+1) × Fact 𝕩 } Cat2 ← { # header based recursion 0: 1; (𝕊 𝕩-1)×2×(1-˜2×𝕩)÷𝕩+1 }   Cat¨ ↕15 Cat1¨ ↕15 Cat2¨ ↕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...
#Elixir
Elixir
  defmodule ObjectCall do def new() do spawn_link(fn -> loop end) end   defp loop do receive do {:concat, {caller, [str1, str2]}} -> result = str1 <> str2 send caller, {:ok, result} loop end end   def concat(obj, str1, str2) do send obj, {:concat, {self(), [str1, ...
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...
#Factor
Factor
USING: accessors io kernel literals math sequences ; IN: rosetta-code.call-a-method   ! Define some classes. SINGLETON: dog TUPLE: cat sassiness ;   ! Define a constructor for cat. C: <cat> cat   ! Define a generic word that dispatches on the object at the top ! of the data stack. GENERIC: speak ( obj -- )   ! Define m...
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...
#D
D
pragma(lib, "user32.lib");   import std.stdio, std.c.windows.windows;   extern(Windows) UINT GetDoubleClickTime();   void main() { writeln(GetDoubleClickTime()); }
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...
#Dart
Dart
  int add(int num1, int num2) { return num1 + num2; }  
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...
#8th
8th
  \ tell 8th what the function expects: "ZZ" "strdup" func: strdup "VZ" "free" func: free \ call the external funcs "abc" dup \ now we have two strings "abc" on the stack strdup .s cr \ after strdup, you'll have the new (but duplicate) string on the stack \ the ".s" will show both strings and you can see they are...
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...
#6502_Assembly
6502 Assembly
JSR myFunction
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#C.2B.2B
C++
#include <iostream>   const int WIDTH = 81; const int HEIGHT = 5;   char lines[WIDTH*HEIGHT];   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; lines[pos...
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 ...
#Factor
Factor
USING: formatting io kernel lists lists.lazy math math.continued-fractions math.functions math.parser prettyprint sequences strings vectors ;   : next-cw ( x -- y ) [ floor dup + ] [ 1 swap - + recip ] bi ;   : calkin-wilf ( -- list ) 1 [ next-cw ] lfrom-by ;   : >continued-fraction ( x -- seq ) 1vector [ dup last ...
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 ...
#Forth
Forth
\ Calkin-Wilf sequence   : frac. swap . ." / " . ; : cw-next ( num den -- num den ) 2dup / over * 2* over + rot - ; : cw-seq ( n -- ) 1 1 rot 0 do cr 2dup frac. cw-next loop 2drop ;   variable index variable bit-state variable bit-position : r2cf-next ( num1 den1 -- num2 den2 u ) swap over >r s>d r> sm/rem...
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}} ) ...
#Raku
Raku
#include <stdio.h> #include <string.h> #include <magick/MagickCore.h>   int CannyEdgeDetector( const char *infile, const char *outfile, double radius, double sigma, double lower, double upper ) {   ExceptionInfo *exception; Image *image, *processed_image, *output; ImageInfo *input_info;...
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 ...
#Phix
Phix
with javascript_semantics -- (not likely useful) function canonicalize_cidr(string cidr) cidr = substitute(cidr,"."," ") -- (else %d eats 0.0 etc) if not find('/',cidr) then cidr &= "/32" end if sequence res = scanf(cidr,"%d %d %d %d/%d") if length(res)=1 then integer {a,b,c,d,m} = res[1] ...
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...
#Julia
Julia
co9(x) = x == 9  ? 0 : 1<=x<=8 ? x : co9(sum(digits(x)))
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...
#Kotlin
Kotlin
// version 1.1.3   fun castOut(base: Int, start: Int, end: Int): List<Int> { val b = base - 1 val ran = (0 until b).filter { it % b == (it * it) % b } var x = start / b val result = mutableListOf<Int>() while (true) { for (n in ran) { val k = b * x + n if (k < start) ...
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...
#Icon_and_Unicon
Icon and Unicon
link "factors"   procedure main(A) n := integer(!A) | 61 every write(carmichael3(!n)) end   procedure carmichael3(p1) every (isprime(p1), (h := 1+!(p1-1)), (d := !(h+p1-1))) do if (mod(((h+p1)*(p1-1)),d) = 0, mod((-p1*p1),h) = mod(d,h)) then { p2 := 1 + (p1-1)*(h+p1)/d p3 := ...
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: ...
#Forth
Forth
: lowercase? ( c -- f ) [char] a [ char z 1+ ] literal within ;   : char-upcase ( c -- C ) dup lowercase? if bl xor then ;
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: ...
#Fortran
Fortran
SUBROUTINE FOLD(t,F,i,ist,lst) INTEGER t BYNAME F DO i = ist,lst t = F END DO END SUBROUTINE FOLD !Result in temp.   temp = a(1); CALL FOLD(temp,temp*a(i),i,2,N)
http://rosettacode.org/wiki/Chaocipher
Chaocipher
Description The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010. The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here. ...
#zkl
zkl
class Chao{ var [const private] lAlphabet = "HXUCZVAMDSLKPEFJRIGTWOBNYQ", rAlphabet = "PTLNBQDEOYSFAVZKGJRIHWXUMC"; fcn encode(text){ code(text,encodeL); } fcn decode(text){ code(text,decodeL); } // reset alphabets each [en|de]code and maintain re-entrancy fcn code(text,f){ text.apply(f,Data(Voi...
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...
#Phix
Phix
constant N = 15 -- accurate to 30, nan/inf for anything over 514 (gmp version is below). sequence catalan = {}, -- (>=1 only) p = repeat(1,N+1) atom p1 for i=1 to N do p1 = p[1]*2 catalan = append(catalan,p1-p[2]) for j=1 to N-i+1 do p1 += p[j+1] p[j] = p1 end for --  ?p[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...
#PicoLisp
PicoLisp
(de bino (N K) (let f '((N) (if (=0 N) 1 (apply * (range 1 N))) ) (/ (f N) (* (f (- N K)) (f K)) ) ) )   (for N 15 (println (- (bino (* 2 N) N) (bino (* 2 N) (inc N)) ) ) ) (bye)
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...
#Modula-2
Modula-2
MODULE dog;   IMPORT InOut;   TYPE String = ARRAY [0..31] OF CHAR;   VAR dog, Dog, DOG : String;   (* No compiler error, so the rest is simple *)   BEGIN InOut.WriteString ("Three happy dogs."); InOut.WriteLn END 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...
#Nanoquery
Nanoquery
dog = "Benjamin" Dog = "Samba" DOG = "Bernie"   print format("The three dogs are named %s, %s, and %s.\n", 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...
#Nemerle
Nemerle
def dog = "Benjamin"; def Dog = "Samba"; def DOG = "Bernie"; WriteLine($"The three dogs are named $dog, $Dog, and $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...
#J
J
{ 1776 1789 ; 7 12 ; 4 14 23 ; 0 1 NB. result is 4 dimensional array with shape 2 2 3 2 ┌────────────┬────────────┐ │1776 7 4 0 │1776 7 4 1 │ ├────────────┼────────────┤ │1776 7 14 0 │1776 7 14 1 │ ├────────────┼────────────┤ │1776 7 23 0 │1776 7 23 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...
#C
C
#include <stdio.h>   typedef unsigned long long ull;   ull binomial(ull m, ull n) { ull r = 1, d = m - n; if (d > n) { n = d; d = m - n; }   while (m > n) { r *= m--; while (d > 1 && ! (r%d) ) r /= d--; }   return r; }   ull catalan1(int n) { return binomial(2 * n, n) / (1 + n); }   ull catalan2(int n) { int...
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...
#Forth
Forth
include lib/compare.4th include 4pp/lib/foos.4pp   [ASSERT] \ enable assertions   :: Cat class method: dynamicCat \ virtual method end-class {    :static staticCat { 2 } ; \ static method  :method { s" Mew!" } ; defines dynamicCat } ...
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...
#Fortran
Fortran
  ! type declaration type my_type contains procedure, pass :: method1 procedure, pass, pointer :: method2 end type my_type   ! declare object of type my_type type(my_type) :: mytype_object   !static call call mytype_object%method1() ! call method1 defined as subroutine !instance? mytype_object%method2() ! call metho...