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/Bulls_and_cows/Player
Bulls and cows/Player
Task Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts. One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equ...
#Ada
Ada
with Ada.Text_IO; with Ada.Containers.Vectors; with Ada.Numerics.Discrete_Random;   procedure Bulls_Player is   -- package for In-/Output of natural numbers package Nat_IO is new Ada.Text_IO.Integer_IO (Natural);   -- for comparing length of the vectors use type Ada.Containers.Count_Type;   -- number of ...
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers
Calendar - for "REAL" programmers
Task Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented   entirely without lowercase. Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide. (Hint: manually convert the code from the Calendar task to al...
#AutoHotkey
AutoHotkey
CALENDAR(YR){ LASTDAY := [], DAY := [] TITLES = (LTRIM ______JANUARY_________________FEBRUARY_________________MARCH_______ _______APRIL____________________MAY____________________JUNE________ ________JULY___________________AUGUST_________________SEPTEMBER_____ ______OCTOBER_________________NOVEMBER_______________...
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...
#Delphi
Delphi
  {$O myhello.obj}  
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...
#Factor
Factor
FUNCTION: char* strdup ( c-string s ) ;   : my-strdup ( str -- str' ) strdup [ utf8 alien>string ] [ (free) ] bi ;
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...
#Arturo
Arturo
printHello: $[][ print "Hello World!" ]   sayHello: $[name][ print ["Hello" name "!"] ]   printAll: $[args][ loop args [arg][ print arg ] ]   getNumber: $[][3]   ; Calling a function that requires no arguments printHello   ; Calling a function with a fixed number of arguments sayHello "John"   ; Calling a functio...
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#IS-BASIC
IS-BASIC
100 PROGRAM "Cantor.bas" 110 GRAPHICS HIRES 2 120 SET PALETTE BLACK,WHITE 130 CALL CANTOR(28,500,1216,32) 140 DEF CANTOR(X,Y,L,HEIGHT) 150 IF L>3 THEN 160 PLOT X,Y;X+L,Y,X,Y+4;X+L,Y+4 170 CALL CANTOR(X,Y-HEIGHT,L/3,HEIGHT) 180 CALL CANTOR(X+2*L/3,Y-HEIGHT,L/3,HEIGHT) 190 END IF 200 END DEF
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#J
J
  odometer =: [: (4 $. $.) $&1   cantor_dust =: monad define shape =. ,~ 3 ^ y a =. shape $ ' ' i =. odometer shape < (}:"1) 1j1 #"1 '#' (([: <"1 [: ;/"1 (#~ 1 e."1 [: (,/"2) 3 3&#:)) i)}a )  
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 ...
#Prolog
Prolog
  % John Devou: 26-Nov-2021   % g(N,X):- consecutively generate in X the first N elements of the Calkin-Wilf sequence   g(N,[A/B|_]-_,A/B):- N > 0. g(N,[A/B|Ls]-[A/C,C/B|Ys],X):- N > 1, M is N-1, C is A+B, g(M,Ls-Ys,X). g(N,X):- g(N,[1/1|Ls]-Ls,X).   % t(A/B,X):- generate in X the index of A/B in the Calkin-Wilf seque...
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...
#Raku
Raku
sub cast-out(\BASE = 10, \MIN = 1, \MAX = BASE**2 - 1) { my \B9 = BASE - 1; my @ran = ($_ if $_ % B9 == $_**2 % B9 for ^B9); my $x = MIN div B9; gather loop { for @ran -> \n { my \k = B9 * $x + n; take k if k >= MIN; } $x++; } ...^ * > MAX; }   say cast-out; say cast-out 16; say cast-o...
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...
#Prolog
Prolog
  show(Limit) :- forall( carmichael(Limit, P1, P2, P3, C), format("~w * ~w * ~w ~t~20| = ~w~n", [P1, P2, P3, C])).   carmichael(Upto, P1, P2, P3, X) :- between(2, Upto, P1), prime(P1), Limit is P1 - 1, between(2, Limit, H3), MaxD is H3 + P1 - 1, between(1, MaxD, D), (H3 + P1)*(P1...
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: ...
#Logtalk
Logtalk
  :- object(folding_examples).   :- public(show/0). show :- integer::sequence(1, 10, List), write('List: '), write(List), nl, meta::fold_left([Acc,N,Sum0]>>(Sum0 is Acc+N), 0, List, Sum), write('Sum of all elements: '), write(Sum), nl, meta::fold_left([Acc,N,Product0]>>(P...
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...
#TI-83_BASIC
TI-83 BASIC
"CATALAN 15→N seq(0,I,1,N+2)→L1 1→L1(1) For(I,1,N) For(J,I+1,2,-1) L1(J)+L1(J-1)→L1(J) End L1(I)→L1(I+1) For(J,I+2,2,-1) L1(J)+L1(J-1)→L1(J) End Disp L1(I+1)-L1(I) End
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using onl...
#Vala
Vala
void main() { const int N = 15; uint64[] t = {0, 1}; for (int i = 1; i <= N; i++) { for (int j = i; j > 1; j--) t[j] = t[j] + t[j - 1]; t[i + 1] = t[i]; for (int j = i + 1; j > 1; j--) t[j] = t[j] + t[j - 1]; print(@"$(t[i + 1] - t[i]) "); } print("\n"); }
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language...
#Quackery
Quackery
[ $ 'Benjamin' ] is dog ( --> $ )   [ $ 'Samba' ] is Dog ( --> $ )   [ $ 'Bernie' ] is DOG ( --> $ )   say 'There are three dogs named ' dog echo$ say ', ' Dog echo$ say ', and ' DOG echo$ say '.' 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...
#R
R
dog <- 'Benjamin' Dog <- 'Samba' DOG <- 'Bernie'   # Having fun with cats and dogs cat('The three dogs are named ') cat(dog) cat(', ') cat(Dog) cat(' and ') cat(DOG) cat('.\n') # In one line it would be: # cat('The three dogs are named ', dog, ', ', Dog, ' and ', DOG, '.\n', sep = '')
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...
#Racket
Racket
  #lang racket (define dog "Benjamin") (define Dog "Samba") (define DOG "Bernie")   (if (equal? dog DOG) (displayln (~a "There is one dog named " DOG ".")) (displayln (~a "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...
#Modula-2
Modula-2
MODULE CartesianProduct; FROM FormatString IMPORT FormatString; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   PROCEDURE WriteInt(a : INTEGER); VAR buf : ARRAY[0..9] OF CHAR; BEGIN FormatString("%i", buf, a); WriteString(buf) END WriteInt;   PROCEDURE Cartesian(a,b : ARRAY OF INTEGER); VAR i,j : CARDINAL;...
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...
#EDSAC_order_code
EDSAC order code
  [Calculation of Catalan numbers. EDSAC program, Initial Orders 2.]   [Define where to store the list of Catalan numbers.] T 54 K [store address in location 54, so that values are accessed by code letter C (for Catalan)] P 200 F [<------ address here]   [Mod...
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...
#Object_Pascal
Object Pascal
// Static (known in Pascal as class method) MyClass.method(someParameter);   // Instance myInstance.method(someParameter);  
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance m...
#Objective-C
Objective-C
// Class [MyClass method:someParameter]; // or equivalently: id foo = [MyClass class]; [foo method:someParameter];   // Instance [myInstance method:someParameter];   // Method with multiple arguments [myInstance methodWithRed:arg1 green:arg2 blue:arg3];   // Method with no arguments [myInstance method];
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...
#OCaml
OCaml
my_obj#my_meth params
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...
#PARI.2FGP
PARI/GP
install("function_name","G","gp_name","./test.gp.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...
#Pascal
Pascal
use Inline C => "DATA", ENABLE => "AUTOWRAP", LIBS => "-lm";   print 4*atan(1) . "\n";   __DATA__ __C__ double atan(double x);
http://rosettacode.org/wiki/Burrows%E2%80%93Wheeler_transform
Burrows–Wheeler transform
This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Burrows–Wheeler transform (BWT, also called block-s...
#BQN
BQN
stx←@+2 BWT ← { # Burrows-Wheeler Transform and its inverse as an invertible function 𝕊: "Input contained STX"!⊑stx¬∘∊𝕩 ⋄ (⍋↓𝕩) ⊏ stx∾𝕩; 𝕊⁼: 1↓(⊑˜⍟(↕≠𝕩)⟜⊑ ⍋)⊸⊏ 𝕩 }  
http://rosettacode.org/wiki/Burrows%E2%80%93Wheeler_transform
Burrows–Wheeler transform
This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Burrows–Wheeler transform (BWT, also called block-s...
#C
C
#include <string.h> #include <stdio.h> #include <stdlib.h>   const char STX = '\002', ETX = '\003';   int compareStrings(const void *a, const void *b) { char *aa = *(char **)a; char *bb = *(char **)b; return strcmp(aa, bb); }   int bwt(const char *s, char r[]) { int i, len = strlen(s) + 2; char *ss,...
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to...
#11l
11l
F caesar(string, =key, decode = 0B) I decode key = 26 - key   V r = ‘ ’ * string.len L(c) string r[L.index] = S c ‘a’..‘z’ Char(code' (c.code - ‘a’.code + key) % 26 + ‘a’.code) ‘A’..‘Z’ Char(code' (c.code ...
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
#BASIC
BASIC
n = 1  : n1 = 1 e1 = 0 : e = 1 / 1   while e <> e1 e1 = e e += 1 / n n1 += 1 n *= n1 end while   print "The value of e = "; e end
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
#Befunge
Befunge
52*92*1->01p:01g1-:v v *_$101p011p54*21p>:11g1+:01g*01p:11p/21g1-:v v < ^ _$$>\:^ ^ p12_$>+\:#^_$554**/@
http://rosettacode.org/wiki/Bulls_and_cows/Player
Bulls and cows/Player
Task Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts. One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equ...
#AutoHotkey
AutoHotkey
length:=4, i:=0, S:=P(9,length)   Gui, Add, Text, w83 vInfo, Think of a %length%-digit number with no duplicate digits. Gui, Add, Edit, w40 vBulls Gui, Add, Text, x+3, Bulls Gui, Add, Edit, xm w40 vCows Gui, Add, Text, x+3, Cows Gui, Add, Button, xm w83 Default vDefault, Start Gui, Add, Edit, ym w130 r8 vHistory ReadOn...
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers
Calendar - for "REAL" programmers
Task Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented   entirely without lowercase. Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide. (Hint: manually convert the code from the Calendar task to al...
#BaCon
BaCon
DECLARE MON$[] = { "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER" } DECLARE MON[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } Y$ = "1969" ' Leap year INCR MON[1], IIF(MOD(VAL(Y$), 4) = 0 OR MOD(VAL(Y$), 100) = 0 AND MOD(VAL(Y$), 400) <> ...
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...
#FBSL
FBSL
c-library cstrings   \c #include <string.h> c-function strdup strdup a -- a ( c-string -- duped string ) c-function strlen strlen a -- n ( c-string -- length )   end-c-library   \ convenience function (not used here) : c-string ( addr u -- addr' ) tuck pad swap move pad + 0 swap c! pad ;   create test s" testing...
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...
#Forth
Forth
c-library cstrings   \c #include <string.h> c-function strdup strdup a -- a ( c-string -- duped string ) c-function strlen strlen a -- n ( c-string -- length )   end-c-library   \ convenience function (not used here) : c-string ( addr u -- addr' ) tuck pad swap move pad + 0 swap c! pad ;   create test s" testing...
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...
#AutoHotkey
AutoHotkey
; Call a function without arguments: f()   ; Call a function with a fixed number of arguments: f("string", var, 15.5)   ; Call a function with optional arguments: f("string", var, 15.5)   ; Call a function with a variable number of arguments: f("string", var, 15.5)   ; Call a function with named arguments: ; AutoHo...
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#Java
Java
public class App { private static final int WIDTH = 81; private static final int HEIGHT = 5;   private static char[][] lines; static { lines = new char[HEIGHT][WIDTH]; for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { lines[i][j] = '*'; ...
http://rosettacode.org/wiki/Calkin-Wilf_sequence
Calkin-Wilf sequence
The Calkin-Wilf sequence contains every nonnegative rational number exactly once. It can be calculated recursively as follows: a1 = 1 an+1 = 1/(2⌊an⌋+1-an) for n > 1 Task part 1 Show on this page terms 1 through 20 of the Calkin-Wilf sequence. To avoid floating point error, you may want to ...
#Python
Python
from fractions import Fraction from math import floor from itertools import islice, groupby     def cw(): a = Fraction(1) while True: yield a a = 1 / (2 * floor(a) + 1 - a)   def r2cf(rational): num, den = rational.numerator, rational.denominator while den: num, (digit, den) = de...
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 ...
#Quackery
Quackery
[ $ "bigrat.qky" loadfile ] now!   [ ' [ [ 1 1 ] ] swap 1 - times [ dup -1 peek do 2dup proper 2drop 2 * n->v 2swap -v 1 n->v v+ v+ 1/v join nested join ] ] is calkin-wilf ( n --> [ )   [ 1 & ] is odd ( n --> b )   [ dup size odd not i...
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...
#REXX
REXX
/*REXX program demonstrates the casting─out─nines algorithm (with Kaprekar numbers). */ parse arg LO HI base . /*obtain optional arguments from the CL*/ if LO=='' | LO=="," then do; LO=1; HI=1000; end /*Not specified? Then use the default*/ if HI=='' | HI=="," then HI= LO ...
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...
#Python
Python
class Isprime(): ''' Extensible sieve of Eratosthenes   >>> isprime.check(11) True >>> isprime.multiples {2, 4, 6, 8, 9, 10} >>> isprime.primes [2, 3, 5, 7, 11] >>> isprime(13) True >>> isprime.multiples {2, 4, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16, 18, 20, 21, 22} >>> i...
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article: ...
#LOLCODE
LOLCODE
HAI 1.3   HOW IZ I reducin YR array AN YR size AN YR fn I HAS A val ITZ array'Z SRS 0 IM IN YR LOOP UPPIN YR i TIL BOTH SAEM i AN DIFF OF size AN 1 val R I IZ fn YR val AN YR array'Z SRS SUM OF i AN 1 MKAY IM OUTTA YR LOOP FOUND YR val IF U SAY SO   O HAI IM array I HAS A SRS 0 ITZ 1 I H...
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...
#VBScript
VBScript
dim t() if Wscript.arguments.count=1 then n=Wscript.arguments.item(0) else n=15 end if redim t(n+1) 't(*)=0 t(1)=1 for i=1 to n ip=i+1 for j = i to 1 step -1 t(j)=t(j)+t(j-1) next 'j t(i+1)=t(i) for j = i+1 to 1 step -1 t(j)=t(j)+t(j-1) next 'j Wscript.echo t(i+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...
#Visual_Basic
Visual Basic
  Sub catalan() Const n = 15 Dim t(n + 2) As Long Dim i As Integer, j As Integer t(1) = 1 For i = 1 To n For j = i + 1 To 2 Step -1 t(j) = t(j) + t(j - 1) Next j t(i + 1) = t(i) For j = i + 2 To 2 Step -1 t(j) = t(j) + t(j - 1) Next j ...
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...
#Raku
Raku
my $dog = 'Benjamin'; my $Dog = 'Samba'; my $DOG = 'Bernie'; say "The three dogs are named $dog, $Dog, and $DOG."
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language...
#Retro
Retro
: dog ( -$ ) "Benjamin" ; : Dog ( -$ ) "Samba" ; : DOG ( -$ ) "Bernie" ;   DOG Dog dog "The three dogs are named %s, %s, and %s.\n" puts
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...
#REXX
REXX
/*REXX program demonstrate case insensitivity for simple REXX variable names. */   /* ┌──◄── all 3 left─hand side REXX variables are identical (as far as assignments). */ /* │ */ /* ↓ ...
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...
#Nim
Nim
iterator product[T1, T2](a: openArray[T1]; b: openArray[T2]): tuple[a: T1, b: T2] = # Yield the element of the cartesian product of "a" and "b". # Yield tuples rather than arrays as it allows T1 and T2 to be different.   for x in a: for y in b: yield (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...
#Eiffel
Eiffel
  class APPLICATION   create make   feature {NONE}   make do across 0 |..| 14 as c loop io.put_double (nth_catalan_number (c.item)) io.new_line end end   nth_catalan_number (n: INTEGER): DOUBLE --'n'th number in the sequence of Catalan numbers. require n_not_negative: n >= 0 local...
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...
#Oforth
Oforth
1.2 sqrt
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...
#ooRexx
ooRexx
say "pi:" .circle~pi c=.circle~new(1) say "c~area:" c~area Do r=2 To 10 c.r=.circle~new(r) End say .circle~instances('') 'circles were created'   ::class circle ::method pi class -- a class method return 3.14159265358979323   ::method instances class -- another class method expose in use arg a If datatype(in)...
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...
#Perl
Perl
# Class method MyClass->classMethod($someParameter); # Equivalently using a class name my $foo = 'MyClass'; $foo->classMethod($someParameter);     # Instance method $myInstance->method($someParameter);   # Calling a method with no parameters $myInstance->anotherMethod;   # Class and instance method calls are made behin...
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...
#Perl
Perl
use Inline C => "DATA", ENABLE => "AUTOWRAP", LIBS => "-lm";   print 4*atan(1) . "\n";   __DATA__ __C__ double atan(double x);
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...
#Phix
Phix
without js -- not from a browser, mate! string {libname,funcname} = iff(platform()=WINDOWS?{"user32","CharLowerA"}:{"libc","tolower"}) atom lib = open_dll(libname) integer func = define_c_func(lib,funcname,{C_INT},C_INT) if func=-1 then ?{{lower('A')}} -- (you don't //have// to crash!) else ?c_func(func,{'A'}) ...
http://rosettacode.org/wiki/Burrows%E2%80%93Wheeler_transform
Burrows–Wheeler transform
This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Burrows–Wheeler transform (BWT, also called block-s...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   namespace BurrowsWheeler { class Program { const char STX = (char)0x02; const char ETX = (char)0x03;   private static void Rotate(ref char[] a) { char t = a.Last(); for (int i = a.Length - 1; i > 0; ...
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to...
#360_Assembly
360 Assembly
* Caesar cypher 04/01/2019 CAESARO PROLOG XPRNT PHRASE,L'PHRASE print phrase LH R3,OFFSET offset BAL R14,CYPHER call cypher LNR R3,R3 -offset BAL R14,CYPHER call cypher EPILOG CYPHER...
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
#Burlesque
Burlesque
  blsq ) 70rz?!{10 100**\/./}ms36.+Sh'.1iash 2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274  
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
#C
C
#include <stdio.h> #include <math.h>   int main(int argc, char* argv[]) { double e;   puts("The double precision in C give about 15 significant digits.\n" "Values below are presented with 16 digits after the decimal point.\n");   // The most direct way to compute Euler constant. // e = exp(...
http://rosettacode.org/wiki/Bulls_and_cows/Player
Bulls and cows/Player
Task Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts. One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equ...
#BBC_BASIC
BBC BASIC
secret$ = "" REPEAT c$ = CHR$(&30 + RND(9)) IF INSTR(secret$, c$) = 0 secret$ += c$ UNTIL LEN(secret$) = 4   FOR i% = 1234 TO 9876 possible$ += STR$(i%) NEXT   PRINT "Guess a four-digit number with no digit used twice." guesses% = 0 REPEAT   ...
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers
Calendar - for "REAL" programmers
Task Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented   entirely without lowercase. Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide. (Hint: manually convert the code from the Calendar task to al...
#BBC_BASIC
BBC BASIC
VDU 23,22,1056;336;8,16,16,128   YEAR = 1969 PRINT TAB(62) "[SNOOPY]" TAB(64); YEAR DIM DOM(5), MJD(5), DM(5), MONTH$(11) DAYS$ = "SU MO TU WE TH FR SA" MONTH$() = "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", \ \ "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", ...
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...
#Fortran
Fortran
module c_api use iso_c_binding implicit none   interface function strdup(ptr) bind(C) import c_ptr type(c_ptr), value :: ptr type(c_ptr) :: strdup end function end interface   interface subroutine free(ptr) bind(C) import c_ptr ...
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...
#AWK
AWK
BEGIN { sayhello() # Call a function with no parameters in statement context b=squareit(3) # Obtain the return value from a function with a single parameter in first class context }
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#JavaScript
JavaScript
(() => { "use strict";   // -------------- CANTOR BOOL-INT PAIRS --------------   // cantor :: [(Bool, Int)] -> [(Bool, Int)] const cantor = xs => { const go = ([bln, n]) => bln && 1 < n ? (() => { const x = Math.floor(n / 3);   return [ ...
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 ...
#Raku
Raku
my @calkin-wilf = Any, 1, {1 / (.Int × 2 + 1 - $_)} … *;   # Rational to Calkin-Wilf index sub r2cw (Rat $rat) { :2( join '', flat (flat (1,0) xx *) Zxx reverse r2cf $rat ) }   # The task   say "First twenty terms of the Calkin-Wilf sequence: ", @calkin-wilf[1..20]».&prat.join: ', ';   say "\n99991st through 100000...
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...
#Ring
Ring
  # Project : Casting out nines   co9(1, 10, 99, [1,9,45,55,99]) co9(1, 10, 1000, [1,9,45,55,99,297,703,999])   func co9(start,base,lim,kaprekars) c1=0 c2=0 s = [] for k = start to lim c1 = c1 + 1 if k % (base-1) = (k*k) % (base-1) c2 = c2 + 1 add(s,k) ok next msg = "Valid subset" + ...
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...
#Ruby
Ruby
N = 2 base = 10 c1 = 0 c2 = 0   for k in 1 .. (base ** N) - 1 c1 = c1 + 1 if k % (base - 1) == (k * k) % (base - 1) then c2 = c2 + 1 print "%d " % [k] end end   puts print "Trying %d numbers instead of %d numbers saves %f%%" % [c2, c1, 100.0 - 100.0 * c2 / c1]
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...
#Racket
Racket
  #lang racket (require math)   (for ([p1 (in-range 3 62)] #:when (prime? p1)) (for ([h3 (in-range 2 p1)]) (define g (+ p1 h3)) (let next ([d 1]) (when (< d g) (when (and (zero? (modulo (* g (- p1 1)) d)) (= (modulo (- (sqr p1)) h3) (modulo d h3))) (define p2 (+ 1 (q...
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...
#Raku
Raku
for (2..67).grep: *.is-prime -> \Prime1 { for 1 ^..^ Prime1 -> \h3 { my \g = h3 + Prime1; for 0 ^..^ h3 + Prime1 -> \d { if (h3 + Prime1) * (Prime1 - 1) %% d and -Prime1**2 % h3 == d % h3 { my \Prime2 = floor 1 + (Prime1 - 1) * g / d; next unless Prime2.i...
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article: ...
#Lua
Lua
  table.unpack = table.unpack or unpack -- 5.1 compatibility local nums = {1,2,3,4,5,6,7,8,9}   function add(a,b) return a+b end   function mult(a,b) return a*b end   function cat(a,b) return tostring(a)..tostring(b) end   local function reduce(fun,a,b,...) if ... then return reduce(fun,fun(a,b),...) ...
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using onl...
#Wren
Wren
var n = 15 var t = List.filled(n+2, 0) t[1] = 1 for (i in 1..n) { if (i > 1) for (j in i..2) t[j] = t[j] + t[j-1] t[i+1] = t[i] if (i > 0) for (j in i+1..2) t[j] = t[j] + t[j-1] System.write("%(t[i+1]-t[i]) ") } System.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...
#Ring
Ring
  dog = "Benjamin" doG = "Smokey" Dog = "Samba" DOG = "Bernie" see "The 4 dogs are : " + dog + ", " + doG + ", " + Dog + " and " + DOG + "."  
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language...
#Ruby
Ruby
module FiveDogs dog = "Benjamin" dOg = "Dogley" doG = "Fido" Dog = "Samba" # this constant is FiveDogs::Dog DOG = "Bernie" # this constant is FiveDogs::DOG   names = [dog, dOg, doG, Dog, DOG] names.uniq! puts "There are %d dogs named %s." % [names.length, names.join(", ")] puts puts "The local va...
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...
#Run_BASIC
Run BASIC
  dog$ = "Benjamin" doG$ = "Smokey" Dog$ = "Samba" DOG$ = "Bernie" print "The 4 dogs are "; dog$; ", "; 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...
#OCaml
OCaml
let rec product l1 l2 = match l1, l2 with | [], _ | _, [] -> [] | h1::t1, h2::t2 -> (h1,h2)::(product [h1] t2)@(product t1 l2) ;;   product [1;2] [3;4];; (*- : (int * int) list = [(1, 3); (1, 4); (2, 3); (2, 4)]*) product [3;4] [1;2];; (*- : (int * int) list = [(3, 1); (3, 2); (4, 1); (4, 2)]*) product [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...
#Elixir
Elixir
defmodule Catalan do def cat(n), do: div( factorial(2*n), factorial(n+1) * factorial(n) )   defp factorial(n), do: fac1(n,1)   defp fac1(0, acc), do: acc defp fac1(n, acc), do: fac1(n-1, n*acc)   def cat_r1(0), do: 1 def cat_r1(n), do: Enum.sum(for i <- 0..n-1, do: cat_r1(i) * cat_r1(n-1-i))   def cat_r2(...
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...
#Phix
Phix
without js -- (no class in p2js) class test string msg = "this is a test" procedure show() ?this.msg end procedure procedure inst() ?"this is dynamic" end procedure end class test t = new() t.show() -- prints "this is a test" t.inst() -- prints "this is dynamic" t.inst = t.show t.inst(...
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...
#PHP
PHP
// Static method MyClass::method($someParameter); // In PHP 5.3+, static method can be called on a string of the class name $foo = 'MyClass'; $foo::method($someParameter);     // Instance method $myInstance->method($someParameter);
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance m...
#PicoLisp
PicoLisp
(foo> MyClass) (foo> MyObject)
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...
#PicoLisp
PicoLisp
(load "@lib/gcc.l")   (gcc "x11" '("-lX11") 'xOpenDisplay 'xCloseDisplay)   #include <X11/Xlib.h>   any xOpenDisplay(any ex) { any x = evSym(cdr(ex)); // Get display name char display[bufSize(x)]; // Create a buffer for the name   bufString(x, display); // Upack the name return boxCnt((long)XOpenDis...
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...
#PowerBASIC
PowerBASIC
#INCLUDE "Win32API.inc"   FUNCTION PBMAIN () AS LONG DIM hWnd AS LONG DIM msg AS ASCIIZ * 14, titl AS ASCIIZ * 8   hWnd = LoadLibrary ("user32") msg = "Hello, world!" titl = "Example" IF ISTRUE (hWnd) THEN funcAddr& = GetProcAddress (hWnd, "MessageBoxA") IF ISTRUE (funcAddr&) THE...
http://rosettacode.org/wiki/Burrows%E2%80%93Wheeler_transform
Burrows–Wheeler transform
This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Burrows–Wheeler transform (BWT, also called block-s...
#C.2B.2B
C++
#include <algorithm> #include <iostream> #include <vector>   const int STX = 0x02; const int ETX = 0x03;   void rotate(std::string &a) { char t = a[a.length() - 1]; for (int i = a.length() - 1; i > 0; i--) { a[i] = a[i - 1]; } a[0] = t; }   std::string bwt(const std::string &s) { for (char c...
http://rosettacode.org/wiki/Caesar_cipher
Caesar cipher
Task Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates (either towards left or right) the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to...
#8th
8th
\ Ensure the output char is in the correct range: : modulate \ char base -- char tuck n:- 26 n:+ 26 n:mod n:+ ;   \ Symmetric Caesar cipher. Input is text and number of characters to advance \ (or retreat, if negative). That value should be in the range 1..26 : caesar \ intext key -- outext >r ( \ Ignore ...
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
#C.23
C#
using System;   namespace CalculateE { class Program { public const double EPSILON = 1.0e-15;   static void Main(string[] args) { ulong fact = 1; double e = 2.0; double e0; uint n = 2; do { e0 = e; fact *= n+...
http://rosettacode.org/wiki/Bulls_and_cows/Player
Bulls and cows/Player
Task Write a player of the Bulls and Cows game, rather than a scorer. The player should give intermediate answers that respect the scores to previous attempts. One method is to generate a list of all possible numbers that could be the answer, then to prune the list by keeping only those numbers that would give an equ...
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h>   char *list; const char *line = "--------+--------------------\n"; int len = 0;   int irand(int n) { int r, rand_max = RAND_MAX - (RAND_MAX % n); do { r = rand(); } while(r >= rand_max); return r / (rand_max / n); }   char* get_digits(int ...
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers
Calendar - for "REAL" programmers
Task Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented   entirely without lowercase. Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide. (Hint: manually convert the code from the Calendar task to al...
#C
C
tcc -DSTRUCT=struct -DCONST=const -DINT=int -DCHAR=char -DVOID=void -DMAIN=main -DIF=if -DELSE=else -DWHILE=while -DFOR=for -DDO=do -DBREAK=break -DRETURN=return -DPUTCHAR=putchar UCCALENDAR.c
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...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   'Using StrDup function in Shlwapi.dll Dim As Any Ptr library = DyLibLoad("Shlwapi") Dim strdup As Function (ByVal As Const ZString Ptr) As ZString Ptr strdup = DyLibSymbol(library, "StrDupA")   'Using LocalFree function in kernel32.dll Dim As Any Ptr library2 = DyLibLoad("kernel32") Dim localfree As...
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...
#Go
Go
package main   // #include <string.h> // #include <stdlib.h> import "C" import ( "fmt" "unsafe" )   func main() { // a go string go1 := "hello C" // allocate in C and convert from Go representation to C representation c1 := C.CString(go1) // go string can now be garbage collected go1 = "...
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...
#Axe
Axe
NOARG() ARGS(1,5,42)
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#jq
jq
# cantor(width; height) def cantor($w; $h): def init: [range(0; $h) | [range(0; $w) | "*"]];   def cantor($start; $leng; $ix): ($leng/3|floor) as $seg | if $seg == 0 then . else reduce range($ix; $h) as $i (.; reduce range($start+$seg; $start + 2*$seg) as $j (.; .[$i][$j] = " ")) | ...
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#Julia
Julia
const width = 81 const height = 5   function cantor!(lines, start, len, idx) seg = div(len, 3) if seg > 0 for i in idx+1:height, j in start + seg + 1: start + seg * 2 lines[i, j] = ' ' end cantor!(lines, start, seg, idx + 1) cantor!(lines, start + 2 * seg, seg, idx + ...
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 ...
#REXX
REXX
/*REXX pgm finds the Nth value of the Calkin─Wilf sequence (which will be a fraction),*/ /*────────────────────── or finds which sequence number contains a specified fraction). */ numeric digits 2000 /*be able to handle ginormic integers. */ parse arg LO HI te . ...
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...
#Rust
Rust
fn compare_co9_efficiency(base: u64, upto: u64) { let naive_candidates: Vec<u64> = (1u64..upto).collect(); let co9_candidates: Vec<u64> = naive_candidates.iter().cloned() .filter(|&x| x % (base - 1) == (x * x) % (base - 1)) .collect(); for candidate in &co9_candidates { print!("{} ",...
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...
#Scala
Scala
  object kaprekar{ // PART 1 val co_base = ((x:Int,base:Int) => (x%(base-1) == (x*x)%(base-1))) //PART 2 def get_cands(n:Int,base:Int):List[Int] = { if(n==1) List[Int]() else if (co_base(n,base)) n :: get_cands(n-1,base) else ...
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...
#REXX
REXX
/*REXX program calculates Carmichael 3─strong pseudoprimes (up to and including N). */ numeric digits 18 /*handle big dig #s (9 is the default).*/ parse arg N .; if N=='' | N=="," then N=61 /*allow user to specify for the search.*/ tell= N>0; N= abs(N) ...
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: ...
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { Function Reduce (a, f) { if len(a)=0 then Error "Nothing to reduce" if len(a)=1 then =Array(a) : Exit k=each(a, 2, -1) m=Array(a) While k { m=f(m, array(k)) } =m } a=(1, 2, 3, 4, 5...
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: ...
#Maple
Maple
> nums := seq( 1 .. 10 ); nums := 1, 2, 3, 4, 5, 6, 7, 8, 9, 10   > foldl( `+`, 0, nums ); # compute sum using foldl 55   > foldr( `*`, 1, nums ); # compute product using foldr 3628800
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...
#Zig
Zig
  const std = @import("std"); const stdout = std.io.getStdOut().outStream();   pub fn main() !void { var n: u32 = 1; while (n <= 15) : (n += 1) { const row = binomial(n * 2).?; try stdout.print("{d:2} {d:8}\n", .{ n, row[n] - row[n + 1] }); } }   pub fn binomial(n: u32) ?[]const u64 { i...
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using onl...
#zkl
zkl
fcn binomial(n,k){ (1).reduce(k,fcn(p,i,n){ p*(n-i+1)/i },1,n) } (1).pump(15,List,fcn(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...
#Rust
Rust
fn main() { let dog = "Benjamin"; let Dog = "Samba"; let DOG = "Bernie"; println!("The three dogs are named {}, {} and {}.", 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...
#Sather
Sather
class MAIN is main is dog ::= "Benjamin"; Dog ::= "Samba"; DOG ::= "Bernie"; #OUT + #FMT("The three dogs are %s, %s and %s\n", dog, Dog, DOG); end; 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...
#Scala
Scala
val dog = "Benjamin" val Dog = "Samba" val DOG = "Bernie" println("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...
#Perl
Perl
sub cartesian { my $sets = shift @_; for (@$sets) { return [] unless @$_ }   my $products = [[]]; for my $set (reverse @$sets) { my $partial = $products; $products = []; for my $item (@$set) { for my $product (@$partial) { push @$products, [$item, @$pr...
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...
#Erlang
Erlang
-module(catalan).   -export([test/0]).   cat(N) -> factorial(2 * N) div (factorial(N+1) * factorial(N)).   factorial(N) -> fac1(N,1).   fac1(0,Acc) -> Acc; fac1(N,Acc) -> fac1(N-1, N * Acc).   cat_r1(0) -> 1; cat_r1(N) -> lists:sum([cat_r1(I)*cat_r1(N-1-I) || I <- lists:seq(0,N-1)]).   cat_r2(0) ...