task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.   Sequence A000108 on OEIS has a lot of information on Catalan Numbers. Related Tasks Pascal's triangle
#Ruby
Ruby
def catalan(num) t = [0, 1] #grows as needed (1..num).map do |i| i.downto(1){|j| t[j] += t[j-1]} t[i+1] = t[i] (i+1).downto(1) {|j| t[j] += t[j-1]} t[i+1] - t[i] end end   p catalan(15)
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.   Sequence A000108 on OEIS has a lot of information on Catalan Numbers. Related Tasks Pascal's triangle
#Run_BASIC
Run BASIC
n = 15 dim t(n+2) t(1) = 1 for i = 1 to n for j = i to 1 step -1  : t(j) = t(j) + t(j-1): next j t(i+1) = t(i) for j = i+1 to 1 step -1: t(j) = t(j) + t(j-1 : next j print t(i+1) - t(i);" "; next i
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#PARI.2FGP
PARI/GP
dog="Benjamin"; Dog="Samba"; DOG="Bernie"; printf("The three dogs are named %s, %s, and %s.", dog, Dog, DOG)
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#Pascal
Pascal
# These variables are all different $dog='Benjamin'; $Dog='Samba'; $DOG='Bernie'; print "The three dogs are named $dog, $Dog, and $DOG \n"
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists
Cartesian product of two or more lists
Task Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language. Demonstrate that your function/method correctly returns: {1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)} and, in contrast: {3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)} Also demonstrate, using your function/method, that the product of an empty list with any other list is empty. {1, 2} × {} = {} {} × {1, 2} = {} For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists. Use your n-ary Cartesian product function to show the following products: {1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1} {1, 2, 3} × {30} × {500, 100} {1, 2, 3} × {} × {500, 100}
#Kotlin
Kotlin
// version 1.1.2   fun flattenList(nestList: List<Any>): List<Any> { val flatList = mutableListOf<Any>()   fun flatten(list: List<Any>) { for (e in list) { if (e !is List<*>) flatList.add(e) else @Suppress("UNCHECKED_CAST") flatten(e as List<Any>) } }   flatten(nestList) return flatList }   operator fun List<Any>.times(other: List<Any>): List<List<Any>> { val prod = mutableListOf<List<Any>>() for (e in this) { for (f in other) { prod.add(listOf(e, f)) } } return prod }   fun nAryCartesianProduct(lists: List<List<Any>>): List<List<Any>> { require(lists.size >= 2) return lists.drop(2).fold(lists[0] * lists[1]) { cp, ls -> cp * ls }.map { flattenList(it) } }   fun printNAryProduct(lists: List<List<Any>>) { println("${lists.joinToString(" x ")} = ") println("[") println(nAryCartesianProduct(lists).joinToString("\n ", " ")) println("]\n") }   fun main(args: Array<String>) { println("[1, 2] x [3, 4] = ${listOf(1, 2) * listOf(3, 4)}") println("[3, 4] x [1, 2] = ${listOf(3, 4) * listOf(1, 2)}") println("[1, 2] x [] = ${listOf(1, 2) * listOf()}") println("[] x [1, 2] = ${listOf<Any>() * listOf(1, 2)}") println("[1, a] x [2, b] = ${listOf(1, 'a') * listOf(2, 'b')}") println() printNAryProduct(listOf(listOf(1776, 1789), listOf(7, 12), listOf(4, 14, 23), listOf(0, 1))) printNAryProduct(listOf(listOf(1, 2, 3), listOf(30), listOf(500, 100))) printNAryProduct(listOf(listOf(1, 2, 3), listOf<Int>(), listOf(500, 100))) printNAryProduct(listOf(listOf(1, 2, 3), listOf(30), listOf('a', 'b'))) }
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_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.} Or recursively: C 0 = 1 and C n + 1 = ∑ i = 0 n C i C n − i for  n ≥ 0 ; {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;} Or alternatively (also recursive): C 0 = 1 and C n = 2 ( 2 n − 1 ) n + 1 C n − 1 , {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},} Task Implement at least one of these algorithms and print out the first 15 Catalan numbers with each. Memoization   is not required, but may be worth the effort when using the second method above. Related tasks Catalan numbers/Pascal's triangle Evaluate binomial coefficients
#Crystal
Crystal
require "big" require "benchmark"   def factorial(n : BigInt) : BigInt (1..n).product(1.to_big_i) end   def factorial(n : Int32 | Int64) factorial n.to_big_i end   # direct   def catalan_direct(n) factorial(2*n) / (factorial(n + 1) * factorial(n)) end   # recursive   def catalan_rec1(n) return 1 if n == 0 (0...n).reduce(0) do |sum, i| sum + catalan_rec1(i) * catalan_rec1(n - 1 - i) end end   def catalan_rec2(n) return 1 if n == 0 2*(2*n - 1) * catalan_rec2(n - 1) / (n + 1) end   # performance and results   Benchmark.bm do |b| b.report("catalan_direct") { 16.times { |n| catalan_direct(n) } } b.report("catalan_rec1") { 16.times { |n| catalan_rec1(n) } } b.report("catalan_rec2") { 16.times { |n| catalan_rec2(n) } } end   puts "\n direct rec1 rec2" 16.times { |n| puts "%2d :%9d%9d%9d" % [n, catalan_direct(n), catalan_rec1(n), catalan_rec2(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 method of a class.
#LFE
LFE
(defmodule aquarium (export all))   (defun fish-class (species) " This is the constructor that will be used most often, only requiring that one pass a 'species' string.   When the children are not defined, simply use an empty list. " (fish-class species ()))   (defun fish-class (species children) " This contructor is mostly useful as a way of abstracting out the id generation from the larger constructor. Nothing else uses fish-class/2 besides fish-class/1, so it's not strictly necessary.   When the id isn't know, generate one. " (let* (((binary (id (size 128))) (: crypto rand_bytes 16)) (formatted-id (car (: io_lib format '"~32.16.0b" (list id))))) (fish-class species children formatted-id)))   (defun fish-class (species children id) " This is the constructor used internally, once the children and fish id are known. " (let ((move-verb '"swam")) (lambda (method-name) (case method-name ('id (lambda (self) id)) ('species (lambda (self) species)) ('children (lambda (self) children)) ('info (lambda (self) (: io format '"id: ~p~nspecies: ~p~nchildren: ~p~n" (list (get-id self) (get-species self) (get-children self))))) ('move (lambda (self distance) (: io format '"The ~s ~s ~p feet!~n" (list species move-verb distance)))) ('reproduce (lambda (self) (let* ((child (fish-class species)) (child-id (get-id child)) (children-ids (: lists append (list children (list child-id)))) (parent-id (get-id self)) (parent (fish-class species children-ids parent-id))) (list parent child)))) ('children-count (lambda (self) (: erlang length children)))))))   (defun get-method (object method-name) " This is a generic function, used to call into the given object (class instance). " (funcall object method-name))   ; define object methods (defun get-id (object) (funcall (get-method object 'id) object))   (defun get-species (object) (funcall (get-method object 'species) object))   (defun get-info (object) (funcall (get-method object 'info) object))   (defun move (object distance) (funcall (get-method object 'move) object distance))   (defun reproduce (object) (funcall (get-method object 'reproduce) object))   (defun get-children (object) (funcall (get-method object 'children) object))   (defun get-children-count (object) (funcall (get-method object 'children-count) object))  
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 close to the ABI level and not at the normal API level. Related task OpenGL -- OpenGL is usually maintained as a shared library.
#Kotlin
Kotlin
#include <stdio.h> /* gcc -shared -fPIC -nostartfiles fakeimglib.c -o fakeimglib.so */ int openimage(const char *s) { static int handle = 100; fprintf(stderr, "opening %s\n", s); return handle++; }
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library
Call a function in a shared library
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level. Related task OpenGL -- OpenGL is usually maintained as a shared library.
#Lingo
Lingo
-- calculate CRC-32 checksum str = "The quick brown fox jumps over the lazy dog"   -- is shared library (in Director called "Xtra", a DLL in windows, a sharedLib in -- OS X) available? if ilk(xtra("Crypto"))=#xtra then   -- use shared library cx = xtra("Crypto").new() crc = cx.cx_crc32_string(str)   else   -- otherwise use (slower) pure lingo solution crcObj = script("CRC").new() crc = crcObj.crc32(str)   end if
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#ALGOL_68
ALGOL 68
BEGIN # calculate an approximation to e # LONG REAL epsilon = 1.0e-15; LONG INT fact := 1; LONG REAL e := 2; LONG INT n := 2; WHILE LONG REAL e0 = e; fact *:= n; n +:= 1; e +:= 1.0 / fact; ABS ( e - e0 ) >= epsilon DO SKIP OD; print( ( "e = ", fixed( e, -17, 15 ), newline ) ) END
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 result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap). Notes It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way. C++ and C solutions can take some other language to communicate with. It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative. See also   Use another language to call a function
#C.2B.2B
C++
FUNCTION MULTIPLY(X, Y) DOUBLE PRECISION MULTIPLY, X, Y
http://rosettacode.org/wiki/Call_a_foreign-language_function
Call a foreign-language function
Task Show how a foreign language function can be called from the language. As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap). Notes It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way. C++ and C solutions can take some other language to communicate with. It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative. See also   Use another language to call a function
#Clojure
Clojure
(JNIDemo/callStrdup "Hello World!")
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   Calling a function with named arguments   Using a function in statement context   Using a function in first-class context within an expression   Obtaining the return value of a function   Distinguishing built-in functions and user-defined functions   Distinguishing subroutines and functions   Stating whether arguments are passed by value or by reference   Is partial application possible and how This task is not about defining functions.
#ALGOL_68
ALGOL 68
# Note functions and subroutines are called procedures (or PROCs) in Algol 68 # # A function called without arguments: # f; # Algol 68 does not expect an empty parameter list for calls with no arguments, "f()" is a syntax error # # A function with a fixed number of arguments: # f(1, x);   # variable number of arguments: # # functions that accept an array as a parameter can effectively provide variable numbers of arguments # # a "literal array" (called a row-display in Algol 68) can be passed, as is often the case for the I/O # # functions - e.g.: # print( ( "the result is: ", r, " after ", n, " iterations", newline ) ); # the outer brackets indicate the parameters of print, the inner brackets indicates the contents are a "literal array" #   # ALGOL 68 does not support optional arguments, though in some cases an empty array could be passed to a function # # expecting an array, e.g.: # f( () );   # named arguments - see the Algol 68 sample in: http://rosettacode.org/wiki/Named_parameters #   # In "Talk:Call a function" a statement context is explained as "The function is used as an instruction (with a void context), rather than used within an expression." Based on that, the examples above are already in a statement context. Technically, when a function that returns other than VOID (i.e. is not a subroutine) is called in a statement context, the result of the call is "voided" i.e. discarded. If desired, this can be made explicit using a cast, e.g.: # VOID(f);   # A function's return value being used: # x := f(y);   # There is no distinction between built-in functions and user-defined functions. #   # A subroutine is simply a function that returns VOID. #   # If the function is declared with argument(s) of mode REF MODE, then those arguments are being passed by reference. # # Technically, all parameters are passed by value, however the value of a REF MODE is a reference... #
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#FreeBASIC
FreeBASIC
  Const ancho = 81 Const alto = 5 Dim Shared intervalo(alto, ancho) As String Dim As Integer i, j   Sub Cantor() Dim As Integer i, j For i = 0 To alto - 1 For j = 0 To ancho - 1 intervalo(i, j) = Chr(254) Next j Next i End Sub   Sub ConjCantor(inicio As Integer, longitud As Integer, indice As Integer) Dim As Integer i, j Dim segmento As Integer = longitud / 3 If segmento = 0 Then Return For i = indice To alto - 1 For j = inicio + segmento To inicio + segmento * 2 - 1 intervalo(i, j) = Chr(32) Next j Next i ConjCantor(inicio, segmento, indice + 1) ConjCantor(inicio + segmento * 2, segmento, indice + 1) End Sub   Cantor() ConjCantor(0, ancho, 1) For i = 0 To alto - 1 For j = 0 To ancho - 1 Print intervalo(i, j); Next j Print Next i End  
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 use a rational number data type. It is also possible, given a non-negative rational number, to determine where it appears in the sequence without calculating the sequence. The procedure is to get the continued fraction representation of the rational and use it as the run-length encoding of the binary representation of the term number, beginning from the end of the continued fraction. It only works if the number of terms in the continued fraction is odd- use either of the two equivalent representations to achieve this: [a0; a1, a2, ..., an] = [a0; a1, a2 ,..., an-1, 1] Example The fraction   9/4   has odd continued fraction representation     2; 3, 1,     giving a binary representation of   100011, which means   9/4   appears as the   35th   term of the sequence. Task part 2 Find the position of the number   83116/51639   in the Calkin-Wilf sequence. See also Wikipedia entry: Calkin-Wilf tree Continued fraction Continued fraction/Arithmetic/Construct from rational number
#Little_Man_Computer
Little Man Computer
  // Little Man Computer, for Rosetta Code. // Displays terms of Calkin-Wilf sequence up to the given index. // The chosen algorithm calculates the i-th term directly from i // (i.e. not using any previous terms). input INP // get number of terms from user BRZ exit // exit if 0 STA max_i // store maximum index LDA c1 // index := 1 next_i STA i // Write index followed by '->' OTX 3 // non-standard: minimum width 3, no new line LDA asc_hy OTC LDA asc_gt OTC // Find greatest power of 2 not exceeding i, // and count the number of binary digits in i. LDA c1 STA pwr2 loop2 STA nrDigits LDA i SUB pwr2 SUB pwr2 BRP double BRA part2 // jump out if next power of 2 would exceed i double LDA pwr2 ADD pwr2 STA pwr2 LDA nrDigits ADD c1 BRA loop2 // The nth term a/b is calculated from the binary digits of i. // The leading 1 is not used. part2 LDA c1 STA a // a := 1 STA b // b := 1 LDA i SUB pwr2 STA diff // Pre-decrement count, since leading 1 is not used dec_ct LDA nrDigits // count down the number of digits SUB c1 BRZ output // if all digits done, output the result STA nrDigits // We now want to compare diff with pwr2/2. // Since division is awkward in LMC, we compare 2*diff with pwr2. LDA diff // diff := 2*diff ADD diff STA diff SUB pwr2 // is diff >= pwr2 ? BRP digit_1 // binary digit is 1 if yes, 0 if no // If binary digit is 0 then set b := a + b LDA a ADD b STA b BRA dec_ct // If binary digit is 1 then update diff and set a := a + b digit_1 STA diff LDA a ADD b STA a BRA dec_ct // Now have nth term a/b. Write it to the output. output LDA a // write a OTX 1 // non-standard: minimum width 1; no new line LDA asc_sl // write slash OTC LDA b // write b OTX 11 // non-standard: minimum width 1; add new line LDA i // have we done maximum i yet? SUB max_i BRZ exit // if yes, exit LDA i // if no, increment i and loop back ADD c1 BRA next_i exit HLT // Constants c1 DAT 1 asc_hy DAT 45 asc_gt DAT 62 asc_sl DAT 47 // Variables i DAT max_i DAT pwr2 DAT nrDigits DAT diff DAT a DAT b DAT // end  
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 use a rational number data type. It is also possible, given a non-negative rational number, to determine where it appears in the sequence without calculating the sequence. The procedure is to get the continued fraction representation of the rational and use it as the run-length encoding of the binary representation of the term number, beginning from the end of the continued fraction. It only works if the number of terms in the continued fraction is odd- use either of the two equivalent representations to achieve this: [a0; a1, a2, ..., an] = [a0; a1, a2 ,..., an-1, 1] Example The fraction   9/4   has odd continued fraction representation     2; 3, 1,     giving a binary representation of   100011, which means   9/4   appears as the   35th   term of the sequence. Task part 2 Find the position of the number   83116/51639   in the Calkin-Wilf sequence. See also Wikipedia entry: Calkin-Wilf tree Continued fraction Continued fraction/Arithmetic/Construct from rational number
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[a] a[1] = 1; a[n_?(GreaterThan[1])] := a[n] = 1/(2 Floor[a[n - 1]] + 1 - a[n - 1]) a /@ Range[20]   ClearAll[a] a = 1; n = 1; Dynamic[n] done = False; While[! done, a = 1/(2 Floor[a] + 1 - a); n++; If[a == 83116/51639, Print[n]; Break[]; ] ]
http://rosettacode.org/wiki/Casting_out_nines
Casting out nines
Task   (in three parts) Part 1 Write a procedure (say c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} ) which implements Casting Out Nines as described by returning the checksum for x {\displaystyle x} . Demonstrate the procedure using the examples given there, or others you may consider lucky. Part 2 Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure: Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: Kaprekar numbers#Casting Out Nines (fast)). note that 318682 {\displaystyle 318682} has the same checksum as ( 101558 + 217124 {\displaystyle 101558+217124} ); note that 101558217124 {\displaystyle 101558217124} has the same checksum as ( 101558 + 217124 {\displaystyle 101558+217124} ) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes); note that this implies that for Kaprekar numbers the checksum of k {\displaystyle k} equals the checksum of k 2 {\displaystyle k^{2}} . Demonstrate that your procedure can be used to generate or filter a range of numbers with the property c o 9 ( k ) = c o 9 ( k 2 ) {\displaystyle {\mathit {co9}}(k)={\mathit {co9}}(k^{2})} and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. Part 3 Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing: c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} is the residual of x {\displaystyle x} mod 9 {\displaystyle 9} ; the procedure can be extended to bases other than 9. Demonstrate your algorithm by generating or filtering a range of numbers with the property k % ( B a s e − 1 ) == ( k 2 ) % ( B a s e − 1 ) {\displaystyle k\%({\mathit {Base}}-1)==(k^{2})\%({\mathit {Base}}-1)} and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. related tasks First perfect square in base N with N unique digits Kaprekar numbers
#Phix
Phix
with javascript_semantics procedure co9(integer start, integer base, integer lim, sequence kaprekars) integer c1=0, c2=0 sequence s = {} for k=start to lim do c1 += 1 if mod(k,base-1)=mod(k*k,base-1) then c2 += 1 s &= k end if end for string msg = "valid subset" for i=1 to length(kaprekars) do if not find(kaprekars[i],s) then msg = "***INVALID***" exit end if end for if length(s)>25 then s[10..-10] = {"..."} end if printf(1,"%V\nKaprekar numbers: %V - %s\n",{s,kaprekars,msg}) printf(1,"Trying %d numbers instead of %d saves %3.2f%%\n\n",{c2,c1,100-(c2/c1)*100}) end procedure co9(1, 10, 99, {1,9,45,55,99}) co9(0(17)10, 17, 17*17, {0(17)3d,0(17)d4,0(17)gg}) co9(1, 10, 1000, {1,9,45,55,99,297,703,999})
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 method based on   Carmichael numbers,   as suggested in   Notes by G.J.O Jameson March 2010. Task Find Carmichael numbers of the form: Prime1 × Prime2 × Prime3 where   (Prime1 < Prime2 < Prime3)   for all   Prime1   up to   61. (See page 7 of   Notes by G.J.O Jameson March 2010   for solutions.) Pseudocode For a given   P r i m e 1 {\displaystyle Prime_{1}} for 1 < h3 < Prime1 for 0 < d < h3+Prime1 if (h3+Prime1)*(Prime1-1) mod d == 0 and -Prime1 squared mod h3 == d mod h3 then Prime2 = 1 + ((Prime1-1) * (h3+Prime1)/d) next d if Prime2 is not prime Prime3 = 1 + (Prime1*Prime2/h3) next d if Prime3 is not prime next d if (Prime2*Prime3) mod (Prime1-1) not equal 1 Prime1 * Prime2 * Prime3 is a Carmichael Number related task Chernick's Carmichael numbers
#PARI.2FGP
PARI/GP
f(p)={ my(v=List(),q,r); for(h=2,p-1, for(d=1,h+p-1, if((h+p)*(p-1)%d==0 && Mod(p,h)^2==-d && isprime(q=(p-1)*(h+p)/d+1) && isprime(r=p*q\h+1)&&q*r%(p-1)==1, listput(v,p*q*r) ) ) ); Set(v) }; forprime(p=3,67,v=f(p); for(i=1,#v,print1(v[i]", ")))
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article:   Fold Wikipedia article:   Catamorphism
#J
J
/
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article:   Fold Wikipedia article:   Catamorphism
#Java
Java
import java.util.stream.Stream;   public class ReduceTask {   public static void main(String[] args) { System.out.println(Stream.of(1, 2, 3, 4, 5).mapToInt(i -> i).sum()); System.out.println(Stream.of(1, 2, 3, 4, 5).reduce(1, (a, b) -> a * b)); } }
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.   Sequence A000108 on OEIS has a lot of information on Catalan Numbers. Related Tasks Pascal's triangle
#Rust
Rust
    fn main() {let n=15usize; let mut t= [0; 17]; t[1]=1; let mut j:usize; for i in 1..n+1 { j=i; loop{ if j==1{ break; } t[j]=t[j] + t[j-1]; j=j-1; } t[i+1]= t[i]; j=i+1; loop{ if j==1{ break; } t[j]=t[j] + t[j-1]; j=j-1; } print!("{} ", t[i+1]-t[i]); } }  
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.   Sequence A000108 on OEIS has a lot of information on Catalan Numbers. Related Tasks Pascal's triangle
#Scala
Scala
def catalan(n: Int): Int = if (n <= 1) 1 else (0 until n).map(i => catalan(i) * catalan(n - i - 1)).sum   (1 to 15).map(catalan(_))
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#Perl
Perl
# These variables are all different $dog='Benjamin'; $Dog='Samba'; $DOG='Bernie'; print "The three dogs are named $dog, $Dog, and $DOG \n"
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#Phix
Phix
sequence dog = "Benjamin", Dog = "Samba", DOG = "Bernie" printf( 1, "The three dogs are named %s, %s and %s\n", {dog, Dog, DOG} )
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists
Cartesian product of two or more lists
Task Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language. Demonstrate that your function/method correctly returns: {1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)} and, in contrast: {3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)} Also demonstrate, using your function/method, that the product of an empty list with any other list is empty. {1, 2} × {} = {} {} × {1, 2} = {} For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists. Use your n-ary Cartesian product function to show the following products: {1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1} {1, 2, 3} × {30} × {500, 100} {1, 2, 3} × {} × {500, 100}
#langur
langur
writeln X([1, 2], [3, 4]) == [[1, 3], [1, 4], [2, 3], [2, 4]] writeln X([3, 4], [1, 2]) == [[3, 1], [3, 2], [4, 1], [4, 2]] writeln X([1, 2], []) == [] writeln X([], [1, 2]) == [] writeln()   writeln X [1776, 1789], [7, 12], [4, 14, 23], [0, 1] writeln()   writeln X [1, 2, 3], [30], [500, 100] writeln()   writeln X [1, 2, 3], [], [500, 100] writeln()
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_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.} Or recursively: C 0 = 1 and C n + 1 = ∑ i = 0 n C i C n − i for  n ≥ 0 ; {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;} Or alternatively (also recursive): C 0 = 1 and C n = 2 ( 2 n − 1 ) n + 1 C n − 1 , {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},} Task Implement at least one of these algorithms and print out the first 15 Catalan numbers with each. Memoization   is not required, but may be worth the effort when using the second method above. Related tasks Catalan numbers/Pascal's triangle Evaluate binomial coefficients
#D
D
import std.stdio, std.algorithm, std.bigint, std.functional, std.range;   auto product(R)(R r) { return reduce!q{a * b}(1.BigInt, r); }   const cats1 = sequence!((a, n) => iota(n+2, 2*n+1).product / iota(1, n+1).product)(1);   BigInt cats2a(in uint n) { alias mcats2a = memoize!cats2a; if (n == 0) return 1.BigInt; return n.iota.map!(i => mcats2a(i) * mcats2a(n - 1 - i)).sum; }   const cats2 = sequence!((a, n) => n.cats2a);   const cats3 = recurrence!q{ (4*n - 2) * a[n - 1] / (n + 1) }(1.BigInt);   void main() { foreach (cats; TypeTuple!(cats1, cats2, cats3)) cats.take(15).writeln; }
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 method of a class.
#Lingo
Lingo
-- call static method script("MyClass").foo()   -- call instance method obj = script("MyClass").new() obj.foo()
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#Logtalk
Logtalk
  % avoid infinite metaclass regression by % making the metaclass an instance of itself :- object(metaclass, instantiates(metaclass)).   :- public(me/1). me(Me) :- self(Me).   :- end_object.  
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#Lua
Lua
local object = { name = "foo", func = function (self) print(self.name) end }   object:func() -- with : sugar object.func(object) -- without : sugar
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library
Call a function in a shared library
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level. Related task OpenGL -- OpenGL is usually maintained as a shared library.
#Lua
Lua
alien = require("alien") msgbox = alien.User32.MessageBoxA msgbox:types({ ret='long', abi='stdcall', 'long', 'string', 'string', 'long' }) retval = msgbox(0, 'Please press Yes, No or Cancel', 'The Title', 3) print(retval) --> 6, 7 or 2
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library
Call a function in a shared library
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level. Related task OpenGL -- OpenGL is usually maintained as a shared library.
#Maple
Maple
> cfloor := define_external( floor, s::float[8], RETURN::float[8], LIB = "libm.so" ): > cfloor( 2.3 ); 2.
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#AppleScript
AppleScript
--------------- CALCULATING THE VALUE OF E ---------------- on run   sum(map(inverse, ¬ scanl(product, 1, enumFromTo(1, 16))))   --> 2.718281828459   end run   -- inverse :: Float -> Float on inverse(x) 1 / x end inverse   -- product :: Float -> Float -> Float on product(a, b) a * b end product     --------------------- GENERIC FUNCTIONS ---------------------   -- enumFromTo :: Int -> Int -> [Int] on enumFromTo(m, n) if m ≤ n then set lst to {} repeat with i from m to n set end of lst to i end repeat lst else {} end if end enumFromTo   -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from 1 to lng set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl   -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: First-class m => (a -> b) -> m (a -> b) on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn   -- map :: (a -> b) -> [a] -> [b] on map(f, xs) -- The list obtained by applying f -- to each element of xs. tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map   -- scanl :: (b -> a -> b) -> b -> [a] -> [b] on scanl(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs set lst to {startValue} repeat with i from 1 to lng set v to |λ|(v, item i of xs, i, xs) set end of lst to v end repeat return lst end tell end scanl   -- sum :: [Num] -> Num on sum(xs) script add on |λ|(a, b) a + b end |λ| end script   foldl(add, 0, xs) end sum
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 all UPPERCASE) This task also is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983. THE REAL PROGRAMMER'S NATURAL HABITAT "Taped to the wall is a line-printer Snoopy calender for the year 1969." Moreover this task is further inspired by the long lost corollary article titled: "Real programmers think in UPPERCASE"! Note: Whereas today we only need to worry about ASCII, UTF-8, UTF-16, UTF-32, UTF-7 and UTF-EBCDIC encodings, in the 1960s having code in UPPERCASE was often mandatory as characters were often stuffed into 36-bit words as 6 lots of 6-bit characters. More extreme words sizes include 60-bit words of the CDC 6000 series computers. The Soviets even had a national character set that was inclusive of all 4-bit, 5-bit, 6-bit & 7-bit depending on how the file was opened... And one rogue Soviet university went further and built a 1.5-bit based computer. Of course... as us Boomers have turned into Geezers we have become HARD OF HEARING, and suffer from chronic Presbyopia, hence programming in UPPERCASE is less to do with computer architecture and more to do with practically. :-) For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder. FYI: a nice ASCII art file of Snoopy can be found at textfiles.com. Save with a .txt extension. Trivia: The terms uppercase and lowercase date back to the early days of the mechanical printing press. Individual metal alloy casts of each needed letter, or punctuation symbol, were meticulously added to a press block, by hand, before rolling out copies of a page. These metal casts were stored and organized in wooden cases. The more often needed minuscule letters were placed closer to hand, in the lower cases of the work bench. The less often needed, capitalized, majuscule letters, ended up in the harder to reach upper cases.
#360_Assembly
360 Assembly
* CALENDAR FOR REAL PROGRAMMERS 05/03/2017 CALENDAR CSECT USING CALENDAR,R13 BASE REGISTER B 72(R15) SKIP MY SAVEAREA DC 17F'0' MY SAVEAREA STM R14,R12,12(R13) SAVE CALLER'S REGISTERS ST R13,4(R15) LINK BACKWARD ST R15,8(R13) LINK FORWARD LR R13,R15 SET ADDRESSABILITY L R4,YEAR YEAR SRDA R4,32 . D R4,=F'4' YEAR//4 LTR R4,R4 IF YEAR//4=0 BNZ LYNOT L R4,YEAR YEAR SRDA R4,32 . D R4,=F'100' YEAR//100 LTR R4,R4 IF YEAR//100=0 BNZ LY L R4,YEAR YEAR SRDA R4,32 . D R4,=F'400' IF YEAR//400 LTR R4,R4 IF YEAR//400=0 BNZ LYNOT LY MVC ML+2,=H'29' ML(2)=29 LEAPYEAR LYNOT SR R10,R10 LTD1=0 LA R6,1 I=1 LOOPI1 C R6,=F'31' DO I=1 TO 31 BH ELOOPI1 XDECO R6,XDEC EDIT I LA R14,TD1 TD1 AR R14,R10 TD1+LTD1 MVC 0(3,R14),XDEC+9 SUB(TD1,LTD1+1,3)=PIC(I,3) LA R10,3(R10) LTD1+3 LA R6,1(R6) I=I+1 B LOOPI1 ELOOPI1 LA R6,1 I=1 LOOPI2 C R6,=F'12' DO I=1 TO 12 BH ELOOPI2 ST R6,M M=I MVC D,=F'1' D=1 MVC YY,YEAR YY=YEAR L R4,M M C R4,=F'3' IF M<3 BNL GE3 L R2,M M LA R2,12(R2) M+12 ST R2,M M=M+12 L R2,YY YY BCTR R2,0 YY-1 ST R2,YY YY=YY-1 GE3 L R2,YY YY LR R1,R2 YY SRA R1,2 YY/4 AR R2,R1 YY+(YY/4) L R4,YY YY SRDA R4,32 . D R4,=F'100' YY/100 SR R2,R5 YY+(YY/4)-(YY/100) L R4,YY YY SRDA R4,32 . D R4,=F'400' YY/400 AR R2,R5 YY+(YY/4)-(YY/100)+(YY/400) A R2,D R2=YY+(YY/4)-(YY/100)+(YY/400)+D LA R5,153 153 M R4,M 153*M LA R5,8(R5) 153*M+8 D R4,=F'5' (153*M+8)/5 AR R5,R2 ((153*M+8)/5+R2 LA R4,0 . D R4,=F'7' R4=MOD(R5,7) 0=SUN 1=MON ... 6=SAT LTR R4,R4 IF J=0 BNZ JNE0 LA R4,7 J=7 JNE0 BCTR R4,0 J-1 MH R4,=H'3' J*3 LR R10,R4 J1=J*3 LR R1,R6 I SLA R1,1 *2 LH R11,ML-2(R1) ML(I) MH R11,=H'3' J2=ML(I)*3 MVC TD2,BLANK TD2=' ' LA R4,TD1 @TD1 LR R5,R11 J2 LA R2,TD2 @TD2 AR R2,R10 @TD2+J1 LR R3,R5 J2 MVCL R2,R4 SUB(TD2,J1+1,J2)=SUB(TD1,1,J2) LR R1,R6 I MH R1,=H'144' *144 LA R14,DA-144(R1) @DA(I) MVC 0(144,R14),TD2 DA(I)=TD2 LA R6,1(R6) I=I+1 B LOOPI2 ELOOPI2 XPRNT SNOOPY,132 PRINT SNOOPY L R1,YEAR YEAR XDECO R1,PG+56 EDIT YEAR XPRNT PG,L'PG PRINT YEAR MVC WDLINE,BLANK WDLINE=' ' LA R10,1 LWDLINE=1 LA R8,1 K=1 LOOPK3 C R8,=F'6' DO K=1 TO 6 BH ELOOPK3 LA R4,WDLINE @WDLINE AR R4,R10 +LWDLINE MVC 0(20,R4),WDNA SUB(WDLINE,LWDLINE+1,20)=WDNA LA R10,20(R10) LWDLINE=LWDLINE+20 C R8,=F'6' IF K<6 BNL ITERK3 LA R10,2(R10) LWDLINE=LWDLINE+2 ITERK3 LA R8,1(R8) K=K+1 B LOOPK3 ELOOPK3 LA R6,1 I=1 LOOPI4 C R6,=F'12' DO I=1 TO 12 BY 6 BH ELOOPI4 MVC MOLINE,BLANK MOLINE=' ' LA R10,6 LMOLINE=6 LR R8,R6 K=I LOOPK4 LA R2,5(R6) I+5 CR R8,R2 DO K=I TO I+5 BH ELOOPK4 LR R1,R8 K MH R1,=H'10' *10 LA R3,MO-10(R1) MO(K) LA R4,MOLINE @MOLINE AR R4,R10 +LMOLINE MVC 0(10,R4),0(R3) SUB(MOLINE,LMOLINE+1,10)=MO(K) LA R10,22(R10) LMOLINE=LMOLINE+22 LA R8,1(R8) K=K+1 B LOOPK4 ELOOPK4 XPRNT MOLINE,L'MOLINE PRINT MONTHS XPRNT WDLINE,L'WDLINE PRINT DAYS OF WEEK LA R7,1 J=1 LOOPJ4 C R7,=F'106' DO J=1 TO 106 BY 21 BH ELOOPJ4 MVC PG,BLANK CLEAR BUFFER LA R9,PG PGI=0 LR R8,R6 K=I LOOPK5 LA R2,5(R6) I+5 CR R8,R2 DO K=I TO I+5 BH ELOOPK5 LR R1,R8 K MH R1,=H'144' *144 LA R4,DA-144(R1) DA(K) BCTR R4,0 -1 AR R4,R7 +J MVC 0(21,R9),0(R4) SUBSTR(DA(K),J,21) LA R9,22(R9) PGI=PGI+22 LA R8,1(R8) K=K+1 B LOOPK5 ELOOPK5 XPRNT PG,L'PG PRINT BUFFER LA R7,21(R7) J=J+21 B LOOPJ4 ELOOPJ4 LA R6,6(R6) I=I+6 B LOOPI4 ELOOPI4 L R13,4(0,R13) RESTORE PREVIOUS SAVEAREA POINTER LM R14,R12,12(R13) RESTORE CALLER'S REGISTERS XR R15,R15 SET RETURN CODE TO 0 BR R14 RETURN TO CALLER SNOOPY DC CL57' ',CL18'INSERT SNOOPY HERE',CL57' ' YEAR DC F'1969' <== 1969 MO DC CL10' JANUARY ',CL10' FEBRUARY ',CL10' MARCH ' DC CL10' APRIL ',CL10' MAY ',CL10' JUNE ' DC CL10' JULY ',CL10' AUGUST ',CL10'SEPTEMBER ' DC CL10' OCTOBER ',CL10' NOVEMBER ',CL10' DECEMBER ' ML DC H'31',H'28',H'31',H'30',H'31',H'30' DC H'31',H'31',H'30',H'31',H'30',H'31' WDNA DC CL20'MO TU WE TH FR SA SU' M DS F D DS F YY DS F TD1 DS CL93 TD2 DS CL144 MOLINE DS CL132 WDLINE DS CL132 PG DC CL132' ' BUFFER FOR THE LINE PRINTER XDEC DS CL12 BLANK DC CL144' ' DA DS 12CL144 YREGS END CALENDAR
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 result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap). Notes It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way. C++ and C solutions can take some other language to communicate with. It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative. See also   Use another language to call a function
#CMake
CMake
cmake_minimum_required(VERSION 2.6) project("outer project" C)   # Compile cmDIV. try_compile( compiled_div # result variable ${CMAKE_BINARY_DIR}/div # bindir ${CMAKE_SOURCE_DIR}/div # srcDir div) # projectName if(NOT compiled_div) message(FATAL_ERROR "Failed to compile cmDIV") endif()   # Load cmDIV. load_command(DIV ${CMAKE_BINARY_DIR}/div) if(NOT CMAKE_LOADED_COMMAND_DIV) message(FATAL_ERROR "Failed to load cmDIV") endif()   # Try div() command. div(quot rem 2012 500) message(" 2012 / 500 = ${quot} 2012 % 500 = ${rem} ")
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 result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap). Notes It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way. C++ and C solutions can take some other language to communicate with. It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative. See also   Use another language to call a function
#COBOL
COBOL
identification division. program-id. foreign.   data division. working-storage section. 01 hello. 05 value z"Hello, world". 01 duplicate usage pointer. 01 buffer pic x(16) based. 01 storage pic x(16).   procedure division. call "strdup" using hello returning duplicate on exception display "error calling strdup" upon syserr end-call if duplicate equal null then display "strdup returned null" upon syserr else set address of buffer to duplicate string buffer delimited by low-value into storage display function trim(storage) call "free" using by value duplicate on exception display "error calling free" upon syserr end-if goback.
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   Calling a function with named arguments   Using a function in statement context   Using a function in first-class context within an expression   Obtaining the return value of a function   Distinguishing built-in functions and user-defined functions   Distinguishing subroutines and functions   Stating whether arguments are passed by value or by reference   Is partial application possible and how This task is not about defining functions.
#ALGOL_W
ALGOL W
% Note, in Algol W, functions are called procedures % % calling a function with no parameters: % f;   % calling a function with a fixed number of parameters % g( 1, 2.3, "4" );   % Algol W does not support optional parameters in general, however constructors for records can % % be called wither with parameters (one for each field in the record) or no parameters #   % Algol W does not support variable numbers of parameters, except for the built-in I/O functions # % Algol W does not support named arguments %   % A function can be used in a statement context by calling it, as in the examples above %   % First class context: A function can be passed as a parameter to another procedure, e.g.: % v := integrate( sin, 0, 1 ) % assuming a suitable definition of integrate % % Algol W does not support functions returning functions %   % obtaining the return value of a function: e.g.: % v := g( x, y, z );   % There is no syntactic distinction between user-defined and built-in functions %   % Subroutines and functions are both procedures, a subroutine is a procedure with no return type % % (called a proper procedure in Algol W) % % There is no syntactic distinction between a call to a function and a call to a subroutine % % other than the context %   % In Algol W, parameters are passed by value, result or value result. This must be stated in the % % definition of the function/subroutine. Value parameters are passed by value, result and value result % % are effectively passed by reference and assigned on function exit. Result parameters are "out" parameters % % and value result parameters are "in out". % % Algol W also has "name" parameters (not to be confused with named parameters). Functions with name % % parameters are somewhat like macros %   % Partial application is not possible in Algol W %
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#Go
Go
package main   import "fmt"   const ( width = 81 height = 5 )   var lines [height][width]byte   func init() { for i := 0; i < height; i++ { for j := 0; j < width; j++ { lines[i][j] = '*' } } }   func cantor(start, len, index int) { seg := len / 3 if seg == 0 { return } for i := index; i < height; i++ { for j := start + seg; j < start + 2 * seg; j++ { lines[i][j] = ' ' } } cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) }   func main() { cantor(0, width, 1) for _, line := range lines { fmt.Println(string(line[:])) } }
http://rosettacode.org/wiki/Calkin-Wilf_sequence
Calkin-Wilf sequence
The Calkin-Wilf sequence contains every nonnegative rational number exactly once. It can be calculated recursively as follows: a1 = 1 an+1 = 1/(2⌊an⌋+1-an) for n > 1 Task part 1 Show on this page terms 1 through 20 of the Calkin-Wilf sequence. To avoid floating point error, you may want to use a rational number data type. It is also possible, given a non-negative rational number, to determine where it appears in the sequence without calculating the sequence. The procedure is to get the continued fraction representation of the rational and use it as the run-length encoding of the binary representation of the term number, beginning from the end of the continued fraction. It only works if the number of terms in the continued fraction is odd- use either of the two equivalent representations to achieve this: [a0; a1, a2, ..., an] = [a0; a1, a2 ,..., an-1, 1] Example The fraction   9/4   has odd continued fraction representation     2; 3, 1,     giving a binary representation of   100011, which means   9/4   appears as the   35th   term of the sequence. Task part 2 Find the position of the number   83116/51639   in the Calkin-Wilf sequence. See also Wikipedia entry: Calkin-Wilf tree Continued fraction Continued fraction/Arithmetic/Construct from rational number
#Nim
Nim
type Fraction = tuple[num, den: uint32]   iterator calkinWilf(): Fraction = ## Yield the successive values of the sequence. var n, d = 1u32 yield (n, d) while true: n = 2 * (n div d) * d + d - n swap n, d yield (n, d)   proc `$`(fract: Fraction): string = ## Return the representation of a fraction. $fract.num & '/' & $fract.den   func `==`(a, b: Fraction): bool {.inline.} = ## Compare two fractions. Slightly faster than comparison of tuples. a.num == b.num and a.den == b.den   when isMainModule:   echo "The first 20 terms of the Calkwin-Wilf sequence are:" var count = 0 for an in calkinWilf(): inc count stdout.write $an & ' ' if count == 20: break stdout.write '\n'   const Target: Fraction = (83116u32, 51639u32) var index = 0 for an in calkinWilf(): inc index if an == Target: break echo "\nThe element ", $Target, " is at position ", $index, " in the sequence."
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 use a rational number data type. It is also possible, given a non-negative rational number, to determine where it appears in the sequence without calculating the sequence. The procedure is to get the continued fraction representation of the rational and use it as the run-length encoding of the binary representation of the term number, beginning from the end of the continued fraction. It only works if the number of terms in the continued fraction is odd- use either of the two equivalent representations to achieve this: [a0; a1, a2, ..., an] = [a0; a1, a2 ,..., an-1, 1] Example The fraction   9/4   has odd continued fraction representation     2; 3, 1,     giving a binary representation of   100011, which means   9/4   appears as the   35th   term of the sequence. Task part 2 Find the position of the number   83116/51639   in the Calkin-Wilf sequence. See also Wikipedia entry: Calkin-Wilf tree Continued fraction Continued fraction/Arithmetic/Construct from rational number
#Pascal
Pascal
  program CWTerms;   {------------------------------------------------------------------------------- FreePascal command-line program. Calculates the Calkin-Wilf sequence up to the specified maximum index, where the first term 1/1 has index 1. Command line format is: CWTerms <max_index>   The program demonstrates 3 algorithms for calculating the sequence: (1) Calculate term[2n] and term[2n + 1] from term[n] (2) Calculate term[n + 1] from term[n] (3) Calculate term[n] directly from n, without using other terms Algorithm 1 is called first, and stores the terms in an array. Then the program calls Algorithms 2 and 3, and checks that they agree with Algorithm 1. -------------------------------------------------------------------------------}   uses SysUtils;   type TRational = record Num, Den : integer; end;   var terms : array of TRational; max_index, k : integer;   // Routine to calculate array of terms up the the maiximum index procedure CalcTerms_algo_1(); var j, k : integer; begin SetLength( terms, max_index + 1); j := 1; // index to earlier term, from which current term is calculated k := 1; // index to current term terms[1].Num := 1; terms[1].Den := 1; while (k < max_index) do begin inc(k); if (k and 1) = 0 then begin // or could write "if not Odd(k)" terms[k].Num := terms[j].Num; terms[k].Den := terms[j].Num + terms[j].Den; end else begin terms[k].Num := terms[j].Num + terms[j].Den; terms[k].Den := terms[j].Den; inc(j); end; end; end;   // Method to get each term from the preceding term. // a/b --> b/(a + b - 2(a mod b)); function CheckTerms_algo_2() : boolean; var index, a, b, temp : integer; begin result := true; index := 1; a := 1; b := 1; while (index <= max_index) do begin if (a <> terms[index].Num) or (b <> terms[index].Den) then result := false; temp := a + b - 2*(a mod b); a := b; b := temp; inc( index) end; end;   // Mathod to calcualte each term from its index, without using other terms. function CheckTerms_algo_3() : boolean; var index, a, b, pwr2, idiv2 : integer; begin result := true; for index := 1 to max_index do begin   idiv2 := index div 2; pwr2 := 1; while (pwr2 <= idiv2) do pwr2 := pwr2 shl 1; a := 1; b := 1; while (pwr2 > 1) do begin pwr2 := pwr2 shr 1; if (pwr2 and index) = 0 then inc( b, a) else inc( a, b); end; if (a <> terms[index].Num) or (b <> terms[index].Den) then result := false; end; end;   begin // Read and validate maximum index max_index := SysUtils.StrToIntDef( paramStr(1), -1); // -1 if not an integer if (max_index <= 0) then begin WriteLn( 'Maximum index must be a positive integer'); exit; end;   // Calculate terms by algo 1, then check that algos 2 and 3 agree. CalcTerms_algo_1(); if not CheckTerms_algo_2() then begin WriteLn( 'Algorithm 2 failed'); exit; end; if not CheckTerms_algo_3() then begin WriteLn( 'Algorithm 3 failed'); exit; end;   // Display the terms for k := 1 to max_index do with terms[k] do WriteLn( SysUtils.Format( '%8d: %d/%d', [k, Num, Den])); end.  
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. Part 2 Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure: Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: Kaprekar numbers#Casting Out Nines (fast)). note that 318682 {\displaystyle 318682} has the same checksum as ( 101558 + 217124 {\displaystyle 101558+217124} ); note that 101558217124 {\displaystyle 101558217124} has the same checksum as ( 101558 + 217124 {\displaystyle 101558+217124} ) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes); note that this implies that for Kaprekar numbers the checksum of k {\displaystyle k} equals the checksum of k 2 {\displaystyle k^{2}} . Demonstrate that your procedure can be used to generate or filter a range of numbers with the property c o 9 ( k ) = c o 9 ( k 2 ) {\displaystyle {\mathit {co9}}(k)={\mathit {co9}}(k^{2})} and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. Part 3 Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing: c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} is the residual of x {\displaystyle x} mod 9 {\displaystyle 9} ; the procedure can be extended to bases other than 9. Demonstrate your algorithm by generating or filtering a range of numbers with the property k % ( B a s e − 1 ) == ( k 2 ) % ( B a s e − 1 ) {\displaystyle k\%({\mathit {Base}}-1)==(k^{2})\%({\mathit {Base}}-1)} and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. related tasks First perfect square in base N with N unique digits Kaprekar numbers
#Picat
Picat
go => Base10 = 10, foreach(N in [2,6]) casting_out_nines(Base10,N) end, nl, Base16 = 16, foreach(N in [2,6]) casting_out_nines(Base16,N) end, nl.   casting_out_nines(Base,N) => println([base=Base,n=N]), C1 = 0, C2 = 0, Ks = [], LimitN = 3, foreach(K in 1..Base**N-1) C1 := C1 + 1, if K mod (Base-1) == (K*K) mod (Base-1) then C2 := C2+1, if N <= LimitN then Ks := Ks ++ [K] end end end, if C2 <= 100 then println(ks=Ks) end, printf("Trying %d numbers instead of %d numbers saves %2.3f%%\n", C2, C1, 100 - ((C2/C1)*100)), nl.
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. Part 2 Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure: Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: Kaprekar numbers#Casting Out Nines (fast)). note that 318682 {\displaystyle 318682} has the same checksum as ( 101558 + 217124 {\displaystyle 101558+217124} ); note that 101558217124 {\displaystyle 101558217124} has the same checksum as ( 101558 + 217124 {\displaystyle 101558+217124} ) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes); note that this implies that for Kaprekar numbers the checksum of k {\displaystyle k} equals the checksum of k 2 {\displaystyle k^{2}} . Demonstrate that your procedure can be used to generate or filter a range of numbers with the property c o 9 ( k ) = c o 9 ( k 2 ) {\displaystyle {\mathit {co9}}(k)={\mathit {co9}}(k^{2})} and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. Part 3 Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing: c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} is the residual of x {\displaystyle x} mod 9 {\displaystyle 9} ; the procedure can be extended to bases other than 9. Demonstrate your algorithm by generating or filtering a range of numbers with the property k % ( B a s e − 1 ) == ( k 2 ) % ( B a s e − 1 ) {\displaystyle k\%({\mathit {Base}}-1)==(k^{2})\%({\mathit {Base}}-1)} and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. related tasks First perfect square in base N with N unique digits Kaprekar numbers
#PicoLisp
PicoLisp
(de kaprekar (N) (let L (cons 0 (chop (* N N))) (for ((I . R) (cdr L) R (cdr R)) (NIL (gt0 (format R))) (T (= N (+ @ (format (head I L)))) N) ) ) )   (de co9 (N) (until (> 9 (setq N (sum '((N) (unless (= "9" N) (format N))) (chop N) ) ) ) ) N )   (println 'Part1:) (println (= (co9 (+ 6395 1259)) (co9 (+ (co9 6395) (co9 1259))) ) )   (println 'Part2:) (println (filter '((N) (= (co9 N) (co9 (* N N)))) (range 1 100) ) ) (println (filter kaprekar (range 1 100)) )   (println 'Part3 '- 'base17:) (println (filter '((N) (= (% N 16) (% (* N N) 16))) (range 1 100) ) )   (bye)
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 method based on   Carmichael numbers,   as suggested in   Notes by G.J.O Jameson March 2010. Task Find Carmichael numbers of the form: Prime1 × Prime2 × Prime3 where   (Prime1 < Prime2 < Prime3)   for all   Prime1   up to   61. (See page 7 of   Notes by G.J.O Jameson March 2010   for solutions.) Pseudocode For a given   P r i m e 1 {\displaystyle Prime_{1}} for 1 < h3 < Prime1 for 0 < d < h3+Prime1 if (h3+Prime1)*(Prime1-1) mod d == 0 and -Prime1 squared mod h3 == d mod h3 then Prime2 = 1 + ((Prime1-1) * (h3+Prime1)/d) next d if Prime2 is not prime Prime3 = 1 + (Prime1*Prime2/h3) next d if Prime3 is not prime next d if (Prime2*Prime3) mod (Prime1-1) not equal 1 Prime1 * Prime2 * Prime3 is a Carmichael Number related task Chernick's Carmichael numbers
#Perl
Perl
use ntheory qw/forprimes is_prime vecprod/;   forprimes { my $p = $_; for my $h3 (2 .. $p-1) { my $ph3 = $p + $h3; for my $d (1 .. $ph3-1) { # Jameseon procedure page 6 next if ((-$p*$p) % $h3) != ($d % $h3); next if (($p-1)*$ph3) % $d; my $q = 1 + ($p-1)*$ph3 / $d; # Jameson eq 7 next unless is_prime($q); my $r = 1 + ($p*$q-1) / $h3; # Jameson eq 6 next unless is_prime($r); next unless ($q*$r) % ($p-1) == 1; printf "%2d x %5d x %5d = %s\n",$p,$q,$r,vecprod($p,$q,$r); } } } 3,61;
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:   Fold Wikipedia article:   Catamorphism
#JavaScript
JavaScript
var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];   function add(a, b) { return a + b; }   var summation = nums.reduce(add);   function mul(a, b) { return a * b; }   var product = nums.reduce(mul, 1);   var concatenation = nums.reduce(add, "");   console.log(summation, product, concatenation);
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.   Sequence A000108 on OEIS has a lot of information on Catalan Numbers. Related Tasks Pascal's triangle
#Scilab
Scilab
n=15 t=zeros(1,n+2) t(1)=1 for i=1:n for j=i+1:-1:2 t(j)=t(j)+t(j-1) end t(i+1)=t(i) for j=i+2:-1:2 t(j)=t(j)+t(j-1) end disp(t(i+1)-t(i)) end
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.   Sequence A000108 on OEIS has a lot of information on Catalan Numbers. Related Tasks Pascal's triangle
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func local const integer: N is 15; var array integer: t is [] (1) & N times 0; var integer: i is 0; var integer: j is 0; begin for i range 1 to N do for j range i downto 2 do t[j] +:= t[j - 1]; end for; t[i + 1] := t[i]; for j range i + 1 downto 2 do t[j] +:= t[j - 1]; end for; write(t[i + 1] - t[i] <& " "); end for; writeln; end func;
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 that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#PicoLisp
PicoLisp
(let (dog "Benjamin" Dog "Samba" DOG "Bernie") (prinl "The three dogs are named " dog ", " Dog " and " DOG) )
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#PL.2FI
PL/I
*process or(!) source xref attributes macro options; /********************************************************************* * Program to show that PL/I is case-insensitive * 28.05.2013 Walter Pachl *********************************************************************/ case: proc options(main); Dcl dog Char(20) Var; dog = "Benjamin"; Dog = "Samba"; DOG = "Bernie"; Put Edit(dog,Dog,DOG)(Skip,3(a,x(1))); End;
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 your function/method, that the product of an empty list with any other list is empty. {1, 2} × {} = {} {} × {1, 2} = {} For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists. Use your n-ary Cartesian product function to show the following products: {1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1} {1, 2, 3} × {30} × {500, 100} {1, 2, 3} × {} × {500, 100}
#Lua
Lua
local pk,upk = table.pack, table.unpack local getn = function(t)return #t end local const = function(k)return function(e) return k end end local function attachIdx(f)-- one-time-off function modifier local idx = 0 return function(e)idx=idx+1 ; return f(e,idx)end end   local function reduce(t,acc,f) for i=1,t.n or #t do acc=f(acc,t[i])end return acc end local function imap(t,f) local r = {n=t.n or #t, r=reduce, u=upk, m=imap} for i=1,r.n do r[i]=f(t[i])end return r end   local function prod(...) local ts = pk(...) local limit = imap(ts,getn) local idx, cnt = imap(limit,const(1)), 0 local max = reduce(limit,1,function(a,b)return a*b end) local function ret(t,i)return t[idx[i]] end return function() if cnt>=max then return end -- no more output if cnt==0 then -- skip for 1st cnt = cnt + 1 else cnt, idx[#idx] = cnt + 1, idx[#idx] + 1 for i=#idx,2,-1 do -- update index list if idx[i]<=limit[i] then break -- no further update need else -- propagate limit overflow idx[i],idx[i-1] = 1, idx[i-1]+1 end end end return cnt,imap(ts,attachIdx(ret)):u() end end --- test for i,a,b in prod({1,2},{3,4}) do print(i,a,b) end print() for i,a,b in prod({3,4},{1,2}) do print(i,a,b) end  
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_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.} Or recursively: C 0 = 1 and C n + 1 = ∑ i = 0 n C i C n − i for  n ≥ 0 ; {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;} Or alternatively (also recursive): C 0 = 1 and C n = 2 ( 2 n − 1 ) n + 1 C n − 1 , {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},} Task Implement at least one of these algorithms and print out the first 15 Catalan numbers with each. Memoization   is not required, but may be worth the effort when using the second method above. Related tasks Catalan numbers/Pascal's triangle Evaluate binomial coefficients
#Delphi
Delphi
func catalan n . ans . if n = 0 ans = 1 else call catalan n - 1 h ans = 2 * (2 * n - 1) * h div (1 + n) . . for i range 15 call catalan i h print h .
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { \\ A class definition is a function which return a Group \\ We can make groups and we can alter them using Group statement \\ Groups may have other groups inside   Group Alfa { Private: myvalue=100 Public: Group SetValue { Set (x) { Link parent myvalue to m m<=x } } Module MyMethod { Read x Print x*.myvalue } }   Alfa.MyMethod 5 '500 Alfa.MyMethod %x=200 ' 20000 \\ we can copy Alfa to Z Z=Alfa Z.MyMethod 5 Z.SetValue=300 Z.MyMethod 5 ' 1500 Alfa.MyMethod 5 ' 500 Dim A(10) A(3)=Z A(3).MyMethod 5 '1500 A(3).SetValue=200 A(3).MyMethod 5 '1000 \\ get a pointer of group in A(3) k->A(3) k=>SetValue=100 A(3).MyMethod 5 '500 \\ k get pointer to Alfa k->Alfa k=>SetValue=500 Alfa.MyMethod 5 '2500 k->Z k=>MyMethod 5 ' 1500 Z.SetValue=100 k=>MyMethod 5 ' 500 } Checkit  
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 method of a class.
#Maple
Maple
# Static Method( obj, other, arg );
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#MiniScript
MiniScript
Dog = {} Dog.name = "" Dog.help = function() print "This class represents dogs." end function Dog.speak = function() print self.name + " says Woof!" end function   fido = new Dog fido.name = "Fido"   Dog.help // calling a "class method" fido.speak // calling an "instance method"
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library
Call a function in a shared library
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level. Related task OpenGL -- OpenGL is usually maintained as a shared library.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Needs["NETLink`"]; externalFloor = DefineDLLFunction["floor", "msvcrt.dll", "double", { "double" }]; externalFloor[4.2] -> 4.
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library
Call a function in a shared library
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level. Related task OpenGL -- OpenGL is usually maintained as a shared library.
#Nim
Nim
proc openimage(s: cstring): cint {.importc, dynlib: "./fakeimglib.so".}   echo openimage("foo") echo openimage("bar") echo openimage("baz")
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#Applesoft_BASIC
Applesoft BASIC
?"E = "EXP(1)
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#Arturo
Arturo
fact: 1 e: 2.0 e0: 0.0 n: 2 lim: 0.0000000000000010   while [lim =< abs e-e0][ e0: e fact: fact * n n: n + 1 e: e + 1.0 / fact ]   print e
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers
Calendar - for "REAL" programmers
Task Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented   entirely without lowercase. Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide. (Hint: manually convert the code from the Calendar task to all UPPERCASE) This task also is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983. THE REAL PROGRAMMER'S NATURAL HABITAT "Taped to the wall is a line-printer Snoopy calender for the year 1969." Moreover this task is further inspired by the long lost corollary article titled: "Real programmers think in UPPERCASE"! Note: Whereas today we only need to worry about ASCII, UTF-8, UTF-16, UTF-32, UTF-7 and UTF-EBCDIC encodings, in the 1960s having code in UPPERCASE was often mandatory as characters were often stuffed into 36-bit words as 6 lots of 6-bit characters. More extreme words sizes include 60-bit words of the CDC 6000 series computers. The Soviets even had a national character set that was inclusive of all 4-bit, 5-bit, 6-bit & 7-bit depending on how the file was opened... And one rogue Soviet university went further and built a 1.5-bit based computer. Of course... as us Boomers have turned into Geezers we have become HARD OF HEARING, and suffer from chronic Presbyopia, hence programming in UPPERCASE is less to do with computer architecture and more to do with practically. :-) For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder. FYI: a nice ASCII art file of Snoopy can be found at textfiles.com. Save with a .txt extension. Trivia: The terms uppercase and lowercase date back to the early days of the mechanical printing press. Individual metal alloy casts of each needed letter, or punctuation symbol, were meticulously added to a press block, by hand, before rolling out copies of a page. These metal casts were stored and organized in wooden cases. The more often needed minuscule letters were placed closer to hand, in the lower cases of the work bench. The less often needed, capitalized, majuscule letters, ended up in the harder to reach upper cases.
#Ada
Ada
WITH PRINTABLE_CALENDAR;   PROCEDURE REAL_CAL IS   C: PRINTABLE_CALENDAR.CALENDAR := PRINTABLE_CALENDAR.INIT_132 ((WEEKDAY_REP => "MO TU WE TH FR SA SO", MONTH_REP => (" JANUARY ", " FEBRUARY ", " MARCH ", " APRIL ", " MAY ", " JUNE ", " JULY ", " AUGUST ", " SEPTEMBER ", " OCTOBER ", " NOVEMBER ", " DECEMBER ") ));   BEGIN C.PRINT_LINE_CENTERED("[SNOOPY]"); C.NEW_LINE; C.PRINT(1969, "NINETEEN-SIXTY-NINE"); END REAL_CAL;
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 result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap). Notes It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way. C++ and C solutions can take some other language to communicate with. It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative. See also   Use another language to call a function
#Common_Lisp
Common Lisp
CL-USER> (let* ((string "Hello World!") (c-string (cffi:foreign-funcall "strdup" :string string :pointer))) (unwind-protect (write-line (cffi:foreign-string-to-lisp c-string)) (cffi:foreign-funcall "free" :pointer c-string :void)) (values)) Hello World! ; No value
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   Calling a function with named arguments   Using a function in statement context   Using a function in first-class context within an expression   Obtaining the return value of a function   Distinguishing built-in functions and user-defined functions   Distinguishing subroutines and functions   Stating whether arguments are passed by value or by reference   Is partial application possible and how This task is not about defining functions.
#AntLang
AntLang
2*2+9
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#Groovy
Groovy
class App { private static final int WIDTH = 81 private static final int HEIGHT = 5   private static char[][] lines static { lines = new char[HEIGHT][WIDTH] for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { lines[i][j] = '*' } } }   private static void cantor(int start, int len, int index) { int seg = (int) (len / 3) if (seg == 0) return for (int i = index; i < HEIGHT; i++) { for (int j = start + seg; j < start + seg * 2; j++) { lines[i][j] = ' ' } } cantor(start, seg, index + 1) cantor(start + seg * 2, seg, index + 1) }   static void main(String[] args) { cantor(0, WIDTH, 1) for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { System.out.print(lines[i][j]) } System.out.println() } } }
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 use a rational number data type. It is also possible, given a non-negative rational number, to determine where it appears in the sequence without calculating the sequence. The procedure is to get the continued fraction representation of the rational and use it as the run-length encoding of the binary representation of the term number, beginning from the end of the continued fraction. It only works if the number of terms in the continued fraction is odd- use either of the two equivalent representations to achieve this: [a0; a1, a2, ..., an] = [a0; a1, a2 ,..., an-1, 1] Example The fraction   9/4   has odd continued fraction representation     2; 3, 1,     giving a binary representation of   100011, which means   9/4   appears as the   35th   term of the sequence. Task part 2 Find the position of the number   83116/51639   in the Calkin-Wilf sequence. See also Wikipedia entry: Calkin-Wilf tree Continued fraction Continued fraction/Arithmetic/Construct from rational number
#Perl
Perl
use strict; use warnings; use feature qw(say state);   use ntheory 'fromdigits'; use List::Lazy 'lazy_list'; use Math::AnyNum ':overload';   my $calkin_wilf = lazy_list { state @cw = 1; push @cw, 1 / ( (2 * int $cw[0]) + 1 - $cw[0] ); shift @cw };   sub r2cf { my($num, $den) = @_; my($n, @cf); my $f = sub { return unless $den; my $q = int($num/$den); ($num, $den) = ($den, $num - $q*$den); $q; }; push @cf, $n while defined($n = $f->()); reverse @cf; }   sub r2cw { my($num, $den) = @_; my $bits; my @f = r2cf($num, $den); $bits .= ($_%2 ? 0 : 1) x $f[$_] for 0..$#f; fromdigits($bits, 2); }   say 'First twenty terms of the Calkin-Wilf sequence:'; printf "%s ", $calkin_wilf->next() for 1..20; say "\n\n83116/51639 is at index: " . r2cw(83116,51639);
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. Part 2 Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure: Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: Kaprekar numbers#Casting Out Nines (fast)). note that 318682 {\displaystyle 318682} has the same checksum as ( 101558 + 217124 {\displaystyle 101558+217124} ); note that 101558217124 {\displaystyle 101558217124} has the same checksum as ( 101558 + 217124 {\displaystyle 101558+217124} ) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes); note that this implies that for Kaprekar numbers the checksum of k {\displaystyle k} equals the checksum of k 2 {\displaystyle k^{2}} . Demonstrate that your procedure can be used to generate or filter a range of numbers with the property c o 9 ( k ) = c o 9 ( k 2 ) {\displaystyle {\mathit {co9}}(k)={\mathit {co9}}(k^{2})} and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. Part 3 Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing: c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} is the residual of x {\displaystyle x} mod 9 {\displaystyle 9} ; the procedure can be extended to bases other than 9. Demonstrate your algorithm by generating or filtering a range of numbers with the property k % ( B a s e − 1 ) == ( k 2 ) % ( B a s e − 1 ) {\displaystyle k\%({\mathit {Base}}-1)==(k^{2})\%({\mathit {Base}}-1)} and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. related tasks First perfect square in base N with N unique digits Kaprekar numbers
#Python
Python
# Casting out Nines # # Nigel Galloway: June 27th., 2012, # def CastOut(Base=10, Start=1, End=999999): ran = [y for y in range(Base-1) if y%(Base-1) == (y*y)%(Base-1)] x,y = divmod(Start, Base-1) while True: for n in ran: k = (Base-1)*x + n if k < Start: continue if k > End: return yield k x += 1   for V in CastOut(Base=16,Start=1,End=255): print(V, 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 method based on   Carmichael numbers,   as suggested in   Notes by G.J.O Jameson March 2010. Task Find Carmichael numbers of the form: Prime1 × Prime2 × Prime3 where   (Prime1 < Prime2 < Prime3)   for all   Prime1   up to   61. (See page 7 of   Notes by G.J.O Jameson March 2010   for solutions.) Pseudocode For a given   P r i m e 1 {\displaystyle Prime_{1}} for 1 < h3 < Prime1 for 0 < d < h3+Prime1 if (h3+Prime1)*(Prime1-1) mod d == 0 and -Prime1 squared mod h3 == d mod h3 then Prime2 = 1 + ((Prime1-1) * (h3+Prime1)/d) next d if Prime2 is not prime Prime3 = 1 + (Prime1*Prime2/h3) next d if Prime3 is not prime next d if (Prime2*Prime3) mod (Prime1-1) not equal 1 Prime1 * Prime2 * Prime3 is a Carmichael Number related task Chernick's Carmichael numbers
#Phix
Phix
with javascript_semantics integer count = 0 for p1=1 to 61 do if is_prime(p1) then for h3=1 to p1 do atom h3p1 = h3 + p1 for d=1 to h3p1-1 do if mod(h3p1*(p1-1),d)=0 and mod(-(p1*p1),h3) = mod(d,h3) then atom p2 := 1 + floor(((p1-1)*h3p1)/d), p3 := 1 +floor(p1*p2/h3) if is_prime(p2) and is_prime(p3) and mod(p2*p3,p1-1)=1 then if count<5 or count>65 then printf(1,"%d * %d * %d = %d\n",{p1,p2,p3,p1*p2*p3}) elsif count=35 then puts(1,"...\n") end if count += 1 end if end if end for end for end if end for printf(1,"%d Carmichael numbers found\n",count)
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:   Fold Wikipedia article:   Catamorphism
#jq
jq
def factorial: reduce range(2;.+1) as $i (1; . * $i);
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article:   Fold Wikipedia article:   Catamorphism
#Julia
Julia
println([reduce(op, 1:5) for op in [+, -, *]]) println([foldl(op, 1:5) for op in [+, -, *]]) println([foldr(op, 1:5) for op in [+, -, *]])
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.   Sequence A000108 on OEIS has a lot of information on Catalan Numbers. Related Tasks Pascal's triangle
#Sidef
Sidef
func catalan(num) { var t = [0, 1] (1..num).map { |i| flip(^i ).each {|j| t[j+1] += t[j] } t[i+1] = t[i] flip(^i.inc).each {|j| t[j+1] += t[j] } t[i+1] - t[i] } }   say catalan(15).join(' ')
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.   Sequence A000108 on OEIS has a lot of information on Catalan Numbers. Related Tasks Pascal's triangle
#smart_BASIC
smart BASIC
PRINT "Catalan Numbers from Pascal's Triangle"!PRINT x = 15 DIM t(x+2) t(1) = 1 FOR n = 1 TO x FOR m = n TO 1 STEP -1 t(m) = t(m) + t(m-1) NEXT m t(n+1) = t(n) FOR m = n+1 TO 1 STEP -1 t(m) = t(m) + t(m-1) NEXT m PRINT n,"#######":t(n+1) - t(n) NEXT n
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#Plain_English
Plain English
To run: Start up. Put "Benjamin" into a DOG string. Put "Samba" into the Dog string. Put "Bernie" into the dog string. Write "There is just one dog named " then the DOG on the console. Wait for the escape key. Shut down.
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#PowerShell
PowerShell
  $dog = "Benjamin" $Dog = "Samba" $DOG = "Bernie"   "There is just one dog named {0}." -f $dOg  
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#Prolog
Prolog
three_dogs :- DoG = 'Benjamin', Dog = 'Samba', DOG = 'Bernie', format('The three dogs are named ~w, ~w and ~w.~n', [DoG, Dog, DOG]).  
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists
Cartesian product of two or more lists
Task Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language. Demonstrate that your function/method correctly returns: {1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)} and, in contrast: {3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)} Also demonstrate, using your function/method, that the product of an empty list with any other list is empty. {1, 2} × {} = {} {} × {1, 2} = {} For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists. Use your n-ary Cartesian product function to show the following products: {1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1} {1, 2, 3} × {30} × {500, 100} {1, 2, 3} × {} × {500, 100}
#Maple
Maple
  cartmulti := proc () local m, v; if [] in {args} then return []; else m := Iterator:-CartesianProduct(args); for v in m do printf("%{}a\n", v); end do; end if; end proc;  
http://rosettacode.org/wiki/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.} Or recursively: C 0 = 1 and C n + 1 = ∑ i = 0 n C i C n − i for  n ≥ 0 ; {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;} Or alternatively (also recursive): C 0 = 1 and C n = 2 ( 2 n − 1 ) n + 1 C n − 1 , {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},} Task Implement at least one of these algorithms and print out the first 15 Catalan numbers with each. Memoization   is not required, but may be worth the effort when using the second method above. Related tasks Catalan numbers/Pascal's triangle Evaluate binomial coefficients
#EasyLang
EasyLang
func catalan n . ans . if n = 0 ans = 1 else call catalan n - 1 h ans = 2 * (2 * n - 1) * h div (1 + n) . . for i range 15 call catalan i h print h .
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#Nanoquery
Nanoquery
class MyClass declare static id = 5 declare MyName   // constructor def MyClass(MyName) this.MyName = MyName end   // class method def getName() return this.MyName end   // static method def static getID() return id end end   // call the static method println MyClass.getID()   // instantiate a new MyClass object with the name "test" // and call the class method myclass = new(MyClass, "test") println myclass.getName()
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 method of a class.
#Nemerle
Nemerle
// Static MyClass.Method(someParameter);   // Instance myInstance.Method(someParameter);
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#NetRexx
NetRexx
SomeClass.staticMethod()
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library
Call a function in a shared library
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level. Related task OpenGL -- OpenGL is usually maintained as a shared library.
#OCaml
OCaml
open Dlffi   let get_int = function Int v -> v | _ -> failwith "get_int" let get_ptr = function Ptr v -> v | _ -> failwith "get_ptr" let get_float = function Float v -> v | _ -> failwith "get_float" let get_double = function Double v -> v | _ -> failwith "get_double" let get_string = function String v -> v | _ -> failwith "get_string"   let () = (* load the library *) let xlib = dlopen "/usr/lib/libX11.so" [RTLD_LAZY] in (* load the functions *) let _open_display = dlsym xlib "XOpenDisplay" and _default_screen = dlsym xlib "XDefaultScreen" and _display_width = dlsym xlib "XDisplayWidth" and _display_height = dlsym xlib "XDisplayHeight" in (* wrap functions to provide a higher level interface *) let open_display ~name = get_ptr(fficall _open_display [| String name |] Return_ptr) and default_screen ~dpy = get_int(fficall _default_screen [| (Ptr dpy) |] Return_int) and display_width ~dpy ~scr = get_int(fficall _display_width [| (Ptr dpy); (Int scr) |] Return_int) and display_height ~dpy ~scr = get_int(fficall _display_height [| (Ptr dpy); (Int scr) |] Return_int) in (* use our functions *) let dpy = open_display ~name:":0" in let screen_number = default_screen ~dpy in let width = display_width ~dpy ~scr:screen_number and height = display_height ~dpy ~scr:screen_number in Printf.printf "# Screen dimensions are: %d x %d pixels\n" width height; dlclose xlib; ;;
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#Asymptote
Asymptote
real n, n1; real e1, e;   n = 1.0; n1 = 1.0; e1 = 0.0; e = 1.0;   while (e != e1){ e1 = e; e += (1.0 / n); n1 += 1; n *= n1; } write("The value of e = ", e);
http://rosettacode.org/wiki/Calendar_-_for_%22REAL%22_programmers
Calendar - for "REAL" programmers
Task Provide an algorithm as per the Calendar task, except the entire code for the algorithm must be presented   entirely without lowercase. Also - as per many 1969 era line printers - format the calendar to nicely fill a page that is 132 characters wide. (Hint: manually convert the code from the Calendar task to all UPPERCASE) This task also is inspired by Real Programmers Don't Use PASCAL by Ed Post, Datamation, volume 29 number 7, July 1983. THE REAL PROGRAMMER'S NATURAL HABITAT "Taped to the wall is a line-printer Snoopy calender for the year 1969." Moreover this task is further inspired by the long lost corollary article titled: "Real programmers think in UPPERCASE"! Note: Whereas today we only need to worry about ASCII, UTF-8, UTF-16, UTF-32, UTF-7 and UTF-EBCDIC encodings, in the 1960s having code in UPPERCASE was often mandatory as characters were often stuffed into 36-bit words as 6 lots of 6-bit characters. More extreme words sizes include 60-bit words of the CDC 6000 series computers. The Soviets even had a national character set that was inclusive of all 4-bit, 5-bit, 6-bit & 7-bit depending on how the file was opened... And one rogue Soviet university went further and built a 1.5-bit based computer. Of course... as us Boomers have turned into Geezers we have become HARD OF HEARING, and suffer from chronic Presbyopia, hence programming in UPPERCASE is less to do with computer architecture and more to do with practically. :-) For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder. FYI: a nice ASCII art file of Snoopy can be found at textfiles.com. Save with a .txt extension. Trivia: The terms uppercase and lowercase date back to the early days of the mechanical printing press. Individual metal alloy casts of each needed letter, or punctuation symbol, were meticulously added to a press block, by hand, before rolling out copies of a page. These metal casts were stored and organized in wooden cases. The more often needed minuscule letters were placed closer to hand, in the lower cases of the work bench. The less often needed, capitalized, majuscule letters, ended up in the harder to reach upper cases.
#ALGOL_68
ALGOL 68
'PR' QUOTE 'PR'   'PROC' PRINT CALENDAR = ('INT' YEAR, PAGE WIDTH)'VOID': 'BEGIN'   ()'STRING' MONTH NAMES = ( "JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE", "JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"), WEEKDAY NAMES = ("SU","MO","TU","WE","TH","FR","SA"); 'FORMAT' WEEKDAY FMT = $G,N('UPB' WEEKDAY NAMES - 'LWB' WEEKDAY NAMES)(" "G)$;   # 'JUGGLE' THE CALENDAR FORMAT TO FIT THE PRINTER/SCREEN WIDTH # 'INT' DAY WIDTH = 'UPB' WEEKDAY NAMES(1), DAY GAP=1; 'INT' MONTH WIDTH = (DAY WIDTH+DAY GAP) * 'UPB' WEEKDAY NAMES-1; 'INT' MONTH HEADING LINES = 2; 'INT' MONTH LINES = (31 'OVER' 'UPB' WEEKDAY NAMES+MONTH HEADING LINES+2); # +2 FOR HEAD/TAIL WEEKS # 'INT' YEAR COLS = (PAGE WIDTH+1) 'OVER' (MONTH WIDTH+1); 'INT' YEAR ROWS = ('UPB' MONTH NAMES-1)'OVER' YEAR COLS + 1; 'INT' MONTH GAP = (PAGE WIDTH - YEAR COLS*MONTH WIDTH + 1)'OVER' YEAR COLS; 'INT' YEAR WIDTH = YEAR COLS*(MONTH WIDTH+MONTH GAP)-MONTH GAP; 'INT' YEAR LINES = YEAR ROWS*MONTH LINES;   'MODE' 'MONTHBOX' = (MONTH LINES, MONTH WIDTH)'CHAR'; 'MODE' 'YEARBOX' = (YEAR LINES, YEAR WIDTH)'CHAR';   'INT' WEEK START = 1; # 'SUNDAY' #   'PROC' DAYS IN MONTH = ('INT' YEAR, MONTH)'INT': 'CASE' MONTH 'IN' 31, 'IF' YEAR 'MOD' 4 'EQ' 0 'AND' YEAR 'MOD' 100 'NE' 0 'OR' YEAR 'MOD' 400 'EQ' 0 'THEN' 29 'ELSE' 28 'FI', 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 'ESAC';   'PROC' DAY OF WEEK = ('INT' YEAR, MONTH, DAY)'INT': 'BEGIN' # 'DAY' OF THE WEEK BY 'ZELLER'’S 'CONGRUENCE' ALGORITHM FROM 1887 # 'INT' Y := YEAR, M := MONTH, D := DAY, C; 'IF' M <= 2 'THEN' M +:= 12; Y -:= 1 'FI'; C := Y 'OVER' 100; Y 'MODAB' 100; (D - 1 + ((M + 1) * 26) 'OVER' 10 + Y + Y 'OVER' 4 + C 'OVER' 4 - 2 * C) 'MOD' 7 'END';   'MODE' 'SIMPLEOUT' = 'UNION'('STRING', ()'STRING', 'INT');   'PROC' CPUTF = ('REF'()'CHAR' OUT, 'FORMAT' FMT, 'SIMPLEOUT' ARGV)'VOID':'BEGIN' 'FILE' F; 'STRING' S; ASSOCIATE(F,S); PUTF(F, (FMT, ARGV)); OUT(:'UPB' S):=S; CLOSE(F) 'END';   'PROC' MONTH REPR = ('INT' YEAR, MONTH)'MONTHBOX':'BEGIN' 'MONTHBOX' MONTH BOX; 'FOR' LINE 'TO' 'UPB' MONTH BOX 'DO' MONTH BOX(LINE,):=" "* 2 'UPB' MONTH BOX 'OD'; 'STRING' MONTH NAME = MONTH NAMES(MONTH);   # CENTER THE TITLE # CPUTF(MONTH BOX(1,(MONTH WIDTH - 'UPB' MONTH NAME ) 'OVER' 2+1:), $G$, MONTH NAME); CPUTF(MONTH BOX(2,), WEEKDAY FMT, WEEKDAY NAMES);   'INT' FIRST DAY := DAY OF WEEK(YEAR, MONTH, 1); 'FOR' DAY 'TO' DAYS IN MONTH(YEAR, MONTH) 'DO' 'INT' LINE = (DAY+FIRST DAY-WEEK START) 'OVER' 'UPB' WEEKDAY NAMES + MONTH HEADING LINES + 1; 'INT' CHAR =((DAY+FIRST DAY-WEEK START) 'MOD' 'UPB' WEEKDAY NAMES)*(DAY WIDTH+DAY GAP) + 1; CPUTF(MONTH BOX(LINE,CHAR:CHAR+DAY WIDTH-1),$G(-DAY WIDTH)$, DAY) 'OD'; MONTH BOX 'END';   'PROC' YEAR REPR = ('INT' YEAR)'YEARBOX':'BEGIN' 'YEARBOX' YEAR BOX; 'FOR' LINE 'TO' 'UPB' YEAR BOX 'DO' YEAR BOX(LINE,):=" "* 2 'UPB' YEAR BOX 'OD'; 'FOR' MONTH ROW 'FROM' 0 'TO' YEAR ROWS-1 'DO' 'FOR' MONTH COL 'FROM' 0 'TO' YEAR COLS-1 'DO' 'INT' MONTH = MONTH ROW * YEAR COLS + MONTH COL + 1; 'IF' MONTH > 'UPB' MONTH NAMES 'THEN' DONE 'ELSE' 'INT' MONTH COL WIDTH = MONTH WIDTH+MONTH GAP; YEAR BOX( MONTH ROW*MONTH LINES+1 : (MONTH ROW+1)*MONTH LINES, MONTH COL*MONTH COL WIDTH+1 : (MONTH COL+1)*MONTH COL WIDTH-MONTH GAP ) := MONTH REPR(YEAR, MONTH) 'FI' 'OD' 'OD'; DONE: YEAR BOX 'END';   'INT' CENTER = (YEAR COLS*(MONTH WIDTH+MONTH GAP) - MONTH GAP - 1) 'OVER' 2; 'INT' INDENT = (PAGE WIDTH - YEAR WIDTH) 'OVER' 2;   PRINTF(( $N(INDENT + CENTER - 9)K G L$, "(INSERT SNOOPY HERE)", $N(INDENT + CENTER - 1)K 4D L$, YEAR, $L$, $N(INDENT)K N(YEAR WIDTH)(G) L$, YEAR REPR(YEAR) )) 'END';   MAIN: 'BEGIN' 'CO' INSPIRED BY HTTP://WWW.EE.RYERSON.CA/~ELF/hack/realmen.html REAL PROGRAMMERS DONT USE PASCAL - ED POST DATAMATION, VOLUME 29 NUMBER 7, JULY 1983 THE REAL PROGRAMMERS NATURAL HABITAT "TAPED TO THE WALL IS A LINE-PRINTER SNOOPY CALENDER FOR THE YEAR 1969" 'CO' 'INT' MANKIND STEPPED ON THE MOON = 1969, LINE PRINTER WIDTH = 132; # AS AT 1969! # PRINT CALENDAR(MANKIND STEPPED ON THE MOON, LINE PRINTER WIDTH) 'END'
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 result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap). Notes It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way. C++ and C solutions can take some other language to communicate with. It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative. See also   Use another language to call a function
#Crystal
Crystal
@[Link("c")] # name of library that is passed to linker. Not needed as libc is linked by stdlib. lib LibC fun free(ptr : Void*) : Void fun strdup(ptr : Char*) : Char* end   s1 = "Hello World!" p = LibC.strdup(s1) # returns Char* allocated by LibC s2 = String.new(p) LibC.free p # pointer can be freed as String.new(Char*) makes a copy of data   puts s2
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 result from strdup and print it using language means. Do not forget to free the result of strdup (allocated in the heap). Notes It is not mandated if the C run-time library is to be loaded statically or dynamically. You are free to use either way. C++ and C solutions can take some other language to communicate with. It is not mandatory to use strdup, especially if the foreign function interface being demonstrated makes that uninformative. See also   Use another language to call a function
#D
D
import std.stdio: writeln; import std.string: toStringz; import std.conv: to;   extern(C) { char* strdup(in char* s1); void free(void* ptr); }   void main() { // We could use char* here (as in D string literals are // null-terminated) but we want to comply with the "of the // string type typical to the language" part. // Note: D supports 0-values inside a string, C doesn't. auto input = "Hello World!";   // Method 1 (preferred): // toStringz converts D strings to null-terminated C strings. char* str1 = strdup(toStringz(input));   // Method 2: // D strings are not null-terminated, so we append '\0'. // .ptr returns a pointer to the 1st element of the array, // just as &array[0] // This has to be done because D dynamic arrays are // represented with: { size_t length; T* pointer; } char* str2 = strdup((input ~ '\0').ptr);   // We could have just used printf here, but the task asks to // "print it using language means": writeln("str1: ", to!string(str1)); writeln("str2: ", to!string(str2));   free(str1); free(str2); }
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   Calling a function with named arguments   Using a function in statement context   Using a function in first-class context within an expression   Obtaining the return value of a function   Distinguishing built-in functions and user-defined functions   Distinguishing subroutines and functions   Stating whether arguments are passed by value or by reference   Is partial application possible and how This task is not about defining functions.
#ARM_Assembly
ARM Assembly
    /* ARM assembly Raspberry PI */ /* program callfonct.s */   /* Constantes */ .equ STDOUT, 1 .equ WRITE, 4 .equ EXIT, 1   /***********************/ /* Initialized data */ /***********************/ .data szMessage: .asciz "Hello. \n" @ message szRetourLigne: .asciz "\n" szMessResult: .ascii "Resultat : " @ message result sMessValeur: .fill 12, 1, ' ' .asciz "\n" /***********************/ /* No Initialized data */ /***********************/ .bss iValeur: .skip 4 @ reserve 4 bytes in memory   .text .global main main: ldr r0,=szMessage @ adresse of message short program bl affichageMess @ call function with 1 parameter (r0)   @ call function with parameters in register mov r0,#5 mov r1,#10 bl fonction1 @ call function with 2 parameters (r0,r1) ldr r1,=sMessValeur @ result in r0 bl conversion10S @ call function with 2 parameter (r0,r1) ldr r0,=szMessResult bl affichageMess @ call function with 1 parameter (r0)   @ call function with parameters on stack mov r0,#5 mov r1,#10 push {r0,r1} bl fonction2 @ call function with 2 parameters on the stack @ result in r0 ldr r1,=sMessValeur bl conversion10S @ call function with 2 parameter (r0,r1) ldr r0,=szMessResult bl affichageMess @ call function with 1 parameter (r0)     /* end of program */ mov r0, #0 @ return code mov r7, #EXIT @ request to exit program swi 0 @ perform the system call   /******************************************************************/ /* call function parameter in register */ /******************************************************************/ /* r0 value one */ /* r1 value two */ /* return in r0 */ fonction1: push {fp,lr} /* save des 2 registres */ push {r1,r2} /* save des autres registres */ mov r2,#20 mul r0,r2 add r0,r0,r1 pop {r1,r2} /* restaur des autres registres */ pop {fp,lr} /* restaur des 2 registres */ bx lr /* retour procedure */   /******************************************************************/ /* call function parameter in the stack */ /******************************************************************/ /* return in r0 */ fonction2: push {fp,lr} /* save des 2 registres */ add fp,sp,#8 /* address parameters in the stack*/ push {r1,r2} /* save des autres registres */ ldr r0,[fp] ldr r1,[fp,#4] mov r2,#-20 mul r0,r2 add r0,r0,r1 pop {r1,r2} /* restaur des autres registres */ pop {fp,lr} /* restaur des 2 registres */ add sp,#8 /* very important, for stack aligned */ bx lr /* retour procedure */   /******************************************************************/ /* affichage des messages avec calcul longueur */ /******************************************************************/ /* r0 contient l adresse du message */ affichageMess: push {fp,lr} /* save des 2 registres */ push {r0,r1,r2,r7} /* save des autres registres */ mov r2,#0 /* compteur longueur */ 1: /*calcul de la longueur */ ldrb r1,[r0,r2] /* recup octet position debut + indice */ cmp r1,#0 /* si 0 c est fini */ beq 1f add r2,r2,#1 /* sinon on ajoute 1 */ b 1b 1: /* donc ici r2 contient la longueur du message */ mov r1,r0 /* adresse du message en r1 */ mov r0,#STDOUT /* code pour écrire sur la sortie standard Linux */ mov r7, #WRITE /* code de l appel systeme 'write' */ swi #0 /* appel systeme */ pop {r0,r1,r2,r7} /* restaur des autres registres */ pop {fp,lr} /* restaur des 2 registres */ bx lr /* retour procedure */ /***************************************************/ /* conversion registre en décimal signé */ /***************************************************/ /* r0 contient le registre */ /* r1 contient l adresse de la zone de conversion */ conversion10S: push {fp,lr} /* save des 2 registres frame et retour */ push {r0-r5} /* save autres registres */ mov r2,r1 /* debut zone stockage */ mov r5,#'+' /* par defaut le signe est + */ cmp r0,#0 /* nombre négatif ? */ movlt r5,#'-' /* oui le signe est - */ mvnlt r0,r0 /* et inversion en valeur positive */ addlt r0,#1   mov r4,#10 /* longueur de la zone */ 1: /* debut de boucle de conversion */ bl divisionpar10 /* division */ add r1,#48 /* ajout de 48 au reste pour conversion ascii */ strb r1,[r2,r4] /* stockage du byte en début de zone r5 + la position r4 */ sub r4,r4,#1 /* position précedente */ cmp r0,#0 bne 1b /* boucle si quotient different de zéro */ strb r5,[r2,r4] /* stockage du signe à la position courante */ subs r4,r4,#1 /* position précedente */ blt 100f /* si r4 < 0 fin */ /* sinon il faut completer le debut de la zone avec des blancs */ mov r3,#' ' /* caractere espace */ 2: strb r3,[r2,r4] /* stockage du byte */ subs r4,r4,#1 /* position précedente */ bge 2b /* boucle si r4 plus grand ou egal a zero */ 100: /* fin standard de la fonction */ pop {r0-r5} /*restaur des autres registres */ pop {fp,lr} /* restaur des 2 registres frame et retour */ bx lr   /***************************************************/ /* division par 10 signé */ /* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/* /* and http://www.hackersdelight.org/ */ /***************************************************/ /* r0 contient le dividende */ /* r0 retourne le quotient */ /* r1 retourne le reste */ divisionpar10: /* r0 contains the argument to be divided by 10 */ push {r2-r4} /* save autres registres */ mov r4,r0 ldr r3, .Ls_magic_number_10 /* r1 <- magic_number */ smull r1, r2, r3, r0 /* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) */ mov r2, r2, ASR #2 /* r2 <- r2 >> 2 */ mov r1, r0, LSR #31 /* r1 <- r0 >> 31 */ add r0, r2, r1 /* r0 <- r2 + r1 */ add r2,r0,r0, lsl #2 /* r2 <- r0 * 5 */ sub r1,r4,r2, lsl #1 /* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) */ pop {r2-r4} bx lr /* leave function */ .align 4 .Ls_magic_number_10: .word 0x66666667    
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#Haskell
Haskell
-------------------------- CANTOR ------------------------   cantor :: [(Bool, Int)] -> [(Bool, Int)] cantor = concatMap go where go (bln, n) | bln && 1 < n = let m = quot n 3 in [(True, m), (False, m), (True, m)] | otherwise = [(bln, n)]   --------------------------- TEST ------------------------- main :: IO () main = putStrLn $ cantorLines 5   ------------------------- DISPLAY ------------------------ cantorLines :: Int -> String cantorLines n = unlines $ showCantor <$> take n (iterate cantor [(True, 3 ^ pred n)])   showCantor :: [(Bool, Int)] -> String showCantor = concatMap $ uncurry (flip replicate . c) where c True = '*' c False = ' '
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 use a rational number data type. It is also possible, given a non-negative rational number, to determine where it appears in the sequence without calculating the sequence. The procedure is to get the continued fraction representation of the rational and use it as the run-length encoding of the binary representation of the term number, beginning from the end of the continued fraction. It only works if the number of terms in the continued fraction is odd- use either of the two equivalent representations to achieve this: [a0; a1, a2, ..., an] = [a0; a1, a2 ,..., an-1, 1] Example The fraction   9/4   has odd continued fraction representation     2; 3, 1,     giving a binary representation of   100011, which means   9/4   appears as the   35th   term of the sequence. Task part 2 Find the position of the number   83116/51639   in the Calkin-Wilf sequence. See also Wikipedia entry: Calkin-Wilf tree Continued fraction Continued fraction/Arithmetic/Construct from rational number
#Phix
Phix
with javascript_semantics requires("1.0.0") -- (new even() builtin) function calkin_wilf(integer len) sequence cw = repeat(0,len) integer n=0, d=1 for i=1 to len do {n,d} = {d,(floor(n/d)*2+1)*d-n} cw[i] = {n,d} end for return cw end function function odd_length(sequence cf) -- replace even length continued fraction with odd length equivalent -- if remainder(length(cf),2)=0 then if even(length(cf)) then cf[$] -= 1 cf &= 1 end if return cf end function function to_continued_fraction(sequence r) integer {a,b} = r sequence cf = {} while true do cf &= floor(a/b) {a, b} = {b, remainder(a,b)} if a=1 then exit end if end while cf = odd_length(cf) return cf end function function get_term_number(sequence cf) sequence b = {} integer d = 1 for i=1 to length(cf) do b &= repeat(d,cf[i]) d = 1-d end for integer t = bits_to_int(b) return t end function -- additional verification methods (2 of) function i_to_cf(integer i) -- sequence b = trim_tail(int_to_bits(i,32),0)&2, sequence b = int_to_bits(i)&2, cf = iff(b[1]=0?{0}:{}) while length(b)>1 do for j=2 to length(b) do if b[j]!=b[1] then cf &= j-1 b = b[j..$] exit end if end for end while cf = odd_length(cf) return cf end function function cf2r(sequence cf) integer n=0, d=1 for i=length(cf) to 2 by -1 do {n,d} = {d,n+d*cf[i]} end for return {n+cf[1]*d,d} end function function prettyr(sequence r) integer {n,d} = r return iff(d=1?sprintf("%d",n):sprintf("%d/%d",{n,d})) end function sequence cw = calkin_wilf(20) printf(1,"The first 20 terms of the Calkin-Wilf sequence are:\n") for i=1 to 20 do string s = prettyr(cw[i]), r = prettyr(cf2r(i_to_cf(i))) integer t = get_term_number(to_continued_fraction(cw[i])) printf(1,"%2d: %-4s [==> %2d: %-3s]\n", {i, s, t, r}) end for printf(1,"\n") sequence r = {83116,51639} sequence cf = to_continued_fraction(r) integer tn = get_term_number(cf) printf(1,"%d/%d is the %,d%s term of the sequence.\n", r&{tn,ord(tn)})
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. Part 2 Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure: Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: Kaprekar numbers#Casting Out Nines (fast)). note that 318682 {\displaystyle 318682} has the same checksum as ( 101558 + 217124 {\displaystyle 101558+217124} ); note that 101558217124 {\displaystyle 101558217124} has the same checksum as ( 101558 + 217124 {\displaystyle 101558+217124} ) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes); note that this implies that for Kaprekar numbers the checksum of k {\displaystyle k} equals the checksum of k 2 {\displaystyle k^{2}} . Demonstrate that your procedure can be used to generate or filter a range of numbers with the property c o 9 ( k ) = c o 9 ( k 2 ) {\displaystyle {\mathit {co9}}(k)={\mathit {co9}}(k^{2})} and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. Part 3 Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing: c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} is the residual of x {\displaystyle x} mod 9 {\displaystyle 9} ; the procedure can be extended to bases other than 9. Demonstrate your algorithm by generating or filtering a range of numbers with the property k % ( B a s e − 1 ) == ( k 2 ) % ( B a s e − 1 ) {\displaystyle k\%({\mathit {Base}}-1)==(k^{2})\%({\mathit {Base}}-1)} and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. related tasks First perfect square in base N with N unique digits Kaprekar numbers
#Quackery
Quackery
[ true unrot swap witheach [ over find over found not if [ dip not conclude ] ] drop ] is subset ( [ [ --> [ )   [ abs 0 swap [ 10 /mod rot + dup 8 > if [ 9 - ] swap dup 0 = until ] drop ] is co9 ( n --> n )   say "Part 1: Examples from Dr Math page." cr cr say "6395 1259 + = " 6395 1259 + echo cr say "6395 co9 = " 6395 co9 echo cr say "1259 co9 = " 1259 co9 echo cr say "5 8 + co9 = " 5 8 + co9 echo cr say "7654 co9 = " 7654 co9 echo cr cr   say "6395 1259 * = " 6395 1259 * echo cr say "6395 co9 = " 6395 co9 echo cr say "1259 co9 = " 1259 co9 echo cr say "5 8 * co9 = " 5 8 * co9 echo cr say "8051305 co9 = " 7654 co9 echo cr cr   say "Part 2: Kaprekar numbers." cr cr   say "Kaprekar numbers less than one hundred: " [] 100 times [ i^ kaprekar if [ i^ join ] ] dup echo cr say '0...99 with property "n co9 n 2 ** co9 =": ' [] 100 times [ i^ co9 i^ 2 ** co9 = if [ i^ join ] ] dup echo cr say "Is the former a subset of the latter? " subset iff [ say "Yes." ] else [ say "No." ] cr cr   say "Part 3: Same as Part 2, but base 17." cr cr   say "Kaprekar (base 17) numbers less than one hundred: " 17 base put [] 100 times [ i^ kaprekar if [ i^ join ] ] base release dup echo cr say '0...99 with property "n 16 mod n 2 ** 16 mod =": ' [] 100 times [ i^ 16 mod i^ 2 ** 16 mod = if [ i^ join ] ] dup echo cr say "Is the former a subset of the latter? " subset iff [ say "Yes." ] else [ say "No." ]
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. Part 2 Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure: Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: Kaprekar numbers#Casting Out Nines (fast)). note that 318682 {\displaystyle 318682} has the same checksum as ( 101558 + 217124 {\displaystyle 101558+217124} ); note that 101558217124 {\displaystyle 101558217124} has the same checksum as ( 101558 + 217124 {\displaystyle 101558+217124} ) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes); note that this implies that for Kaprekar numbers the checksum of k {\displaystyle k} equals the checksum of k 2 {\displaystyle k^{2}} . Demonstrate that your procedure can be used to generate or filter a range of numbers with the property c o 9 ( k ) = c o 9 ( k 2 ) {\displaystyle {\mathit {co9}}(k)={\mathit {co9}}(k^{2})} and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. Part 3 Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing: c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} is the residual of x {\displaystyle x} mod 9 {\displaystyle 9} ; the procedure can be extended to bases other than 9. Demonstrate your algorithm by generating or filtering a range of numbers with the property k % ( B a s e − 1 ) == ( k 2 ) % ( B a s e − 1 ) {\displaystyle k\%({\mathit {Base}}-1)==(k^{2})\%({\mathit {Base}}-1)} and show that this subset is a small proportion of the range and contains all the Kaprekar in the range. related tasks First perfect square in base N with N unique digits Kaprekar numbers
#Racket
Racket
#lang racket (require math)   (define (digits n) (map (compose1 string->number string) (string->list (number->string n))))   (define (cast-out-nines n) (with-modulus 9 (for/fold ([sum 0]) ([d (digits n)]) (mod+ sum d))))
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes
Carmichael 3 strong pseudoprimes
A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to investigate such numbers using a method based on   Carmichael numbers,   as suggested in   Notes by G.J.O Jameson March 2010. Task Find Carmichael numbers of the form: Prime1 × Prime2 × Prime3 where   (Prime1 < Prime2 < Prime3)   for all   Prime1   up to   61. (See page 7 of   Notes by G.J.O Jameson March 2010   for solutions.) Pseudocode For a given   P r i m e 1 {\displaystyle Prime_{1}} for 1 < h3 < Prime1 for 0 < d < h3+Prime1 if (h3+Prime1)*(Prime1-1) mod d == 0 and -Prime1 squared mod h3 == d mod h3 then Prime2 = 1 + ((Prime1-1) * (h3+Prime1)/d) next d if Prime2 is not prime Prime3 = 1 + (Prime1*Prime2/h3) next d if Prime3 is not prime next d if (Prime2*Prime3) mod (Prime1-1) not equal 1 Prime1 * Prime2 * Prime3 is a Carmichael Number related task Chernick's Carmichael numbers
#PicoLisp
PicoLisp
(de modulo (X Y) (% (+ Y (% X Y)) Y) )   (de prime? (N) (let D 0 (or (= N 2) (and (> N 1) (bit? 1 N) (for (D 3 T (+ D 2)) (T (> D (sqrt N)) T) (T (=0 (% N D)) NIL) ) ) ) ) )   (for P1 61 (when (prime? P1) (for (H3 2 (> P1 H3) (inc H3)) (let G (+ H3 P1) (for (D 1 (> G D) (inc D)) (when (and (=0 (% (* G (dec P1)) D) ) (= (modulo (* (- P1) P1) H3) (% D H3)) ) (let (P2 (inc (/ (* (dec P1) G) D) ) P3 (inc (/ (* P1 P2) H3)) ) (when (and (prime? P2) (prime? P3) (= 1 (modulo (* P2 P3) (dec P1))) ) (print (list P1 P2 P3)) ) ) ) ) ) ) ) ) (prinl)   (bye)
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 method based on   Carmichael numbers,   as suggested in   Notes by G.J.O Jameson March 2010. Task Find Carmichael numbers of the form: Prime1 × Prime2 × Prime3 where   (Prime1 < Prime2 < Prime3)   for all   Prime1   up to   61. (See page 7 of   Notes by G.J.O Jameson March 2010   for solutions.) Pseudocode For a given   P r i m e 1 {\displaystyle Prime_{1}} for 1 < h3 < Prime1 for 0 < d < h3+Prime1 if (h3+Prime1)*(Prime1-1) mod d == 0 and -Prime1 squared mod h3 == d mod h3 then Prime2 = 1 + ((Prime1-1) * (h3+Prime1)/d) next d if Prime2 is not prime Prime3 = 1 + (Prime1*Prime2/h3) next d if Prime3 is not prime next d if (Prime2*Prime3) mod (Prime1-1) not equal 1 Prime1 * Prime2 * Prime3 is a Carmichael Number related task Chernick's Carmichael numbers
#PL.2FI
PL/I
Carmichael: procedure options (main, reorder); /* 24 January 2014 */ declare (Prime1, Prime2, Prime3, h3, d) fixed binary (31);   put ('Carmichael numbers are:');   do Prime1 = 1 to 61;   do h3 = 2 to Prime1;   d_loop: do d = 1 to h3+Prime1-1; if (mod((h3+Prime1)*(Prime1-1), d) = 0) & (mod(-Prime1*Prime1, h3) = mod(d, h3)) then do; Prime2 = (Prime1-1) * (h3+Prime1)/d; Prime2 = Prime2 + 1; if ^is_prime(Prime2) then iterate d_loop; Prime3 = Prime1*Prime2/h3; Prime3 = Prime3 + 1; if ^is_prime(Prime3) then iterate d_loop; if mod(Prime2*Prime3, Prime1-1) ^= 1 then iterate d_loop; put skip edit (trim(Prime1), ' x ', trim(Prime2), ' x ', trim(Prime3)) (A); end; end; end; end;   /* Uses is_prime from Rosetta Code PL/I. */   end Carmichael;
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:   Fold Wikipedia article:   Catamorphism
#Kotlin
Kotlin
fun main(args: Array<String>) { val a = intArrayOf(1, 2, 3, 4, 5) println("Array  : ${a.joinToString(", ")}") println("Sum  : ${a.reduce { x, y -> x + y }}") println("Difference  : ${a.reduce { x, y -> x - y }}") println("Product  : ${a.reduce { x, y -> x * y }}") println("Minimum  : ${a.reduce { x, y -> if (x < y) x else y }}") println("Maximum  : ${a.reduce { x, y -> if (x > y) x else y }}") }
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 only addition.   Sequence A000108 on OEIS has a lot of information on Catalan Numbers. Related Tasks Pascal's triangle
#Tcl
Tcl
proc catalan n { set result {} array set t {0 0 1 1} for {set i 1} {[set k $i] <= $n} {incr i} { for {set j $i} {$j > 1} {} {incr t($j) $t([incr j -1])} set t([incr k]) $t($i) for {set j $k} {$j > 1} {} {incr t($j) $t([incr j -1])} lappend result [expr {$t($k) - $t($i)}] } return $result }   puts [catalan 15]
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 that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#PureBasic
PureBasic
dog$="Benjamin" Dog$="Samba" DOG$="Bernie" Debug "There is just one dog named "+dog$
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#Python
Python
>>> dog = 'Benjamin'; Dog = 'Samba'; DOG = 'Bernie' >>> print ('The three dogs are named ',dog,', ',Dog,', and ',DOG) The three dogs are named Benjamin , Samba , and Bernie >>>
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists
Cartesian product of two or more lists
Task Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language. Demonstrate that your function/method correctly returns: {1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)} and, in contrast: {3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)} Also demonstrate, using your function/method, that the product of an empty list with any other list is empty. {1, 2} × {} = {} {} × {1, 2} = {} For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists. Use your n-ary Cartesian product function to show the following products: {1776, 1789} × {7, 12} × {4, 14, 23} × {0, 1} {1, 2, 3} × {30} × {500, 100} {1, 2, 3} × {} × {500, 100}
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
cartesianProduct[args__] := Flatten[Outer[List, args], Length[{args}] - 1]
http://rosettacode.org/wiki/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C_{n}={\frac {1}{n+1}}{2n \choose n}={\frac {(2n)!}{(n+1)!\,n!}}\qquad {\mbox{ for }}n\geq 0.} Or recursively: C 0 = 1 and C n + 1 = ∑ i = 0 n C i C n − i for  n ≥ 0 ; {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n+1}=\sum _{i=0}^{n}C_{i}\,C_{n-i}\quad {\text{for }}n\geq 0;} Or alternatively (also recursive): C 0 = 1 and C n = 2 ( 2 n − 1 ) n + 1 C n − 1 , {\displaystyle C_{0}=1\quad {\mbox{and}}\quad C_{n}={\frac {2(2n-1)}{n+1}}C_{n-1},} Task Implement at least one of these algorithms and print out the first 15 Catalan numbers with each. Memoization   is not required, but may be worth the effort when using the second method above. Related tasks Catalan numbers/Pascal's triangle Evaluate binomial coefficients
#EchoLisp
EchoLisp
  (lib 'sequences) (lib 'bigint) (lib 'math)   ;; function definition (define (C1 n) (/ (factorial (* n 2)) (factorial (1+ n)) (factorial n))) (for ((i [1 .. 16])) (write (C1 i))) → 1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845   ;; using a recursive procedure with memoization (define (C2 n) ;; ( Σ ...)is the same as (sigma ..) (Σ (lambda(i) (* (C2 i) (C2 (- n i 1)))) 0 (1- n))) (remember 'C2 #(1)) ;; first term defined here   (for ((i [1 .. 16])) (write (C2 i))) → 1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845     ;; using procrastinators = infinite sequence (define (catalan n acc) (/ (* acc 2 (1- (* 2 n))) (1+ n))) (define C3 (scanl catalan 1 [1 ..])) (take C3 15) → (1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845)     ;; the same, using infix notation (lib 'match) (load 'infix.glisp)   (define (catalan n acc) ((2 * acc * ( 2 * n - 1)) / (n + 1))) (define C3 (scanl catalan 1 [1 ..]))   (take C3 15) → (1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845) ;; or (for ((c C3) (i 15)) (write c)) → 1 2 5 14 42 132 429 1430 4862 16796 58786 208012 742900 2674440 9694845  
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 method of a class.
#Nim
Nim
var x = @[1, 2, 3] add(x, 4) x.add(5)
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#OASYS_Assembler
OASYS Assembler
+&GO
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#Objeck
Objeck
  ClassName->some_function(); # call class function instance->some_method(); # call instance method
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library
Call a function in a shared library
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level. Related task OpenGL -- OpenGL is usually maintained as a shared library.
#Ol
Ol
  (import (otus ffi))   (define self (load-dynamic-library #f)) (define strdup (self type-string "strdup" type-string))   (print (strdup "Hello World!"))  
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library
Call a function in a shared library
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level. Related task OpenGL -- OpenGL is usually maintained as a shared library.
#OxygenBasic
OxygenBasic
  'Loading a shared library at run time and calling a function.   declare MessageBox(sys hWnd, String text,caption, sys utype)   sys user32 = LoadLibrary "user32.dll"   if user32 then @Messagebox = getProcAddress user32,"MessageBoxA"   if @MessageBox then MessageBox 0,"Hello","OxygenBasic",0   '...   FreeLibrary user32  
http://rosettacode.org/wiki/Burrows%E2%80%93Wheeler_transform
Burrows–Wheeler transform
This page uses content from Wikipedia. The original article was at Burrows–Wheeler_transform. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Burrows–Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters. This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding. More importantly, the transformation is reversible, without needing to store any additional data. The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation. Source: Burrows–Wheeler transform
#11l
11l
F bwt(String =s) ‘Apply Burrows-Wheeler transform to input string.’ assert("\002" !C s & "\003" !C s, ‘Input string cannot contain STX and ETX characters’) s = "\002"s"\003" V table = sorted((0 .< s.len).map(i -> @s[i..]‘’@s[0 .< i])) V last_column = table.map(row -> row[(len)-1..]) R last_column.join(‘’)   F ibwt(String r) ‘Apply inverse Burrows-Wheeler transform.’ V table = [‘’] * r.len L 0 .< r.len table = sorted((0 .< r.len).map(i -> @r[i]‘’@table[i])) V s = table.filter(row -> row.ends_with("\003"))[0] R s.rtrim("\003").trim("\002")   L(text) [‘banana’, ‘appellee’, ‘dogwood’, ‘TO BE OR NOT TO BE OR WANT TO BE OR NOT?’, ‘SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES’] V transformed = bwt(text) V invTransformed = ibwt(transformed)   print(‘Original text: ’text) print(‘After transformation: ’transformed.replace("\2", ‘^’).replace("\3", ‘|’)) print(‘After inverse transformation: ’invTransformed) print()
http://rosettacode.org/wiki/Calculating_the_value_of_e
Calculating the value of e
Task Calculate the value of   e. (e   is also known as   Euler's number   and   Napier's constant.) See details: Calculating the value of e
#AWK
AWK
  # syntax: GAWK -f CALCULATING_THE_VALUE_OF_E.AWK BEGIN { epsilon = 1.0e-15 fact = 1 e = 2.0 n = 2 do { e0 = e fact *= n++ e += 1.0 / fact } while (abs(e-e0) >= epsilon) printf("e=%.15f\n",e) exit(0) } function abs(x) { if (x >= 0) { return x } else { return -x } }