task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article:   Fold Wikipedia article:   Catamorphism
#Elena
Elena
import system'collections; import system'routines; import extensions; import extensions'text;   public program() { var numbers := new Range(1,10).summarize(new ArrayList());   var summary := numbers.accumulate(new Variable(0), (a,b => a + b));   var product := numbers.accumulate(new Variable(1), (a,b => a * b));   var concatenation := numbers.accumulate(new StringWriter(), (a,b => a.toPrintable() + b.toPrintable()));   console.printLine(summary," ",product," ",concatenation) }
http://rosettacode.org/wiki/Chaocipher
Chaocipher
Description The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010. The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here. Task Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
#Tailspin
Tailspin
  templates chaocipher&{left:,right:,decode:} templates permute def ctshift: [ [email protected]($..last)..., [email protected](1..$-1)...]; def p1: $ mod 26 + 1; def ptshift: [ [email protected]($p1..last)..., [email protected](1..$p1-1)...]; ..|@chaocipher: { ct: [ $ctshift(1), $ctshift(3..14)..., $ctshift(2), $ctshift(15..last)...], pt: [ $ptshift(1..2)..., $ptshift(4..14)..., $ptshift(3), $ptshift(15..last)...] }; end permute   @: {ct:[ $left... ], pt: [ $right... ], result:[]}; $... -> # '[email protected]...;' !   when <?($decode <=0>)> do def plain: $; def index: [email protected] -> \[i](<=$plain> $i!\) -> $(1); ..|@.result: [email protected]($index); $index -> permute -> !VOID otherwise def cipher: $; def index: [email protected] -> \[i](<=$cipher> $i!\) -> $(1); ..|@.result: [email protected]($index); $index -> permute -> !VOID end chaocipher   'WELLDONEISBETTERTHANWELLSAID' -> chaocipher&{left:'HXUCZVAMDSLKPEFJRIGTWOBNYQ', right:'PTLNBQDEOYSFAVZKGJRIHWXUMC',decode:0} -> '$; ' -> !OUT::write   'OAHQHCNYNXTSZJRRHJBYHQKSOUJY' -> chaocipher&{left:'HXUCZVAMDSLKPEFJRIGTWOBNYQ', right:'PTLNBQDEOYSFAVZKGJRIHWXUMC',decode:1} -> '$; ' -> !OUT::write  
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
#Nim
Nim
const n = 15 var t = newSeq[int](n + 2)   t[1] = 1 for i in 1..n: for j in countdown(i, 1): t[j] += t[j-1] t[i+1] = t[i] for j in countdown(i+1, 1): t[j] += t[j-1] stdout.write t[i+1] - t[i], " " stdout.write '\n'
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.   Sequence A000108 on OEIS has a lot of information on Catalan Numbers. Related Tasks Pascal's triangle
#OCaml
OCaml
  let catalan : int ref = ref 0 in Printf.printf "%d ," 1 ; for i = 2 to 9 do let nm : int ref = ref 1 in let den : int ref = ref 1 in for k = 2 to i do nm := (!nm)*(i+k); den := (!den)*k; catalan := (!nm)/(!den) ; done; print_int (!catalan); print_string "," ; done;;  
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#Liberty_BASIC
Liberty BASIC
  dog$ = "Benjamin" Dog$ = "Samba" DOG$ = "Bernie" print "The three dogs are "; dog$; ", "; Dog$; " and "; DOG$; "."   end  
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#Lua
Lua
dog = "Benjamin" Dog = "Samba" DOG = "Bernie"   print( "There are three dogs named "..dog..", "..Dog.." and "..DOG.."." )
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists
Cartesian product of two or more lists
Task Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language. Demonstrate that your function/method correctly returns: {1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)} and, in contrast: {3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)} Also demonstrate, using 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}
#Fortran
Fortran
  ! Created by simon on 29/04/2021.   ! ifort -o cartesian_product cartesian_product.f90 -check all   module tuple implicit none private public :: tuple_t, operator(*), print   type tuple_t(n) integer, len :: n integer, private :: v(n) contains procedure, public :: print => print_tuple_t generic, public :: assignment(=) => eq_tuple_t procedure, public :: eq_tuple_t end type tuple_t   interface print module procedure print_tuple_a_t end interface print interface operator(*) module procedure tup_times_tup end interface   contains subroutine eq_tuple_t(this, src) class(tuple_t(*)), intent(inout) :: this integer, intent(in) :: src(:) this%v = src end subroutine eq_tuple_t   pure function tup_times_tup(a, b) result(r) type(tuple_t(*)), intent(in) :: a type(tuple_t(*)), intent(in) :: b type(tuple_t(2)), allocatable :: r(:) integer :: i, j, k   allocate(r(a%n*b%n)) k = 0 do i=1,a%n do j=1,b%n k = k + 1 r(k)%v = [a%v(i),b%v(j)] end do end do end function tup_times_tup   subroutine print_tuple_t(this) class(tuple_t(*)), intent(in) :: this integer :: i write(*,fmt='(a)',advance='no') '{' do i=1,size(this%v) write(*,fmt='(i0)',advance='no') this%v(i) if (i < size(this%v)) write(*,fmt='(a)',advance='no') ',' end do write(*,fmt='(a)',advance='no') '}' end subroutine print_tuple_t   subroutine print_tuple_a_t(r) type(tuple_t(*)), intent(in) :: r(:) integer :: i write(*,fmt='(a)',advance='no') '{' do i=1,size(r) call r(i)%print if (i < size(r)) write(*,fmt='(a)',advance='no') ',' end do write(*,fmt='(a)') '}' end subroutine print_tuple_a_t end module tuple   program cartesian_product use tuple   implicit none type(tuple_t(2)) :: a, b type(tuple_t(0)) :: z   a = [1,2] b = [3,4]   call print_product(a, b) call print_product(b, a) call print_product(z, a) call print_product(a, z)   stop contains subroutine print_product(s, t) type(tuple_t(*)), intent(in) :: s type(tuple_t(*)), intent(in) :: t call s%print write(*,fmt='(a)',advance='no') ' x ' call t%print write(*,fmt='(a)',advance='no') ' = ' call print(s*t) end subroutine print_product end program cartesian_product  
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
#Befunge
Befunge
0>:.:000p1>\:00g-#v_v v 2-1*2p00 :+1g00\< $ > **00g1+/^v,*84,"="< _^#<`*53:+1>#,.#+5< @
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#COBOL
COBOL
*> INVOKE INVOKE FooClass "someMethod" RETURNING bar *> Factory object INVOKE foo-instance "anotherMethod" RETURNING bar *> Instance object   *> Inline method invocation MOVE FooClass::"someMethod" TO bar *> Factory object MOVE foo-instance::"anotherMethod" TO bar *> Instance object
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#CoffeeScript
CoffeeScript
class Foo @staticMethod: -> 'Bar'   instanceMethod: -> 'Baz'   foo = new Foo   foo.instanceMethod() #=> 'Baz' Foo.staticMethod() #=> 'Bar'
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#Common_Lisp
Common Lisp
(defclass my-class () ((x :accessor get-x ;; getter function :initarg :x ;; arg name :initform 0))) ;; initial value   ;; declaring a public class method (defmethod square-x ((class-instance my-class)) (* (get-x class-instance) (get-x class-instance)))   ;; create an instance of my-class (defvar *instance* (make-instance 'my-class :x 10))   (format t "Value of x: ~a~%" (get-x *instance*))   (format t "Value of x^2: ~a~%" (square-x *instance*))  
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.
#C
C
#include <stdio.h> #include <stdlib.h> #include <dlfcn.h>   int myopenimage(const char *in) { static int handle=0; fprintf(stderr, "internal openimage opens %s...\n", in); return handle++; }   int main() { void *imglib; int (*extopenimage)(const char *); int imghandle;   imglib = dlopen("./fakeimglib.so", RTLD_LAZY); if ( imglib != NULL ) { /* extopenimage = (int (*)(const char *))dlsym(imglib,...) "man dlopen" says that C99 standard leaves casting from "void *" to a function pointer undefined. The following is the POSIX.1-2003 workaround found in man */ *(void **)(&extopenimage) = dlsym(imglib, "openimage"); /* the following works with gcc, gives no warning even with -Wall -std=c99 -pedantic options... :D */ /* extopenimage = dlsym(imglib, "openimage"); */ imghandle = extopenimage("fake.img"); } else { imghandle = myopenimage("fake.img"); } printf("opened with handle %d\n", imghandle); /* ... */ if (imglib != NULL ) dlclose(imglib); return EXIT_SUCCESS; }
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#BASIC256
BASIC256
  global ancho, alto, intervalo ancho = 81 : alto = 5 dim intervalo(alto, ancho)   subroutine Cantor() for i = 0 to alto - 1 for j = 0 to ancho - 1 intervalo[i, j] = "■" next j next i end subroutine   subroutine ConjCantor(inicio, longitud, indice) segmento = longitud / 3 if segmento = 0 then return for i = indice to alto - 1 for j = inicio + segmento to inicio + segmento * 2 - 1 intervalo[i, j] = " " next j next i call ConjCantor(inicio, segmento, indice + 1) call ConjCantor(inicio + segmento * 2, segmento, indice + 1) end subroutine   call Cantor() call 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/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#BQN
BQN
Cantor ← {" •" ⊏˜ >⥊¨(¯1⊸⊏⊢¨¨⊢)1‿0‿1∧⌜⍟(↕𝕩)1}
http://rosettacode.org/wiki/Calkin-Wilf_sequence
Calkin-Wilf sequence
The Calkin-Wilf sequence contains every nonnegative rational number exactly once. It can be calculated recursively as follows: a1 = 1 an+1 = 1/(2⌊an⌋+1-an) for n > 1 Task part 1 Show on this page terms 1 through 20 of the Calkin-Wilf sequence. To avoid floating point error, you may want to 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
#Arturo
Arturo
n: new 1 d: new 1 calkinWilf: function [] .export:[n,d] [ n: (d - n) + 2 * (n/d) * d tmp: d d: n n: tmp return @[n d] ]   first20: [[1 1]] ++ map 1..19 => calkinWilf print "The first 20 terms of the Calkwin-Wilf sequence are:" print map first20 'f -> ~"|f\0|/|f\1|"   n: new 1 d: new 1 indx: new 1   target: [83116, 51639]   while ø [ inc 'indx if target = calkinWilf -> break ]   print "" print ["The element" ~"|target\0|/|target\1|" "is at position" indx "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
#BQN
BQN
GCD ← {m 𝕊⍟(0<m←𝕨|𝕩) 𝕨} _while_ ← {𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩} Sim ← { # Simplify a fraction x𝕊1: 𝕨‿1; 0𝕊y: 0‿𝕩; ⌊𝕨‿𝕩 ÷ 𝕨 GCD 𝕩 } Add ← { # Add two fractions 0‿b 𝕊 𝕩: 𝕩; 𝕨 𝕊 0‿y: 𝕨; a‿b 𝕊 x‿y: ((a×y)+x×b) Sim b×y } Next ← {n‿d: ⌽(2×⌊÷´n‿d)‿1 Add (d-n)‿d} # Next term Cal ← {Next⍟𝕩 1‿1}   •Show Cal 1+↕20   •Show { cnt‿fr: ⟨cnt+1,Next fr⟩ } _while_ { cnt‿fr: fr ≢ 83116‿51639 } ⟨1,1‿1⟩
http://rosettacode.org/wiki/Canny_edge_detector
Canny edge detector
Task Write a program that performs so-called canny edge detection on an image. A possible algorithm consists of the following steps: Noise reduction.   May be performed by Gaussian filter.   Compute intensity gradient   (matrices G x {\displaystyle G_{x}} and G y {\displaystyle G_{y}} )   and its magnitude   G {\displaystyle G} :           G = G x 2 + G y 2 {\displaystyle G={\sqrt {G_{x}^{2}+G_{y}^{2}}}} May be performed by convolution of an image with Sobel operators.   Non-maximum suppression.   For each pixel compute the orientation of intensity gradient vector:   θ = a t a n 2 ( G y , G x ) {\displaystyle \theta ={\rm {atan2}}\left(G_{y},\,G_{x}\right)} .     Transform   angle θ {\displaystyle \theta }   to one of four directions:   0, 45, 90, 135 degrees.     Compute new array   N {\displaystyle N} :     if         G ( p a ) < G ( p ) < G ( p b ) {\displaystyle G\left(p_{a}\right)<G\left(p\right)<G\left(p_{b}\right)} where   p {\displaystyle p}   is the current pixel,   p a {\displaystyle p_{a}}   and   p b {\displaystyle p_{b}}   are the two neighbour pixels in the direction of gradient,   then     N ( p ) = G ( p ) {\displaystyle N(p)=G(p)} ,       otherwise   N ( p ) = 0 {\displaystyle N(p)=0} .   Nonzero pixels in resulting array correspond to local maxima of   G {\displaystyle G}   in direction   θ ( p ) {\displaystyle \theta (p)} .   Tracing edges with hysteresis.   At this stage two thresholds for the values of   G {\displaystyle G}   are introduced:   T m i n {\displaystyle T_{min}}   and   T m a x {\displaystyle T_{max}} .   Starting from pixels with   N ( p ) ⩾ T m a x {\displaystyle N(p)\geqslant T_{max}} ,   find all paths of pixels with   N ( p ) ⩾ T m i n {\displaystyle N(p)\geqslant T_{min}}   and put them to the resulting image.
#Perl
Perl
# 20220120 Perl programming solution   use strict; use warnings;   use lib '/home/hkdtam/lib'; use Image::EdgeDetect;   my $detector = Image::EdgeDetect->new(); $detector->process('./input.jpg', './output.jpg') or die; # na.cx/i/pHYdUrV.jpg
http://rosettacode.org/wiki/Canny_edge_detector
Canny edge detector
Task Write a program that performs so-called canny edge detection on an image. A possible algorithm consists of the following steps: Noise reduction.   May be performed by Gaussian filter.   Compute intensity gradient   (matrices G x {\displaystyle G_{x}} and G y {\displaystyle G_{y}} )   and its magnitude   G {\displaystyle G} :           G = G x 2 + G y 2 {\displaystyle G={\sqrt {G_{x}^{2}+G_{y}^{2}}}} May be performed by convolution of an image with Sobel operators.   Non-maximum suppression.   For each pixel compute the orientation of intensity gradient vector:   θ = a t a n 2 ( G y , G x ) {\displaystyle \theta ={\rm {atan2}}\left(G_{y},\,G_{x}\right)} .     Transform   angle θ {\displaystyle \theta }   to one of four directions:   0, 45, 90, 135 degrees.     Compute new array   N {\displaystyle N} :     if         G ( p a ) < G ( p ) < G ( p b ) {\displaystyle G\left(p_{a}\right)<G\left(p\right)<G\left(p_{b}\right)} where   p {\displaystyle p}   is the current pixel,   p a {\displaystyle p_{a}}   and   p b {\displaystyle p_{b}}   are the two neighbour pixels in the direction of gradient,   then     N ( p ) = G ( p ) {\displaystyle N(p)=G(p)} ,       otherwise   N ( p ) = 0 {\displaystyle N(p)=0} .   Nonzero pixels in resulting array correspond to local maxima of   G {\displaystyle G}   in direction   θ ( p ) {\displaystyle \theta (p)} .   Tracing edges with hysteresis.   At this stage two thresholds for the values of   G {\displaystyle G}   are introduced:   T m i n {\displaystyle T_{min}}   and   T m a x {\displaystyle T_{max}} .   Starting from pixels with   N ( p ) ⩾ T m a x {\displaystyle N(p)\geqslant T_{max}} ,   find all paths of pixels with   N ( p ) ⩾ T m i n {\displaystyle N(p)\geqslant T_{min}}   and put them to the resulting image.
#PHP
PHP
  // input: r,g,b in range 0..255 function RGBtoHSV($r, $g, $b) { $r = $r/255.; // convert to range 0..1 $g = $g/255.; $b = $b/255.; $cols = array("r" => $r, "g" => $g, "b" => $b); asort($cols, SORT_NUMERIC); $min = key(array_slice($cols, 1)); // "r", "g" or "b" $max = key(array_slice($cols, -1)); // "r", "g" or "b"   // hue if($cols[$min] == $cols[$max]) { $h = 0; } else { if($max == "r") { $h = 60. * ( 0 + ( ($cols["g"]-$cols["b"]) / ($cols[$max]-$cols[$min]) ) ); } elseif ($max == "g") { $h = 60. * ( 2 + ( ($cols["b"]-$cols["r"]) / ($cols[$max]-$cols[$min]) ) ); } elseif ($max == "b") { $h = 60. * ( 4 + ( ($cols["r"]-$cols["g"]) / ($cols[$max]-$cols[$min]) ) ); } if($h < 0) { $h += 360; } }   // saturation if($cols[$max] == 0) { $s = 0; } else { $s = ( ($cols[$max]-$cols[$min])/$cols[$max] ); $s = $s * 255; }   // lightness $v = $cols[$max]; $v = $v * 255;   return(array($h, $s, $v)); }   $filename = "image.png"; $dimensions = getimagesize($filename); $w = $dimensions[0]; // width $h = $dimensions[1]; // height   $im = imagecreatefrompng($filename);   for($hi=0; $hi < $h; $hi++) {   for($wi=0; $wi < $w; $wi++) { $rgb = imagecolorat($im, $wi, $hi);   $r = ($rgb >> 16) & 0xFF; $g = ($rgb >> 8) & 0xFF; $b = $rgb & 0xFF; $hsv = RGBtoHSV($r, $g, $b);   // compare pixel below with current pixel $brgb = imagecolorat($im, $wi, $hi+1); $br = ($brgb >> 16) & 0xFF; $bg = ($brgb >> 8) & 0xFF; $bb = $brgb & 0xFF; $bhsv = RGBtoHSV($br, $bg, $bb);   // if difference in hue > 20, edge is detected if($hsv[2]-$bhsv[2] > 20) { imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 255, 0, 0)); } else { imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 0, 0, 0)); }   }   }   header('Content-Type: image/jpeg'); imagepng($im); imagedestroy($im);    
http://rosettacode.org/wiki/Canonicalize_CIDR
Canonicalize CIDR
Task Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form. That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address. Example Given   87.70.141.1/22,   your code should output   87.70.140.0/22 Explanation An Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 "digit" is represented by the digit value in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the "network" portion of the address, while the rightmost (least-significant) bits determine the "host" portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion. In general, CIDR blocks stand in for the entire set of IP addresses sharing the same "network" component; it's common to see access control lists specify a single IP address using CIDR with /32 to indicate that only the one address is included. Often, the tools using this notation expect the address to be entered in canonical form, in which the "host" bits are all zeroes in the binary representation. But careless network admins may provide CIDR blocks without canonicalizing them first. This task handles the canonicalization. The example address, 87.70.141.1, translates into 01010111010001101000110100000001 in binary notation zero-padded to 32 bits. The /22 means that the first 22 of those bits determine the match; the final 10 bits should be 0. But they instead include two 1 bits: 0100000001. So to canonicalize the address, change those 1's to 0's to yield 01010111010001101000110000000000, which in dotted-decimal is 87.70.140.0. More examples for testing 36.18.154.103/12 → 36.16.0.0/12 62.62.197.11/29 → 62.62.197.8/29 67.137.119.181/4 → 64.0.0.0/4 161.214.74.21/24 → 161.214.74.0/24 184.232.176.184/18 → 184.232.128.0/18
#JavaScript
JavaScript
const canonicalize = s => {   // Prepare a DataView over a 16 Byte Array buffer. // Initialised to all zeros. const dv = new DataView(new ArrayBuffer(16));   // Get the ip-address and cidr components const [ip, cidr] = s.split('/');   // Make sure the cidr component is a usable int, and // default to 32 if it does not exist. const cidrInt = parseInt(cidr || 32, 10);   // Populate the buffer with uint8 ip address components. // Use zero as the default for shorthand pool definitions. ip.split('.').forEach( (e, i) => dv.setUint8(i, parseInt(e || 0, 10)) );   // Grab the whole buffer as a uint32 const ipAsInt = dv.getUint32(0);   // Zero out the lower bits as per the CIDR number. const normIpInt = (ipAsInt >> 32 - cidrInt) << 32 - cidrInt;   // Plonk it back into the buffer dv.setUint32(0, normIpInt);   // Read each of the uint8 slots in the buffer and join them with a dot. const canonIp = [...'0123'].map((e, i) => dv.getUint8(i)).join('.');   // Attach the cidr number to the back of the normalised IP address. return [canonIp, cidrInt].join('/'); }   const test = s => console.log(s, '->', canonicalize(s)); [ '255.255.255.255/10', '87.70.141.1/22', '36.18.154.103/12', '62.62.197.11/29', '67.137.119.181/4', '161.214.74.21/24', '184.232.176.184/18', '10.207.219.251/32', '10.207.219.251', '110.200.21/4', '10..55/8', '10.../8' ].forEach(test)
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
#Java
Java
import java.util.*; import java.util.stream.IntStream;   public class CastingOutNines {   public static void main(String[] args) { System.out.println(castOut(16, 1, 255)); System.out.println(castOut(10, 1, 99)); System.out.println(castOut(17, 1, 288)); }   static List<Integer> castOut(int base, int start, int end) { int[] ran = IntStream .range(0, base - 1) .filter(x -> x % (base - 1) == (x * x) % (base - 1)) .toArray();   int x = start / (base - 1);   List<Integer> result = new ArrayList<>(); while (true) { for (int n : ran) { int k = (base - 1) * x + n; if (k < start) continue; if (k > end) return result; result.add(k); } x++; } } }
http://rosettacode.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
Catmull–Clark subdivision surface
Implement the Catmull-Clark surface subdivision (description on Wikipedia), which is an algorithm that maps from a surface (described as a set of points and a set of polygons with vertices at those points) to another more refined surface. The resulting surface will always consist of a mesh of quadrilaterals. The process for computing the new locations of the points works as follows when the surface is free of holes: Starting cubic mesh; the meshes below are derived from this. After one round of the Catmull-Clark algorithm applied to a cubic mesh. After two rounds of the Catmull-Clark algorithm. As can be seen, this is converging to a surface that looks nearly spherical. for each face, a face point is created which is the average of all the points of the face. for each edge, an edge point is created which is the average between the center of the edge and the center of the segment made with the face points of the two adjacent faces. for each vertex point, its coordinates are updated from (new_coords): the old coordinates (old_coords), the average of the face points of the faces the point belongs to (avg_face_points), the average of the centers of edges the point belongs to (avg_mid_edges), how many faces a point belongs to (n), then use this formula: m1 = (n - 3) / n m2 = 1 / n m3 = 2 / n new_coords = (m1 * old_coords) + (m2 * avg_face_points) + (m3 * avg_mid_edges) Then each face is replaced by new faces made with the new points, for a triangle face (a,b,c): (a, edge_pointab, face_pointabc, edge_pointca) (b, edge_pointbc, face_pointabc, edge_pointab) (c, edge_pointca, face_pointabc, edge_pointbc) for a quad face (a,b,c,d): (a, edge_pointab, face_pointabcd, edge_pointda) (b, edge_pointbc, face_pointabcd, edge_pointab) (c, edge_pointcd, face_pointabcd, edge_pointbc) (d, edge_pointda, face_pointabcd, edge_pointcd) When there is a hole, we can detect it as follows: an edge is the border of a hole if it belongs to only one face, a point is on the border of a hole if nfaces != nedges with nfaces the number of faces the point belongs to, and nedges the number of edges a point belongs to. On the border of a hole the subdivision occurs as follows: for the edges that are on the border of a hole, the edge point is just the middle of the edge. for the vertex points that are on the border of a hole, the new coordinates are calculated as follows: in all the edges the point belongs to, only take in account the middles of the edges that are on the border of the hole calculate the average between these points (on the hole boundary) and the old coordinates (also on the hole boundary). For edges and vertices not next to a hole, the standard algorithm from above is used.
#Wren
Wren
import "/dynamic" for Tuple, Struct import "/sort" for Sort import "/math" for Int import "/fmt" for Fmt   var Point = Tuple.create("Point", ["x", "y", "z"]) var fields = [ "pn1", // point number 1 "pn2", // point number 2 "fn1", // face number 1 "fn2", // face number 2 "cp" // center point ] var Edge = Tuple.create("Edge", fields) var PointEx = Struct.create("PointEx", ["p", "n"])   var sumPoint = Fn.new { |p1, p2| Point.new(p1.x + p2.x, p1.y + p2.y, p1.z + p2.z) }   var mulPoint = Fn.new { |p, m| Point.new(p.x * m, p.y * m, p.z * m) }   var divPoint = Fn.new { |p, d| mulPoint.call(p, 1/d) }   var centerPoint = Fn.new { |p1, p2| divPoint.call(sumPoint.call(p1, p2), 2) }   var getFacePoints = Fn.new { |inputPoints, inputFaces| var facePoints = List.filled(inputFaces.count, null) var i = 0 for (currFace in inputFaces) { var facePoint = Point.new(0, 0, 0) for (cpi in currFace) { var currPoint = inputPoints[cpi] facePoint = sumPoint.call(facePoint, currPoint) } facePoints[i] = divPoint.call(facePoint, currFace.count) i = i + 1 } return facePoints }   var getEdgesFaces = Fn.new { |inputPoints, inputFaces| var edges = [] var faceNum = 0 for (face in inputFaces) { var numPoints = face.count for (pointIndex in 0...numPoints) { var pointNum1 = face[pointIndex] var pointNum2 = (pointIndex < numPoints-1) ? face[pointIndex+1] : face[0] if (pointNum1 > pointNum2) { var t = pointNum1 pointNum1 = pointNum2 pointNum2 = t } edges.add([pointNum1, pointNum2, faceNum]) } faceNum = faceNum + 1 } var cmp = Fn.new { |e1, e2| if (e1[0] == e2[0]) { if (e1[1] == e2[1]) return (e1[2] - e2[2]).sign return (e1[1] - e2[1]).sign } return (e1[0] - e2[0]).sign } var numEdges = edges.count Sort.quick(edges, 0, numEdges-1, cmp) var eIndex = 0 var mergedEdges = [] while (eIndex < numEdges) { var e1 = edges[eIndex] if (eIndex < numEdges-1) { var e2 = edges[eIndex+1] if (e1[0] == e2[0] && e1[1] == e2[1]) { mergedEdges.add([e1[0], e1[1], e1[2], e2[2]]) eIndex = eIndex + 2 } else { mergedEdges.add([e1[0], e1[1], e1[2], -1]) eIndex = eIndex + 1 } } else { mergedEdges.add([e1[0], e1[1], e1[2], -1]) eIndex = eIndex + 1 } } var edgesCenters = [] for (me in mergedEdges) { var p1 = inputPoints[me[0]] var p2 = inputPoints[me[1]] var cp = centerPoint.call(p1, p2) edgesCenters.add(Edge.new(me[0], me[1], me[2], me[3], cp)) } return edgesCenters }   var getEdgePoints = Fn.new { |inputPoints, edgesFaces, facePoints| var edgePoints = List.filled(edgesFaces.count, null) var i = 0 for (edge in edgesFaces) { var cp = edge.cp var fp1 = facePoints[edge.fn1] var fp2 = (edge.fn2 == -1) ? fp1 : facePoints[edge.fn2] var cfp = centerPoint.call(fp1, fp2) edgePoints[i] = centerPoint.call(cp, cfp) i = i + 1 } return edgePoints }   var getAvgFacePoints = Fn.new { |inputPoints, inputFaces, facePoints| var numPoints = inputPoints.count var tempPoints = List.filled(numPoints, null) for (i in 0...numPoints) tempPoints[i] = PointEx.new(Point.new(0, 0, 0), 0) for (faceNum in 0...inputFaces.count) { var fp = facePoints[faceNum] for (pointNum in inputFaces[faceNum]) { var tp = tempPoints[pointNum].p tempPoints[pointNum].p = sumPoint.call(tp, fp) tempPoints[pointNum].n = tempPoints[pointNum].n + 1 } } var avgFacePoints = List.filled(numPoints, null) var i = 0 for (tp in tempPoints) { avgFacePoints[i] = divPoint.call(tp.p, tp.n) i = i + 1 } return avgFacePoints }   var getAvgMidEdges = Fn.new { |inputPoints, edgesFaces| var numPoints = inputPoints.count var tempPoints = List.filled(numPoints, null) for (i in 0...numPoints) tempPoints[i] = PointEx.new(Point.new(0, 0, 0), 0) for (edge in edgesFaces) { var cp = edge.cp for (pointNum in [edge.pn1, edge.pn2]) { var tp = tempPoints[pointNum].p tempPoints[pointNum].p = sumPoint.call(tp, cp) tempPoints[pointNum].n = tempPoints[pointNum].n + 1 } } var avgMidEdges = List.filled(tempPoints.count, null) var i = 0 for (tp in tempPoints) { avgMidEdges[i] = divPoint.call(tp.p, tp.n) i = i + 1 } return avgMidEdges }   var getPointsFaces = Fn.new { |inputPoints, inputFaces| var numPoints = inputPoints.count var pointsFaces = List.filled(numPoints, 0) for (faceNum in 0...inputFaces.count) { for (pointNum in inputFaces[faceNum]) { pointsFaces[pointNum] = pointsFaces[pointNum] + 1 } } return pointsFaces }   var getNewPoints = Fn.new { |inputPoints, pointsFaces, avgFacePoints, avgMidEdges| var newPoints = List.filled(inputPoints.count, null) for (pointNum in 0...inputPoints.count) { var n = pointsFaces[pointNum] var m1 = (n-3) / n var m2 = 1 / n var m3 = 2 / n var oldCoords = inputPoints[pointNum] var p1 = mulPoint.call(oldCoords, m1) var afp = avgFacePoints[pointNum] var p2 = mulPoint.call(afp, m2) var ame = avgMidEdges[pointNum] var p3 = mulPoint.call(ame, m3) var p4 = sumPoint.call(p1, p2) newPoints[pointNum] = sumPoint.call(p4, p3) } return newPoints }   var switchNums = Fn.new { |pointNums| if (pointNums[0] < pointNums[1]) return pointNums return [pointNums[1], pointNums[0]] }   var cmcSubdiv = Fn.new { |inputPoints, inputFaces| var facePoints = getFacePoints.call(inputPoints, inputFaces) var edgesFaces = getEdgesFaces.call(inputPoints, inputFaces) var edgePoints = getEdgePoints.call(inputPoints, edgesFaces, facePoints) var avgFacePoints = getAvgFacePoints.call(inputPoints, inputFaces, facePoints) var avgMidEdges = getAvgMidEdges.call(inputPoints, edgesFaces) var pointsFaces = getPointsFaces.call(inputPoints, inputFaces) var newPoints = getNewPoints.call(inputPoints, pointsFaces, avgFacePoints, avgMidEdges) var facePointNums = [] var nextPointNum = newPoints.count for (facePoint in facePoints) { newPoints.add(facePoint) facePointNums.add(nextPointNum) nextPointNum = nextPointNum + 1 } var edgePointNums = {} for (edgeNum in 0...edgesFaces.count) { var pointNum1 = edgesFaces[edgeNum].pn1 var pointNum2 = edgesFaces[edgeNum].pn2 var edgePoint = edgePoints[edgeNum] newPoints.add(edgePoint) edgePointNums[Int.cantorPair(pointNum1, pointNum2)] = nextPointNum nextPointNum = nextPointNum + 1 } var newFaces = [] var oldFaceNum = 0 for (oldFace in inputFaces) { if (oldFace.count == 4) { var a = oldFace[0] var b = oldFace[1] var c = oldFace[2] var d = oldFace[3] var facePointAbcd = facePointNums[oldFaceNum] var p = switchNums.call([a, b]) var edgePointAb = edgePointNums[Int.cantorPair(p[0], p[1])] p = switchNums.call([d, a]) var edgePointDa = edgePointNums[Int.cantorPair(p[0], p[1])] p = switchNums.call([b, c]) var edgePointBc = edgePointNums[Int.cantorPair(p[0], p[1])] p = switchNums.call([c, d]) var edgePointCd = edgePointNums[Int.cantorPair(p[0], p[1])] newFaces.add([a, edgePointAb, facePointAbcd, edgePointDa]) newFaces.add([b, edgePointBc, facePointAbcd, edgePointAb]) newFaces.add([c, edgePointCd, facePointAbcd, edgePointBc]) newFaces.add([d, edgePointDa, facePointAbcd, edgePointCd]) } oldFaceNum = oldFaceNum + 1 } return [newPoints, newFaces] }   var inputPoints = [ Point.new(-1, 1, 1), Point.new(-1, -1, 1), Point.new( 1, -1, 1), Point.new( 1, 1, 1), Point.new( 1, -1, -1), Point.new( 1, 1, -1), Point.new(-1, -1, -1), Point.new(-1, 1, -1) ]   var inputFaces = [ [0, 1, 2, 3], [3, 2, 4, 5], [5, 4, 6, 7], [7, 0, 3, 5], [7, 6, 1, 0], [6, 1, 2, 4] ]   var outputPoints = inputPoints.toList var outputFaces = inputFaces.toList var iterations = 1 for (i in 0...iterations) { var res = cmcSubdiv.call(outputPoints, outputFaces) outputPoints = res[0] outputFaces = res[1] } for (p in outputPoints) { Fmt.aprint([p.x, p.y, p.z], 7, 4, "[]") } System.print() for (f in outputFaces) { Fmt.aprint(f, 2, 0, "[]") }
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
#FreeBASIC
FreeBASIC
' version 17-10-2016 ' compile with: fbc -s console   ' using a sieve for finding primes   #Define max_sieve 10000000 ' 10^7 ReDim Shared As Byte isprime(max_sieve)   ' translated the pseudo code to FreeBASIC Sub carmichael3(p1 As Integer)   If isprime(p1) = 0 Then Exit Sub   Dim As Integer h3, d, p2, p3, t1, t2   For h3 = 1 To p1 -1 t1 = (h3 + p1) * (p1 -1) t2 = (-p1 * p1) Mod h3 If t2 < 0 Then t2 = t2 + h3 For d = 1 To h3 + p1 -1 If t1 Mod d = 0 And t2 = (d Mod h3) Then p2 = 1 + (t1 \ d) If isprime(p2) = 0 Then Continue For p3 = 1 + (p1 * p2 \ h3) If isprime(p3) = 0 Or ((p2 * p3) Mod (p1 -1)) <> 1 Then Continue For Print Using "### * #### * #####"; p1; p2; p3 End If Next d Next h3 End Sub     ' ------=< MAIN >=------   Dim As UInteger i, j   'set up sieve For i = 3 To max_sieve Step 2 isprime(i) = 1 Next i   isprime(2) = 1 For i = 3 To Sqr(max_sieve) Step 2 If isprime(i) = 1 Then For j = i * i To max_sieve Step i * 2 isprime(j) = 0 Next j End If Next i   For i = 2 To 61 carmichael3(i) Next i   ' empty keyboard buffer While InKey <> "" : Wend Print : Print "hit any key to end program" Sleep End
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
#Elixir
Elixir
iex(1)> Enum.reduce(1..10, fn i,acc -> i+acc end) 55 iex(2)> Enum.reduce(1..10, fn i,acc -> i*acc end) 3628800 iex(3)> Enum.reduce(10..-10, "", fn i,acc -> acc <> to_string(i) end) "109876543210-1-2-3-4-5-6-7-8-9-10"
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article:   Fold Wikipedia article:   Catamorphism
#Erlang
Erlang
  -module(catamorphism).   -export([test/0]).   test() -> Nums = lists:seq(1,10), Summation = lists:foldl(fun(X, Acc) -> X + Acc end, 0, Nums), Product = lists:foldl(fun(X, Acc) -> X * Acc end, 1, Nums), Concatenation = lists:foldr( fun(X, Acc) -> integer_to_list(X) ++ Acc end, "", Nums), {Summation, Product, Concatenation}.  
http://rosettacode.org/wiki/Chaocipher
Chaocipher
Description The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010. The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here. Task Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   ReadOnly L_ALPHABET As String = "HXUCZVAMDSLKPEFJRIGTWOBNYQ" ReadOnly R_ALPHABET As String = "PTLNBQDEOYSFAVZKGJRIHWXUMC"   Enum Mode ENCRYPT DECRYPT End Enum   Function Exec(text As String, mode As Mode, Optional showSteps As Boolean = False) As String Dim left = L_ALPHABET.ToCharArray() Dim right = R_ALPHABET.ToCharArray() Dim eText(text.Length - 1) As Char Dim temp(25) As Char   For i = 0 To text.Length - 1 If showSteps Then Console.WriteLine("{0} {1}", String.Join("", left), String.Join("", right)) Dim index As Integer If mode = Mode.ENCRYPT Then index = Array.IndexOf(right, text(i)) eText(i) = left(index) Else index = Array.IndexOf(left, text(i)) eText(i) = right(index) End If If i = text.Length - 1 Then Exit For   'permute left   For j = index To 25 temp(j - index) = left(j) Next For j = 0 To index - 1 temp(26 - index + j) = left(j) Next Dim store = temp(1) For j = 2 To 13 temp(j - 1) = temp(j) Next temp(13) = store temp.CopyTo(left, 0)   'permute right   For j = index To 25 temp(j - index) = right(j) Next For j = 0 To index - 1 temp(26 - index + j) = right(j) Next store = temp(0) For j = 1 To 25 temp(j - 1) = temp(j) Next temp(25) = store store = temp(2) For j = 3 To 13 temp(j - 1) = temp(j) Next temp(13) = store temp.CopyTo(right, 0) Next   Return eText End Function   Sub Main() Dim plainText = "WELLDONEISBETTERTHANWELLSAID" Console.WriteLine("The original plaintext is : {0}", plainText) Console.WriteLine(vbNewLine + "The left and right alphabets after each permutation during encryption are :" + vbNewLine) Dim cipherText = Exec(plainText, Mode.ENCRYPT, True) Console.WriteLine(vbNewLine + "The ciphertext is : {0}", cipherText) Dim plainText2 = Exec(cipherText, Mode.DECRYPT) Console.WriteLine(vbNewLine + "The recovered plaintext is : {0}", plainText2) End Sub   End Module
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
#Oforth
Oforth
import: mapping   : pascal( n -- [] ) [ 1 ] n #[ dup [ 0 ] + [ 0 ] rot + zipWith( #+ ) ] times ;   : catalan( n -- m ) n 2 * pascal at( n 1+ ) n 1+ / ;
http://rosettacode.org/wiki/Catalan_numbers/Pascal%27s_triangle
Catalan numbers/Pascal's triangle
Task Print out the first   15   Catalan numbers by extracting them from Pascal's triangle. See   Catalan Numbers and the Pascal Triangle.     This method enables calculation of Catalan Numbers using only addition and subtraction.   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.   Sequence A000108 on OEIS has a lot of information on Catalan Numbers. Related Tasks Pascal's triangle
#PARI.2FGP
PARI/GP
vector(15,n,binomial(2*n,n)-binomial(2*n,n+1))
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#M2000_Interpreter
M2000 Interpreter
  MoDuLe CheckIT { \\ keys as case sensitive if they are strings Inventory A= "Dog":=1, "dog":=2,"DOG":="Hello", 100:="Dog" Print A("Dog"), A("dog"), A$("DOG"), A$(100)   \\ Enumeration get type as defined (same case) Enum Dogs {Benjamin, Samba, Bernie} Print Type$(Bernie)="Dogs" Print Type$(DOGS)="Dogs" m=BenJamiN m++ Print Eval$(m)="Samba" ' same case as defined   DoG$="Benjamin" DOG$="Samba" doG$="Bernie" PrinT "There is just one dog named "+Dog$+"." goto Dog dog: Print "dog" Exit Dog: Print "Dog" GoTo dog } Checkit  
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
#Maple
Maple
> dog, Dog, DOG := "Benjamin", "Samba", "Bernie": > if nops( { dog, Dog, DOG } ) = 3 then > printf( "There are three dogs named %s, %s and %s.\n", dog, Dog, DOG ) > elif nops( { dog, Dog, DOG } ) = 2 then > printf( "WTF? There are two dogs named %s and %s.\n", op( { dog, Dog, DOG } ) ) > else > printf( "There is one dog named %s.\n", dog ) > end if: There are three dogs 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}
#Go
Go
package main   import "fmt"   type pair [2]int   func cart2(a, b []int) []pair { p := make([]pair, len(a)*len(b)) i := 0 for _, a := range a { for _, b := range b { p[i] = pair{a, b} i++ } } return p }   func main() { fmt.Println(cart2([]int{1, 2}, []int{3, 4})) fmt.Println(cart2([]int{3, 4}, []int{1, 2})) fmt.Println(cart2([]int{1, 2}, nil)) fmt.Println(cart2(nil, []int{1, 2})) }
http://rosettacode.org/wiki/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C_{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
#Bracmat
Bracmat
( out$straight & ( C = . ( F = i prod .  !arg:0&1 | 1:?prod & 0:?i & whl ' ( 1+!i:~>!arg:?i & !i*!prod:?prod ) & !prod ) & F$(2*!arg)*(F$(!arg+1)*F$!arg)^-1 ) & -1:?n & whl ' ( 1+!n:~>15:?n & out$(str$(C !n " = " C$!n)) ) & out$"recursive, with memoization, without fractions" & :?seenCs & ( C = i sum .  !arg:0&1 | ( !seenCs:? (!arg.?sum) ? | 0:?sum & -1:?i & whl ' ( 1+!i:<!arg:?i & C$!i*C$(-1+!arg+-1*!i)+!sum:?sum ) & (!arg.!sum) !seenCs:?seenCs ) & !sum ) & -1:?n & whl ' ( 1+!n:~>15:?n & out$(str$(C !n " = " C$!n)) ) & out$"recursive, without memoization, with fractions" & ( C = .  !arg:0&1 | 2*(2*!arg+-1)*(!arg+1)^-1*C$(!arg+-1) ) & -1:?n & whl ' ( 1+!n:~>15:?n & out$(str$(C !n " = " C$!n)) ) & out$"Using taylor expansion of sqrt(1-4X). (See http://bababadalgharaghtakamminarronnkonnbro.blogspot.in/2012/10/algebraic-type-systems-combinatorial.html)" & out$(1+(1+-1*tay$((1+-4*X)^1/2,X,16))*(2*X)^-1+-1) & out$ );
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.
#D
D
struct Cat { static int staticMethod() { return 2; }   string dynamicMethod() { // Never virtual. return "Mew!"; } }   class Dog { static int staticMethod() { return 5; }   string dynamicMethod() { // Virtual method. return "Woof!"; } }   void main() { // Static methods calls: assert(Cat.staticMethod() == 2); assert(Dog.staticMethod() == 5);   Cat c; // This is a value on the stack. Dog d; // This is just a reference, set to null.   // Other static method calls, discouraged: assert(c.staticMethod() == 2); assert(d.staticMethod() == 5);   // Instance method calls: assert(c.dynamicMethod() == "Mew!"); d = new Dog; assert(d.dynamicMethod() == "Woof!"); }
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.
#Dragon
Dragon
r = new run() r.val()
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library
Call a function in a shared library
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level. Related task OpenGL -- OpenGL is usually maintained as a shared library.
#C.23
C#
using System.Runtime.InteropServices;   class Program { [DllImport("fakelib.dll")] public static extern int fakefunction(int args);   static void Main(string[] args) { int r = fakefunction(10); } }
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library
Call a function in a shared library
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level. Related task OpenGL -- OpenGL is usually maintained as a shared library.
#COBOL
COBOL
identification division. program-id. callsym.   data division. working-storage section. 01 handle usage pointer. 01 addr usage program-pointer.   procedure division. call "dlopen" using by reference null by value 1 returning handle on exception display function exception-statement upon syserr goback end-call if handle equal null then display function module-id ": error getting dlopen handle" upon syserr goback end-if   call "dlsym" using by value handle by content z"perror" returning addr end-call if addr equal null then display function module-id ": error getting perror symbol" upon syserr else call addr returning omitted end-if   goback. end program callsym.
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.
#11l
11l
F no_args() {} // call no_args()   F fixed_args(x, y) print(‘x=#., y=#.’.format(x, y)) // call fixed_args(1, 2) // x=1, y=2   // named arguments fixed_args(x' 1, y' 2)   F opt_args(x = 1) print(x) // calls opt_args() // 1 opt_args(3.141) // 3.141
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#C
C
#include <stdio.h>   #define WIDTH 81 #define HEIGHT 5   char lines[HEIGHT][WIDTH];   void init() { int i, j; for (i = 0; i < HEIGHT; ++i) { for (j = 0; j < WIDTH; ++j) lines[i][j] = '*'; } }   void cantor(int start, int len, int index) { int i, j, seg = len / 3; if (seg == 0) return; for (i = index; i < HEIGHT; ++i) { for (j = start + seg; j < start + seg * 2; ++j) lines[i][j] = ' '; } cantor(start, seg, index + 1); cantor(start + seg * 2, seg, index + 1); }   void print() { int i, j; for (i = 0; i < HEIGHT; ++i) { for (j = 0; j < WIDTH; ++j) printf("%c", lines[i][j]); printf("\n"); } }   int main() { init(); cantor(0, WIDTH, 1); print(); return 0; }
http://rosettacode.org/wiki/Calkin-Wilf_sequence
Calkin-Wilf sequence
The Calkin-Wilf sequence contains every nonnegative rational number exactly once. It can be calculated recursively as follows: a1 = 1 an+1 = 1/(2⌊an⌋+1-an) for n > 1 Task part 1 Show on this page terms 1 through 20 of the Calkin-Wilf sequence. To avoid floating point error, you may want to 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
#Bracmat
Bracmat
( 1:?a & 0:?i & whl ' ( 1+!i:<20:?i & (2*div$(!a,1)+1+-1*!a)^-1:?a & out$!a ) & ( r2cf = floor . div$(!arg,1):?floor & ( !floor:!arg | !floor r2cf$((!arg+-1*!floor)^-1) ) ) & ( get-term-num = ans dig pwr . (0,1,1):(?ans,?dig,?pwr) & r2cf$!arg:?n & map $ ( ( = . whl ' ( !arg+-1:~<0:?arg & !dig*!pwr+!ans:?ans & 2*!pwr:?pwr ) & 1+-1*!dig:?dig ) . !n ) & !ans ) & out$(get-term-num$83116/51639) );
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
#C.2B.2B
C++
#include <iostream> #include <vector> #include <boost/rational.hpp>   using rational = boost::rational<unsigned long>;   unsigned long floor(const rational& r) { return r.numerator()/r.denominator(); }   rational calkin_wilf_next(const rational& term) { return 1UL/(2UL * floor(term) + 1UL - term); }   std::vector<unsigned long> continued_fraction(const rational& r) { unsigned long a = r.numerator(); unsigned long b = r.denominator(); std::vector<unsigned long> result; do { result.push_back(a/b); unsigned long c = a; a = b; b = c % b; } while (a != 1); if (result.size() > 0 && result.size() % 2 == 0) { --result.back(); result.push_back(1); } return result; }   unsigned long term_number(const rational& r) { unsigned long result = 0; unsigned long d = 1; unsigned long p = 0; for (unsigned long n : continued_fraction(r)) { for (unsigned long i = 0; i < n; ++i, ++p) result |= (d << p); d = !d; } return result; }   int main() { rational term = 1; std::cout << "First 20 terms of the Calkin-Wilf sequence are:\n"; for (int i = 1; i <= 20; ++i) { std::cout << std::setw(2) << i << ": " << term << '\n'; term = calkin_wilf_next(term); } rational r(83116, 51639); std::cout << r << " is the " << term_number(r) << "th term of the sequence.\n"; }
http://rosettacode.org/wiki/Canny_edge_detector
Canny edge detector
Task Write a program that performs so-called canny edge detection on an image. A possible algorithm consists of the following steps: Noise reduction.   May be performed by Gaussian filter.   Compute intensity gradient   (matrices G x {\displaystyle G_{x}} and G y {\displaystyle G_{y}} )   and its magnitude   G {\displaystyle G} :           G = G x 2 + G y 2 {\displaystyle G={\sqrt {G_{x}^{2}+G_{y}^{2}}}} May be performed by convolution of an image with Sobel operators.   Non-maximum suppression.   For each pixel compute the orientation of intensity gradient vector:   θ = a t a n 2 ( G y , G x ) {\displaystyle \theta ={\rm {atan2}}\left(G_{y},\,G_{x}\right)} .     Transform   angle θ {\displaystyle \theta }   to one of four directions:   0, 45, 90, 135 degrees.     Compute new array   N {\displaystyle N} :     if         G ( p a ) < G ( p ) < G ( p b ) {\displaystyle G\left(p_{a}\right)<G\left(p\right)<G\left(p_{b}\right)} where   p {\displaystyle p}   is the current pixel,   p a {\displaystyle p_{a}}   and   p b {\displaystyle p_{b}}   are the two neighbour pixels in the direction of gradient,   then     N ( p ) = G ( p ) {\displaystyle N(p)=G(p)} ,       otherwise   N ( p ) = 0 {\displaystyle N(p)=0} .   Nonzero pixels in resulting array correspond to local maxima of   G {\displaystyle G}   in direction   θ ( p ) {\displaystyle \theta (p)} .   Tracing edges with hysteresis.   At this stage two thresholds for the values of   G {\displaystyle G}   are introduced:   T m i n {\displaystyle T_{min}}   and   T m a x {\displaystyle T_{max}} .   Starting from pixels with   N ( p ) ⩾ T m a x {\displaystyle N(p)\geqslant T_{max}} ,   find all paths of pixels with   N ( p ) ⩾ T m i n {\displaystyle N(p)\geqslant T_{min}}   and put them to the resulting image.
#Phix
Phix
-- -- demo\rosetta\Canny_Edge_Detection.exw -- ===================================== -- without js -- imImage, im_width, im_height, im_pixel, IupImageRGB, -- imFileImageLoadBitmap, and IupImageFromImImage() include pGUI.e constant TITLE = "Canny Edge Detection", IMGFILE = "Valve.png", C_E_D = {{-1, -1, -1}, {-1, 8, -1}, {-1, -1, -1}} function detect_edges(imImage img) integer width = im_width(img), height = im_height(img) sequence original = repeat(repeat(0,width),height) integer fh = length(C_E_D), hh=(fh-1)/2, fw = length(C_E_D[1]), hw=(fw-1)/2, divisor = max(sum(C_E_D),1) -- read original pixels and make them grey, for y=height-1 to 0 by -1 do for x=0 to width-1 do integer {c1,c2,c3} = im_pixel(img, x, y), grey = floor((c1*114+c2*587+c3*299)/1000) original[height-y,x+1] = {grey,grey,grey} end for end for -- then apply an edge detection filter sequence new_image = original for y=hh+1 to height-hh-1 do for x=hw+1 to width-hw-1 do sequence newrgb = {0,0,0} for i=-hh to +hh do for j=-hw to +hw do newrgb = sq_add(newrgb,sq_mul(C_E_D[i+hh+1,j+hw+1],original[y+i,x+j])) end for end for new_image[y,x] = sq_max(sq_min(sq_floor_div(newrgb,divisor),255),0) end for end for new_image = flatten(new_image) -- (as needed by IupImageRGB) Ihandle new_img = IupImageRGB(width, height, new_image) return new_img end function IupOpen() imImage im1 = imFileImageLoadBitmap(IMGFILE) assert(im1!=NULL,"error opening "&IMGFILE) Ihandle label1 = IupLabel(), label2 = IupLabel() IupSetAttributeHandle(label1, "IMAGE", IupImageFromImImage(im1)) IupSetAttributeHandle(label2, "IMAGE", detect_edges(im1)) Ihandle dlg = IupDialog(IupHbox({label1, label2}),`TITLE="%s"`,{TITLE}) IupShow(dlg) IupMainLoop() IupClose()
http://rosettacode.org/wiki/Canonicalize_CIDR
Canonicalize CIDR
Task Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form. That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address. Example Given   87.70.141.1/22,   your code should output   87.70.140.0/22 Explanation An Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 "digit" is represented by the digit value in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the "network" portion of the address, while the rightmost (least-significant) bits determine the "host" portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion. In general, CIDR blocks stand in for the entire set of IP addresses sharing the same "network" component; it's common to see access control lists specify a single IP address using CIDR with /32 to indicate that only the one address is included. Often, the tools using this notation expect the address to be entered in canonical form, in which the "host" bits are all zeroes in the binary representation. But careless network admins may provide CIDR blocks without canonicalizing them first. This task handles the canonicalization. The example address, 87.70.141.1, translates into 01010111010001101000110100000001 in binary notation zero-padded to 32 bits. The /22 means that the first 22 of those bits determine the match; the final 10 bits should be 0. But they instead include two 1 bits: 0100000001. So to canonicalize the address, change those 1's to 0's to yield 01010111010001101000110000000000, which in dotted-decimal is 87.70.140.0. More examples for testing 36.18.154.103/12 → 36.16.0.0/12 62.62.197.11/29 → 62.62.197.8/29 67.137.119.181/4 → 64.0.0.0/4 161.214.74.21/24 → 161.214.74.0/24 184.232.176.184/18 → 184.232.128.0/18
#Julia
Julia
using Sockets   function canonCIDR(cidr::String) cidr = replace(cidr, r"\.(\.|\/)" => s".0\1") # handle .. cidr = replace(cidr, r"\.(\.|\/)" => s".0\1") # handle ... ip = split(cidr, "/") dig = length(ip) > 1 ? 2^(32 - parse(UInt8, ip[2])) : 1 ip4 = IPv4(UInt64(IPv4(ip[1])) & (0xffffffff - dig + 1)) return length(ip) == 1 ? "$ip4/32" : "$ip4/$(ip[2])" end   println(canonCIDR("87.70.141.1/22")) println(canonCIDR("100.68.0.18/18")) println(canonCIDR("10.4.30.77/30")) println(canonCIDR("10.207.219.251/32")) println(canonCIDR("10.207.219.251")) println(canonCIDR("110.200.21/4")) println(canonCIDR("10..55/8")) println(canonCIDR("10.../8"))  
http://rosettacode.org/wiki/Canonicalize_CIDR
Canonicalize CIDR
Task Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form. That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address. Example Given   87.70.141.1/22,   your code should output   87.70.140.0/22 Explanation An Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 "digit" is represented by the digit value in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the "network" portion of the address, while the rightmost (least-significant) bits determine the "host" portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion. In general, CIDR blocks stand in for the entire set of IP addresses sharing the same "network" component; it's common to see access control lists specify a single IP address using CIDR with /32 to indicate that only the one address is included. Often, the tools using this notation expect the address to be entered in canonical form, in which the "host" bits are all zeroes in the binary representation. But careless network admins may provide CIDR blocks without canonicalizing them first. This task handles the canonicalization. The example address, 87.70.141.1, translates into 01010111010001101000110100000001 in binary notation zero-padded to 32 bits. The /22 means that the first 22 of those bits determine the match; the final 10 bits should be 0. But they instead include two 1 bits: 0100000001. So to canonicalize the address, change those 1's to 0's to yield 01010111010001101000110000000000, which in dotted-decimal is 87.70.140.0. More examples for testing 36.18.154.103/12 → 36.16.0.0/12 62.62.197.11/29 → 62.62.197.8/29 67.137.119.181/4 → 64.0.0.0/4 161.214.74.21/24 → 161.214.74.0/24 184.232.176.184/18 → 184.232.128.0/18
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[CanonicalizeCIDR] CanonicalizeCIDR[str_String] := Module[{i, ip, chop, keep, change}, If[StringMatchQ[str, "*.*.*.*/*"], i = StringSplit[str, "." | "/"]; i = Interpreter["Integer"] /@ i; If[MatchQ[i, {_Integer, _Integer, _Integer, _Integer, _Integer}], If[AllTrue[i, Between[{0, 255}]], {ip, {chop}} = TakeDrop[i, 4]; ip = Catenate[IntegerDigits[ip, 2, 8]]; {keep, change} = TakeDrop[ip, chop]; change = ConstantArray[0, Length[change]]; ip = Partition[Join[keep, change], 8]; ip = ToString[FromDigits[#, 2]] & /@ ip; StringRiffle[ip, "."] <> "/" <> ToString[chop] , Failure["Invalid range of numbers", <|"Input" -> str|>] ] , Failure["Invalid format", <|"Input" -> str|>] ] ] ] CanonicalizeCIDR["87.70.141.1/22"] CanonicalizeCIDR["36.18.154.103/12"] CanonicalizeCIDR["62.62.197.11/29"] CanonicalizeCIDR["67.137.119.181/4"] CanonicalizeCIDR["161.214.74.21/24"] CanonicalizeCIDR["184.232.176.184/18"]
http://rosettacode.org/wiki/Canonicalize_CIDR
Canonicalize CIDR
Task Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form. That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address. Example Given   87.70.141.1/22,   your code should output   87.70.140.0/22 Explanation An Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 "digit" is represented by the digit value in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the "network" portion of the address, while the rightmost (least-significant) bits determine the "host" portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion. In general, CIDR blocks stand in for the entire set of IP addresses sharing the same "network" component; it's common to see access control lists specify a single IP address using CIDR with /32 to indicate that only the one address is included. Often, the tools using this notation expect the address to be entered in canonical form, in which the "host" bits are all zeroes in the binary representation. But careless network admins may provide CIDR blocks without canonicalizing them first. This task handles the canonicalization. The example address, 87.70.141.1, translates into 01010111010001101000110100000001 in binary notation zero-padded to 32 bits. The /22 means that the first 22 of those bits determine the match; the final 10 bits should be 0. But they instead include two 1 bits: 0100000001. So to canonicalize the address, change those 1's to 0's to yield 01010111010001101000110000000000, which in dotted-decimal is 87.70.140.0. More examples for testing 36.18.154.103/12 → 36.16.0.0/12 62.62.197.11/29 → 62.62.197.8/29 67.137.119.181/4 → 64.0.0.0/4 161.214.74.21/24 → 161.214.74.0/24 184.232.176.184/18 → 184.232.128.0/18
#Nim
Nim
import net import strutils     proc canonicalize*(address: var IpAddress; nbits: Positive) = ## Canonicalize an IP address.   var zbits = 32 - nbits # Number of bits to reset.   # We process byte by byte which avoids byte order issues. for idx in countdown(address.address_v4.high, address.address_v4.low): if zbits == 0: # No more bits to reset. break if zbits >= 8: # Reset the current byte and continue with the remaining bits. address.address_v4[idx] = 0 dec zbits, 8 else: # Use a mask to reset the bits. address.address_v4[idx] = address.address_v4[idx] and (0xff'u8 shl zbits) zbits = 0   #———————————————————————————————————————————————————————————————————————————————————————————————————   when isMainModule:   import strformat   var ipAddress: IpAddress var nbits: int   for address in ["87.70.141.1/22", "36.18.154.103/12", "62.62.197.11/29", "67.137.119.181/4", "161.214.74.21/24", "184.232.176.184/18"]:   # Parse the address. let parts = address.split('/') try: ipAddress = parseIpAddress(parts[0]) if ipAddress.family == IPV6: raise newException(ValueError, "") except ValueError: echo "Invalid IP V4 address: ", parts[0] quit(QuitFailure)   # Check the number of bits. try: nbits = parseInt(parts[1]) if nbits notin 1..32: raise newException(ValueError, "") except ValueError: echo "Invalid number of bits: ", parts[1] quit(QuitFailure)   # Canonicalize the address and display the result. ipAddress.canonicalize(nbits) echo &"{address:<18} ⇢ {ipAddress}/{nbits}"
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
#JavaScript
JavaScript
function main(s, e, bs, pbs) { bs = bs || 10; pbs = pbs || 10 document.write('start:', toString(s), ' end:', toString(e), ' base:', bs, ' printBase:', pbs) document.write('<br>castOutNine: '); castOutNine() document.write('<br>kaprekar: '); kaprekar() document.write('<br><br>')   function castOutNine() { for (var n = s, k = 0, bsm1 = bs - 1; n <= e; n += 1) if (n % bsm1 == (n * n) % bsm1) k += 1, document.write(toString(n), ' ') document.write('<br>trying ', k, ' numbers instead of ', n = e - s + 1, ' numbers saves ', (100 - k / n * 100) .toFixed(3), '%') }   function kaprekar() { for (var n = s; n <= e; n += 1) if (isKaprekar(n)) document.write(toString(n), ' ')   function isKaprekar(n) { if (n < 1) return false if (n == 1) return true var s = (n * n) .toString(bs) for (var i = 1, e = s.length; i < e; i += 1) { var a = parseInt(s.substr(0, i), bs) var b = parseInt(s.substr(i), bs) if (b && a + b == n) return true } return false } }   function toString(n) { return n.toString(pbs) .toUpperCase() } } main(1, 10 * 10 - 1) main(1, 16 * 16 - 1, 16) main(1, 17 * 17 - 1, 17) main(parseInt('10', 17), parseInt('gg', 17), 17, 17)
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
#Go
Go
package main   import "fmt"   // Use this rather than % for negative integers func mod(n, m int) int { return ((n % m) + m) % m }   func isPrime(n int) bool { if n < 2 { return false } if n % 2 == 0 { return n == 2 } if n % 3 == 0 { return n == 3 } d := 5 for d * d <= n { if n % d == 0 { return false } d += 2 if n % d == 0 { return false } d += 4 } return true }   func carmichael(p1 int) { for h3 := 2; h3 < p1; h3++ { for d := 1; d < h3 + p1; d++ { if (h3 + p1) * (p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3 { p2 := 1 + (p1 - 1) * (h3 + p1) / d if !isPrime(p2) { continue } p3 := 1 + p1 * p2 / h3 if !isPrime(p3) { continue } if p2 * p3 % (p1 - 1) != 1 { continue } c := p1 * p2 * p3 fmt.Printf("%2d  %4d  %5d  %d\n", p1, p2, p3, c) } } } }   func main() { fmt.Println("The following are Carmichael munbers for p1 <= 61:\n") fmt.Println("p1 p2 p3 product") fmt.Println("== == == =======")   for p1 := 2; p1 <= 61; p1++ { if isPrime(p1) { carmichael(p1) } } }
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article:   Fold Wikipedia article:   Catamorphism
#Excel
Excel
FOLDROW =LAMBDA(op, LAMBDA(a, LAMBDA(xs, LET( b, op(a)(HEADROW(xs)),   IF(1 < COLUMNS(xs), FOLDROW(op)(b)( TAILROW(xs) ), b ) ) ) ) )     updatedBracketDepth =LAMBDA(depth, LAMBDA(c, IF(0 <= depth, IF("[" = c, 1 + depth, IF("]" = c, depth - 1, depth ) ), depth ) ) )     bracketCount =LAMBDA(a, LAMBDA(c, IF(ISNUMBER(FIND(c, "[]", 1)), 1 + a, a ) ) )     HEADROW =LAMBDA(xs, LET(REM, "The first item of each row in xs",   INDEX( xs, SEQUENCE(ROWS(xs)), SEQUENCE(1, 1) ) ) )     TAILROW =LAMBDA(xs, LET(REM,"The tail of each row in the grid", n, COLUMNS(xs) - 1,   IF(0 < n, INDEX( xs, SEQUENCE(ROWS(xs), 1, 1, 1), SEQUENCE(1, n, 2, 1) ), NA() ) ) )     CHARSROW =LAMBDA(s, MID(s, SEQUENCE(1, LEN(s), 1, 1), 1 ) )
http://rosettacode.org/wiki/Chaocipher
Chaocipher
Description The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010. The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here. Task Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
#Vlang
Vlang
type Mode = int const( encrypt = Mode(0) decrypt = Mode(1) )   const( l_alphabet = "HXUCZVAMDSLKPEFJRIGTWOBNYQ" r_alphabet = "PTLNBQDEOYSFAVZKGJRIHWXUMC" )   fn chao(text string, mode Mode, show_steps bool) string { len := text.len if text.bytes().len != len { println("Text contains non-ASCII characters") return "" } mut left  := l_alphabet mut right := r_alphabet mut e_text := []u8{len: len} mut temp  := []u8{len: 26}   for i in 0..len { if show_steps { println('$left $right') } mut index := 0 if mode == encrypt { index = right.index_u8(text[i]) e_text[i] = left[index] } else { index = left.index_u8(text[i]) e_text[i] = right[index] } if i == len - 1 { break }   // permute left for j in index..26 { temp[j - index] = left[j] } for j in 0..index { temp[26 - index + j] = left[j] } mut store := temp[1] for j in 2..14 { temp[j - 1] = temp[j] } temp[13] = store left = temp.bytestr()   // permute right   for j in index..26 { temp[j - index] = right[j] } for j in 0..index { temp[26 - index + j] = right[j] } store = temp[0] for j in 1..26 { temp[j - 1] = temp[j] } temp[25] = store store = temp[2] for j in 3..14 { temp[j - 1] = temp[j] } temp[13] = store right = temp.bytestr() }   return e_text.bytestr() }   fn main() { plain_text := "WELLDONEISBETTERTHANWELLSAID" println("The original plaintext is : $plain_text") print("\nThe left and right alphabets after each permutation ") println("during encryption are :\n") cypher_text := chao(plain_text, encrypt, true) println("\nThe ciphertext is : $cypher_text") plain_text2 := chao(cypher_text, decrypt, false) println("\nThe recovered plaintext is : $plain_text2") }
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
#Pascal
Pascal
  Program CatalanNumbers type tElement = Uint64; var Catalan : array[0..50] of tElement; procedure GetCatalan(L:longint); var PasTri : array[0..100] of tElement; j,k: longInt; begin l := l*2; PasTri[0] := 1; j := 0; while (j<L) do begin inc(j); k := (j+1) div 2; PasTri[k] :=PasTri[k-1]; For k := k downto 1 do inc(PasTri[k],PasTri[k-1]); IF NOT(Odd(j)) then begin k := j div 2; Catalan[k] :=PasTri[k]-PasTri[k-1]; end; end; end;   var i,l: longint; Begin l := 15; GetCatalan(L); For i := 1 to L do Writeln(i:3,Catalan[i]:20); end.
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
dog = "Benjamin"; Dog = "Samba"; DOG = "Bernie"; "The three dogs are named "<> dog <>", "<> Dog <>" and "<> DOG   -> "The three dogs are named Benjamin, Samba and Bernie"
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#MATLAB_.2F_Octave
MATLAB / Octave
dog = 'Benjamin'; Dog = 'Samba'; DOG = 'Bernie';   printf('There are three dogs %s, %s, %s.\n',dog, Dog, DOG);
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists
Cartesian product of two or more lists
Task Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language. Demonstrate that your function/method correctly returns: {1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)} and, in contrast: {3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)} Also demonstrate, using 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}
#Groovy
Groovy
class CartesianCategory { static Iterable multiply(Iterable a, Iterable b) { assert [a,b].every { it != null } def (m,n) = [a.size(),b.size()] (0..<(m*n)).inject([]) { prod, i -> prod << [a[i.intdiv(n)], b[i%n]].flatten() } } }
http://rosettacode.org/wiki/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C_{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
#Brat
Brat
catalan = { n | true? n == 0 { 1 } { (2 * ( 2 * n - 1) / ( n + 1 )) * catalan(n - 1) } }   0.to 15 { n | p "#{n} - #{catalan n}" }
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#Dyalect
Dyalect
//Static method on a built-in type Integer static func Integer.Div(x, y) { x / y }   //Instance method func Integer.Div(n) { this / n }   print(Integer.Div(12, 3)) print(12.Div(3))
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#E
E
someObject.someMethod(someParameter)
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#Elena
Elena
  console.printLine("Hello"," ","World!");  
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library
Call a function in a shared library
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level. Related task OpenGL -- OpenGL is usually maintained as a shared library.
#Common_Lisp
Common Lisp
CL-USER> (cffi:load-foreign-library "libX11.so") #<CFFI::FOREIGN-LIBRARY {1004F4ECC1}> CL-USER> (cffi:foreign-funcall "XOpenDisplay" :string #+sbcl (sb-posix:getenv "DISPLAY") #-sbcl ":0.0" :pointer) #.(SB-SYS:INT-SAP #X00650FD0)
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.
#Crystal
Crystal
libm = LibC.dlopen("libm.so.6", LibC::RTLD_LAZY) sqrtptr = LibC.dlsym(libm, "sqrt") unless libm.null?   if sqrtptr sqrtproc = Proc(Float64, Float64).new sqrtptr, Pointer(Void).null at_exit { LibC.dlclose(libm) } else sqrtproc = ->Math.sqrt(Float64) end   puts "the sqrt of 4 is #{sqrtproc.call(4.0)}"
http://rosettacode.org/wiki/Call_a_function
Call a function
Task Demonstrate the different syntax and semantics provided for calling a function. This may include:   Calling a function that requires no arguments   Calling a function with a fixed number of arguments   Calling a function with optional arguments   Calling a function with a variable number of arguments   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.
#360_Assembly
360 Assembly
X DS F Y DS F Z DS F
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#C.23
C#
using System;   namespace CantorSet { class Program { const int WIDTH = 81; const int HEIGHT = 5; private static char[,] lines = new char[HEIGHT, WIDTH];   static Program() { for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH; j++) { lines[i, j] = '*'; } } }   private static void Cantor(int start, int len, int index) { int seg = len / 3; if (seg == 0) return; for (int i = index; i < HEIGHT; i++) { for (int j = start + seg; j < start + seg * 2; j++) { 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++) { Console.Write(lines[i,j]); } Console.WriteLine(); } } } }
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
#EDSAC_order_code
EDSAC order code
  [For Rosetta Code. EDSAC program, Initial Orders 2. Prints the first 20 terms of the Calkin-Wilf sequence. Uses term{n} to calculate term{n + 1}.]   [Print subroutine for non-negative 17-bit integers. Parameters: 0F = integer to be printed (not preserved) 1F = character for leading zero (preserved) Workspace: 4F, 5F. Even address; 40 locations] T 56 K [define load address] GKA3FT34@A1FT35@S37@T36@AFT5FT4FH38#@V4DH30@ R32FR16FYFE23@O35@A2FT36@T5FV4DYFL8FT4DA5FL1024F UFA36@G16@OFTFT35@A36@G17@ZFPFPFP4FT1714FZ219D   [Main routine] T 100 K [define load address] G K [set up relative addressing via @ (theta)] [Constants] [0] P 10 F [maximum index = 20, edit ad lib.] [1] P D [constant 1] [Teleprinter characters] [2] # F [set figures mode] [3] C F [colon (in figures mode)] [4] X F [slash (in figures mode)] [5] ! F [space] [6] @ F [carriage return] [7] & F [line feed] [8] K 4096 F [null] [Variables] [9] P F [index] [10] P F [a (where term = a/b)] [11] P F [b] [Enter with acc = 0] [12] O 2 @ [set teleprinter to figures] A 1 @ [acc := 1] U 9 @ [index := 1] U 10 @ [a := 1] T 11 @ [b := 1 (and clear acc)] E 34 @ [jump to print first term] [Loop back here if not yet printed enough terms] [18] A @ [restore index after test] A 1 @ [add 1] T 9 @ [update index] [Calculate next term. New b := a + b - 2(a mod b). Code below calculates c := (a mod b) - b, then new b := a - b - 2*c] A 10 @ [acc := a] [22] S 11 @ [subtract b] E 22 @ [if acc >= 0, subtract again] T F [result c < 0, store in 0F] A 10 @ [acc := a] S 11 @ [subtract b] S F [subtract c] S F [subtract c] T F [new b = a - b - 2*c; store in 0F] A 11 @ [acc := old b] T 10 @ [copy to a] A F [acc := new b] T 11 @ [copy to b] [Print index and a/b. Assume acc = 0 here.] [34] A 5 @ [space to replace leading 0's] T 1 F [pass to print subroutine] A 9 @ [acc := index] T F [pass to print subroutine] [38] A 38 @ [for return from subroutine] G 56 F [call subroutine, clears acc] O 3 @ [print colon] O 5 @ [print space] A 8 @ [null to replace leading 0's] T 1 F [pass to print subroutine] A10@ TF A46@ G56F O4@ [print a followed by slash] A11@ TF A51@ G56F O6@ O7@ [print b followed by CR LF] [Test whether enough terms have been printed] A 9 @ [acc := index] S @ [subtract maximum index] G 18 @ [loop back if acc < 0] [Exit] O 8 @ [print null to flush teleprinter buffer] Z F [stop] E 12 Z [relative address of entry point] P F [enter with acc = 0] [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
#F.23
F#
  // Calkin Wilf Sequence. Nigel Galloway: January 9th., 2021 let cW=Seq.unfold(fun(n)->Some(n,seq{for n,g in n do yield (n,n+g); yield (n+g,g)}))(seq[(1,1)])|>Seq.concat  
http://rosettacode.org/wiki/Canny_edge_detector
Canny edge detector
Task Write a program that performs so-called canny edge detection on an image. A possible algorithm consists of the following steps: Noise reduction.   May be performed by Gaussian filter.   Compute intensity gradient   (matrices G x {\displaystyle G_{x}} and G y {\displaystyle G_{y}} )   and its magnitude   G {\displaystyle G} :           G = G x 2 + G y 2 {\displaystyle G={\sqrt {G_{x}^{2}+G_{y}^{2}}}} May be performed by convolution of an image with Sobel operators.   Non-maximum suppression.   For each pixel compute the orientation of intensity gradient vector:   θ = a t a n 2 ( G y , G x ) {\displaystyle \theta ={\rm {atan2}}\left(G_{y},\,G_{x}\right)} .     Transform   angle θ {\displaystyle \theta }   to one of four directions:   0, 45, 90, 135 degrees.     Compute new array   N {\displaystyle N} :     if         G ( p a ) < G ( p ) < G ( p b ) {\displaystyle G\left(p_{a}\right)<G\left(p\right)<G\left(p_{b}\right)} where   p {\displaystyle p}   is the current pixel,   p a {\displaystyle p_{a}}   and   p b {\displaystyle p_{b}}   are the two neighbour pixels in the direction of gradient,   then     N ( p ) = G ( p ) {\displaystyle N(p)=G(p)} ,       otherwise   N ( p ) = 0 {\displaystyle N(p)=0} .   Nonzero pixels in resulting array correspond to local maxima of   G {\displaystyle G}   in direction   θ ( p ) {\displaystyle \theta (p)} .   Tracing edges with hysteresis.   At this stage two thresholds for the values of   G {\displaystyle G}   are introduced:   T m i n {\displaystyle T_{min}}   and   T m a x {\displaystyle T_{max}} .   Starting from pixels with   N ( p ) ⩾ T m a x {\displaystyle N(p)\geqslant T_{max}} ,   find all paths of pixels with   N ( p ) ⩾ T m i n {\displaystyle N(p)\geqslant T_{min}}   and put them to the resulting image.
#Python
Python
#!/bin/python import numpy as np from scipy.ndimage.filters import convolve, gaussian_filter from scipy.misc import imread, imshow   def CannyEdgeDetector(im, blur = 1, highThreshold = 91, lowThreshold = 31): im = np.array(im, dtype=float) #Convert to float to prevent clipping values   #Gaussian blur to reduce noise im2 = gaussian_filter(im, blur)   #Use sobel filters to get horizontal and vertical gradients im3h = convolve(im2,[[-1,0,1],[-2,0,2],[-1,0,1]]) im3v = convolve(im2,[[1,2,1],[0,0,0],[-1,-2,-1]])   #Get gradient and direction grad = np.power(np.power(im3h, 2.0) + np.power(im3v, 2.0), 0.5) theta = np.arctan2(im3v, im3h) thetaQ = (np.round(theta * (5.0 / np.pi)) + 5) % 5 #Quantize direction   #Non-maximum suppression gradSup = grad.copy() for r in range(im.shape[0]): for c in range(im.shape[1]): #Suppress pixels at the image edge if r == 0 or r == im.shape[0]-1 or c == 0 or c == im.shape[1] - 1: gradSup[r, c] = 0 continue tq = thetaQ[r, c] % 4   if tq == 0: #0 is E-W (horizontal) if grad[r, c] <= grad[r, c-1] or grad[r, c] <= grad[r, c+1]: gradSup[r, c] = 0 if tq == 1: #1 is NE-SW if grad[r, c] <= grad[r-1, c+1] or grad[r, c] <= grad[r+1, c-1]: gradSup[r, c] = 0 if tq == 2: #2 is N-S (vertical) if grad[r, c] <= grad[r-1, c] or grad[r, c] <= grad[r+1, c]: gradSup[r, c] = 0 if tq == 3: #3 is NW-SE if grad[r, c] <= grad[r-1, c-1] or grad[r, c] <= grad[r+1, c+1]: gradSup[r, c] = 0   #Double threshold strongEdges = (gradSup > highThreshold)   #Strong has value 2, weak has value 1 thresholdedEdges = np.array(strongEdges, dtype=np.uint8) + (gradSup > lowThreshold)   #Tracing edges with hysteresis #Find weak edge pixels near strong edge pixels finalEdges = strongEdges.copy() currentPixels = [] for r in range(1, im.shape[0]-1): for c in range(1, im.shape[1]-1): if thresholdedEdges[r, c] != 1: continue #Not a weak pixel   #Get 3x3 patch localPatch = thresholdedEdges[r-1:r+2,c-1:c+2] patchMax = localPatch.max() if patchMax == 2: currentPixels.append((r, c)) finalEdges[r, c] = 1   #Extend strong edges based on current pixels while len(currentPixels) > 0: newPix = [] for r, c in currentPixels: for dr in range(-1, 2): for dc in range(-1, 2): if dr == 0 and dc == 0: continue r2 = r+dr c2 = c+dc if thresholdedEdges[r2, c2] == 1 and finalEdges[r2, c2] == 0: #Copy this weak pixel to final result newPix.append((r2, c2)) finalEdges[r2, c2] = 1 currentPixels = newPix   return finalEdges   if __name__=="__main__": im = imread("test.jpg", mode="L") #Open image, convert to greyscale finalEdges = CannyEdgeDetector(im) imshow(finalEdges)
http://rosettacode.org/wiki/Canonicalize_CIDR
Canonicalize CIDR
Task Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form. That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address. Example Given   87.70.141.1/22,   your code should output   87.70.140.0/22 Explanation An Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 "digit" is represented by the digit value in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the "network" portion of the address, while the rightmost (least-significant) bits determine the "host" portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion. In general, CIDR blocks stand in for the entire set of IP addresses sharing the same "network" component; it's common to see access control lists specify a single IP address using CIDR with /32 to indicate that only the one address is included. Often, the tools using this notation expect the address to be entered in canonical form, in which the "host" bits are all zeroes in the binary representation. But careless network admins may provide CIDR blocks without canonicalizing them first. This task handles the canonicalization. The example address, 87.70.141.1, translates into 01010111010001101000110100000001 in binary notation zero-padded to 32 bits. The /22 means that the first 22 of those bits determine the match; the final 10 bits should be 0. But they instead include two 1 bits: 0100000001. So to canonicalize the address, change those 1's to 0's to yield 01010111010001101000110000000000, which in dotted-decimal is 87.70.140.0. More examples for testing 36.18.154.103/12 → 36.16.0.0/12 62.62.197.11/29 → 62.62.197.8/29 67.137.119.181/4 → 64.0.0.0/4 161.214.74.21/24 → 161.214.74.0/24 184.232.176.184/18 → 184.232.128.0/18
#Perl
Perl
#!/usr/bin/env perl use v5.16; use Socket qw(inet_aton inet_ntoa);   # canonicalize a CIDR block: make sure none of the host bits are set if (!@ARGV) { chomp(@ARGV = <>); }   for (@ARGV) {   # dotted-decimal / bits in network part my ($dotted, $size) = split m#/#;   # get IP as binary string my $binary = sprintf "%032b", unpack('N', inet_aton $dotted);   # Replace the host part with all zeroes substr($binary, $size) = 0 x (32 - $size);   # Convert back to dotted-decimal $dotted = inet_ntoa(pack 'B32', $binary);   # And output say "$dotted/$size"; }
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
#jq
jq
def co9: def digits: tostring | explode | map(. - 48); # "0" is 48 if . == 9 then 0 elif 0 <= . and . <= 8 then . else digits | add | co9 end;
http://rosettacode.org/wiki/Carmichael_3_strong_pseudoprimes
Carmichael 3 strong pseudoprimes
A lot of composite numbers can be separated from primes by Fermat's Little Theorem, but there are some that completely confound it. The   Miller Rabin Test   uses a combination of Fermat's Little Theorem and Chinese Division Theorem to overcome this. The purpose of this task is to investigate such numbers using a 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
#Haskell
Haskell
#!/usr/bin/runhaskell   import Data.Numbers.Primes import Control.Monad (guard)   carmichaels = do p <- takeWhile (<= 61) primes h3 <- [2..(p-1)] let g = h3 + p d <- [1..(g-1)] guard $ (g * (p - 1)) `mod` d == 0 && (-1 * p * p) `mod` h3 == d `mod` h3 let q = 1 + (((p - 1) * g) `div` d) guard $ isPrime q let r = 1 + ((p * q) `div` h3) guard $ isPrime r && (q * r) `mod` (p - 1) == 1 return (p, q, r)   main = putStr $ unlines $ map show carmichaels
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
#F.23
F#
> let nums = [1 .. 10];; val nums : int list = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10] > let summation = List.fold (+) 0 nums;; val summation : int = 55 > let product = List.fold (*) 1 nums;; val product : int = 3628800 > let concatenation = List.foldBack (fun x y -> x + y) (List.map (fun i -> i.ToString()) nums) "";; val concatenation : string = "12345678910"
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
#Factor
Factor
{ 1 2 4 6 10 } 0 [ + ] reduce .
http://rosettacode.org/wiki/Chaocipher
Chaocipher
Description The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010. The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here. Task Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
#Wren
Wren
class Chao { static encrypt { 0 } static decrypt { 1 }   static exec(text, mode, showSteps) { var len = text.count if (len != text.bytes.count) Fiber.abort("Text contains non-ASCII characters.") var left = "HXUCZVAMDSLKPEFJRIGTWOBNYQ" var right = "PTLNBQDEOYSFAVZKGJRIHWXUMC" var eText = List.filled(len, "") var temp = List.filled(26, "") for (i in 0...len) { if (showSteps) System.print("%(left)  %(right)") var index if (mode == Chao.encrypt) { index = right.indexOf(text[i]) eText[i] = left[index] } else { index = left.indexOf(text[i]) eText[i] = right[index] } if (i == len - 1) break   // permute left for (j in index..25) temp[j-index] = left[j] for (j in 0...index) temp[26-index+j] = left[j] var store = temp[1] for (j in 2..13) temp[j-1] = temp[j] temp[13] = store left = temp.join()   // permute right for (j in index..25) temp[j-index] = right[j] for (j in 0...index) temp[26-index+j] = right[j] store = temp[0] for (j in 1..25) temp[j-1] = temp[j] temp[25] = store store = temp[2] for (j in 3..13) temp[j-1] = temp[j] temp[13] = store right = temp.join() } return eText.join() } }   var plainText = "WELLDONEISBETTERTHANWELLSAID" System.print("The original plaintext is : %(plainText)") System.write("\nThe left and right alphabets after each permutation ") System.print("during encryption are :\n") var cipherText = Chao.exec(plainText, Chao.encrypt, true) System.print("\nThe ciphertext is : %(cipherText)") var plainText2 = Chao.exec(cipherText, Chao.decrypt, false) System.print("\nThe recovered plaintext is : %(plainText2)")
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
#Perl
Perl
use constant N => 15; my @t = (0, 1); for(my $i = 1; $i <= N; $i++) { for(my $j = $i; $j > 1; $j--) { $t[$j] += $t[$j-1] } $t[$i+1] = $t[$i]; for(my $j = $i+1; $j>1; $j--) { $t[$j] += $t[$j-1] } print $t[$i+1] - $t[$i], " "; }
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#Maxima
Maxima
/* Maxima is case sensitive */ a: 1$ A: 2$   is(a = A); false
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#min
min
"Benjamin" :dog "Samba" :Dog "Bernie" :DOG   "There are three dogs named $1, $2, and $3." (dog Dog DOG)=> % print
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#MiniScript
MiniScript
dog = "Benjamin" Dog = "Samba" DOG = "Bernie"   print "There are three dogs named " + dog + ", " + Dog + " and " + DOG
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists
Cartesian product of two or more lists
Task Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language. Demonstrate that your function/method correctly returns: {1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)} and, in contrast: {3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)} Also demonstrate, using 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}
#Haskell
Haskell
cartProd :: [a] -> [b] -> [(a, b)] cartProd xs ys = [ (x, y) | x <- xs , y <- ys ]
http://rosettacode.org/wiki/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C_{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
#BQN
BQN
Cat←{ 0⊸<◶⟨1, (𝕊-⟜1)×(¯2+4×⊢)÷1+⊢⟩ 𝕩 } Fact ← ×´1+↕ Cat1 ← { # direct formula ⌊0.5 + (Fact 2×𝕩) ÷ (Fact 𝕩+1) × Fact 𝕩 } Cat2 ← { # header based recursion 0: 1; (𝕊 𝕩-1)×2×(1-˜2×𝕩)÷𝕩+1 }   Cat¨ ↕15 Cat1¨ ↕15 Cat2¨ ↕15
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#Elixir
Elixir
  defmodule ObjectCall do def new() do spawn_link(fn -> loop end) end   defp loop do receive do {:concat, {caller, [str1, str2]}} -> result = str1 <> str2 send caller, {:ok, result} loop end end   def concat(obj, str1, str2) do send obj, {:concat, {self(), [str1, str2]}}   receive do {:ok, result} -> result end end end   obj = ObjectCall.new()   IO.puts(obj |> ObjectCall.concat("Hello ", "World!"))  
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#Factor
Factor
USING: accessors io kernel literals math sequences ; IN: rosetta-code.call-a-method   ! Define some classes. SINGLETON: dog TUPLE: cat sassiness ;   ! Define a constructor for cat. C: <cat> cat   ! Define a generic word that dispatches on the object at the top ! of the data stack. GENERIC: speak ( obj -- )   ! Define methods in speak which specialize on various classes. M: dog speak drop "Woof!" print ; M: cat speak sassiness>> 0.5 > "Hiss!" "Meow!" ? print ; M: object speak drop "I don't know how to speak!" print ;   ! Call speak on various objects. ! Despite being a method, it's called like any other word. dog speak 0.75 <cat> speak 0.1 <cat> speak "bird" speak
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.
#D
D
pragma(lib, "user32.lib");   import std.stdio, std.c.windows.windows;   extern(Windows) UINT GetDoubleClickTime();   void main() { writeln(GetDoubleClickTime()); }
http://rosettacode.org/wiki/Call_a_function_in_a_shared_library
Call a function in a shared library
Show how to call a function in a shared library (without dynamically linking to it at compile-time). In particular, show how to call the shared library function if the library is available, otherwise use an internal equivalent function. This is a special case of calling a foreign language function where the focus is close to the ABI level and not at the normal API level. Related task OpenGL -- OpenGL is usually maintained as a shared library.
#Dart
Dart
  int add(int num1, int num2) { return num1 + num2; }  
http://rosettacode.org/wiki/Call_a_foreign-language_function
Call a foreign-language function
Task Show how a foreign language function can be called from the language. As an example, consider calling functions defined in the C language. Create a string containing "Hello World!" of the string type typical to the language. Pass the string content to C's strdup. The content can be copied if necessary. Get the 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
#8th
8th
  \ tell 8th what the function expects: "ZZ" "strdup" func: strdup "VZ" "free" func: free \ call the external funcs "abc" dup \ now we have two strings "abc" on the stack strdup .s cr \ after strdup, you'll have the new (but duplicate) string on the stack \ the ".s" will show both strings and you can see they are different items on the stack free \ let the c library free the string  
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.
#6502_Assembly
6502 Assembly
JSR myFunction
http://rosettacode.org/wiki/Cantor_set
Cantor set
Task Draw a Cantor set. See details at this Wikipedia webpage:   Cantor set
#C.2B.2B
C++
#include <iostream>   const int WIDTH = 81; const int HEIGHT = 5;   char lines[WIDTH*HEIGHT];   void cantor(int start, int len, int index) { int seg = len / 3; if (seg == 0) return; for (int i = index; i < HEIGHT; i++) { for (int j = start + seg; j < start + seg * 2; j++) { int pos = i * WIDTH + j; lines[pos] = ' '; } } cantor(start, seg, index + 1); cantor(start + 2 * seg, seg, index + 1); }   int main() { // init for (int i = 0; i < WIDTH*HEIGHT; i++) { lines[i] = '*'; }   // calculate cantor(0, WIDTH, 1);   // print for (int i = 0; i < HEIGHT*WIDTH; i += WIDTH) { printf("%.*s\n", WIDTH, lines + i); }   return 0; }
http://rosettacode.org/wiki/Calkin-Wilf_sequence
Calkin-Wilf sequence
The Calkin-Wilf sequence contains every nonnegative rational number exactly once. It can be calculated recursively as follows: a1 = 1 an+1 = 1/(2⌊an⌋+1-an) for n > 1 Task part 1 Show on this page terms 1 through 20 of the Calkin-Wilf sequence. To avoid floating point error, you may want to 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
#Factor
Factor
USING: formatting io kernel lists lists.lazy math math.continued-fractions math.functions math.parser prettyprint sequences strings vectors ;   : next-cw ( x -- y ) [ floor dup + ] [ 1 swap - + recip ] bi ;   : calkin-wilf ( -- list ) 1 [ next-cw ] lfrom-by ;   : >continued-fraction ( x -- seq ) 1vector [ dup last integer? ] [ dup next-approx ] until dup length even? [ unclip-last 1 - suffix! 1 suffix! ] when ;   : cw-index ( x -- n ) >continued-fraction <reversed> [ even? CHAR: 1 CHAR: 0 ? <string> ] map-index concat bin> ;   ! Task "First 20 terms of the Calkin-Wilf sequence:" print 20 calkin-wilf ltake [ pprint bl ] leach nl nl   83116/51639 cw-index "83116/51639 is at index %d.\n" printf
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
#Forth
Forth
\ Calkin-Wilf sequence   : frac. swap . ." / " . ; : cw-next ( num den -- num den ) 2dup / over * 2* over + rot - ; : cw-seq ( n -- ) 1 1 rot 0 do cr 2dup frac. cw-next loop 2drop ;   variable index variable bit-state variable bit-position : r2cf-next ( num1 den1 -- num2 den2 u ) swap over >r s>d r> sm/rem ;   : n2bitlength ( n -- ) bit-state @ if 1 swap lshift 1- bit-position @ lshift index +! else drop then ;   : index-init true bit-state ! 0 bit-position ! 0 index ! ; : index-build ( n -- ) dup n2bitlength bit-position +! bit-state @ invert bit-state ! ; : index-finish ( n 0 -- ) 2drop -1 bit-position +! 1 index-build ;   : cw-index ( num den -- ) index-init begin r2cf-next index-build dup 0<> while repeat index-finish ;   : cw-demo 20 cw-seq cr 83116 51639 2dup frac. cw-index index @ . ; cw-demo
http://rosettacode.org/wiki/Canny_edge_detector
Canny edge detector
Task Write a program that performs so-called canny edge detection on an image. A possible algorithm consists of the following steps: Noise reduction.   May be performed by Gaussian filter.   Compute intensity gradient   (matrices G x {\displaystyle G_{x}} and G y {\displaystyle G_{y}} )   and its magnitude   G {\displaystyle G} :           G = G x 2 + G y 2 {\displaystyle G={\sqrt {G_{x}^{2}+G_{y}^{2}}}} May be performed by convolution of an image with Sobel operators.   Non-maximum suppression.   For each pixel compute the orientation of intensity gradient vector:   θ = a t a n 2 ( G y , G x ) {\displaystyle \theta ={\rm {atan2}}\left(G_{y},\,G_{x}\right)} .     Transform   angle θ {\displaystyle \theta }   to one of four directions:   0, 45, 90, 135 degrees.     Compute new array   N {\displaystyle N} :     if         G ( p a ) < G ( p ) < G ( p b ) {\displaystyle G\left(p_{a}\right)<G\left(p\right)<G\left(p_{b}\right)} where   p {\displaystyle p}   is the current pixel,   p a {\displaystyle p_{a}}   and   p b {\displaystyle p_{b}}   are the two neighbour pixels in the direction of gradient,   then     N ( p ) = G ( p ) {\displaystyle N(p)=G(p)} ,       otherwise   N ( p ) = 0 {\displaystyle N(p)=0} .   Nonzero pixels in resulting array correspond to local maxima of   G {\displaystyle G}   in direction   θ ( p ) {\displaystyle \theta (p)} .   Tracing edges with hysteresis.   At this stage two thresholds for the values of   G {\displaystyle G}   are introduced:   T m i n {\displaystyle T_{min}}   and   T m a x {\displaystyle T_{max}} .   Starting from pixels with   N ( p ) ⩾ T m a x {\displaystyle N(p)\geqslant T_{max}} ,   find all paths of pixels with   N ( p ) ⩾ T m i n {\displaystyle N(p)\geqslant T_{min}}   and put them to the resulting image.
#Raku
Raku
#include <stdio.h> #include <string.h> #include <magick/MagickCore.h>   int CannyEdgeDetector( const char *infile, const char *outfile, double radius, double sigma, double lower, double upper ) {   ExceptionInfo *exception; Image *image, *processed_image, *output; ImageInfo *input_info;   exception = AcquireExceptionInfo(); input_info = CloneImageInfo((ImageInfo *) NULL); (void) strcpy(input_info->filename, infile); image = ReadImage(input_info, exception); output = NewImageList(); processed_image = CannyEdgeImage(image,radius,sigma,lower,upper,exception); (void) AppendImageToList(&output, processed_image); (void) strcpy(output->filename, outfile); WriteImage(input_info, output); // after-party clean up DestroyImage(image); output=DestroyImageList(output); input_info=DestroyImageInfo(input_info); exception=DestroyExceptionInfo(exception); MagickCoreTerminus();   return 0; }
http://rosettacode.org/wiki/Canonicalize_CIDR
Canonicalize CIDR
Task Implement a function or program that, given a range of IPv4 addresses in CIDR notation (dotted-decimal/network-bits), will return/output the same range in canonical form. That is, the IP address portion of the output CIDR block must not contain any set (1) bits in the host part of the address. Example Given   87.70.141.1/22,   your code should output   87.70.140.0/22 Explanation An Internet Protocol version 4 address is a 32-bit value, conventionally represented as a number in base 256 using dotted-decimal notation, where each base-256 "digit" is represented by the digit value in decimal and the digits are separated by periods. Logically, this 32-bit value represents two components: the leftmost (most-significant) bits determine the "network" portion of the address, while the rightmost (least-significant) bits determine the "host" portion. Classless Internet Domain Routing block notation indicates where the boundary between these two components is for a given address by adding a slash followed by the number of bits in the network portion. In general, CIDR blocks stand in for the entire set of IP addresses sharing the same "network" component; it's common to see access control lists specify a single IP address using CIDR with /32 to indicate that only the one address is included. Often, the tools using this notation expect the address to be entered in canonical form, in which the "host" bits are all zeroes in the binary representation. But careless network admins may provide CIDR blocks without canonicalizing them first. This task handles the canonicalization. The example address, 87.70.141.1, translates into 01010111010001101000110100000001 in binary notation zero-padded to 32 bits. The /22 means that the first 22 of those bits determine the match; the final 10 bits should be 0. But they instead include two 1 bits: 0100000001. So to canonicalize the address, change those 1's to 0's to yield 01010111010001101000110000000000, which in dotted-decimal is 87.70.140.0. More examples for testing 36.18.154.103/12 → 36.16.0.0/12 62.62.197.11/29 → 62.62.197.8/29 67.137.119.181/4 → 64.0.0.0/4 161.214.74.21/24 → 161.214.74.0/24 184.232.176.184/18 → 184.232.128.0/18
#Phix
Phix
with javascript_semantics -- (not likely useful) function canonicalize_cidr(string cidr) cidr = substitute(cidr,"."," ") -- (else %d eats 0.0 etc) if not find('/',cidr) then cidr &= "/32" end if sequence res = scanf(cidr,"%d %d %d %d/%d") if length(res)=1 then integer {a,b,c,d,m} = res[1] if a>=0 and a<=255 and b>=0 and b<=255 and c>=0 and c<=255 and d>=0 and d<=255 and m>=1 and m<=32 then atom mask = power(2,32-m)-1, addr = bytes_to_int({d,c,b,a}) addr -= and_bits(addr,mask) {d,c,b,a} = int_to_bytes(addr) return sprintf("%d.%d.%d.%d/%d",{a,b,c,d,m}) end if end if return "???" end function constant tests = {"87.70.141.1/22", "36.18.154.103/12", "62.62.197.11/29", "67.137.119.181/4", "161.214.74.21/24", "184.232.176.184/18"} for i=1 to length(tests) do string ti = tests[i] printf(1,"%-18s -> %s\n",{ti,canonicalize_cidr(ti)}) end for
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
#Julia
Julia
co9(x) = x == 9  ? 0 : 1<=x<=8 ? x : co9(sum(digits(x)))
http://rosettacode.org/wiki/Casting_out_nines
Casting out nines
Task   (in three parts) Part 1 Write a procedure (say c o 9 ( x ) {\displaystyle {\mathit {co9}}(x)} ) which implements Casting Out Nines as described by returning the checksum for x {\displaystyle x} . Demonstrate the procedure using the examples given there, or others you may consider lucky. 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
#Kotlin
Kotlin
// version 1.1.3   fun castOut(base: Int, start: Int, end: Int): List<Int> { val b = base - 1 val ran = (0 until b).filter { it % b == (it * it) % b } var x = start / b val result = mutableListOf<Int>() while (true) { for (n in ran) { val k = b * x + n if (k < start) continue if (k > end) return result result.add(k) } x++ } }   fun main(args: Array<String>) { println(castOut(16, 1, 255)) println() println(castOut(10, 1, 99)) println() println(castOut(17, 1, 288)) }
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
#Icon_and_Unicon
Icon and Unicon
link "factors"   procedure main(A) n := integer(!A) | 61 every write(carmichael3(!n)) end   procedure carmichael3(p1) every (isprime(p1), (h := 1+!(p1-1)), (d := !(h+p1-1))) do if (mod(((h+p1)*(p1-1)),d) = 0, mod((-p1*p1),h) = mod(d,h)) then { p2 := 1 + (p1-1)*(h+p1)/d p3 := 1 + p1*p2/h if (isprime(p2), isprime(p3), mod((p2*p3),(p1-1)) = 1) then suspend format(p1,p2,p3) } end   procedure mod(n,d) return (d+n%d)%d end   procedure format(p1,p2,p3) return left(p1||" * "||p2||" * "||p3,20)||" = "||(p1*p2*p3) end
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
#Forth
Forth
: lowercase? ( c -- f ) [char] a [ char z 1+ ] literal within ;   : char-upcase ( c -- C ) dup lowercase? if bl xor then ;
http://rosettacode.org/wiki/Catamorphism
Catamorphism
Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. Task Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language. See also Wikipedia article:   Fold Wikipedia article:   Catamorphism
#Fortran
Fortran
SUBROUTINE FOLD(t,F,i,ist,lst) INTEGER t BYNAME F DO i = ist,lst t = F END DO END SUBROUTINE FOLD !Result in temp.   temp = a(1); CALL FOLD(temp,temp*a(i),i,2,N)
http://rosettacode.org/wiki/Chaocipher
Chaocipher
Description The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010. The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here. Task Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.
#zkl
zkl
class Chao{ var [const private] lAlphabet = "HXUCZVAMDSLKPEFJRIGTWOBNYQ", rAlphabet = "PTLNBQDEOYSFAVZKGJRIHWXUMC"; fcn encode(text){ code(text,encodeL); } fcn decode(text){ code(text,decodeL); } // reset alphabets each [en|de]code and maintain re-entrancy fcn code(text,f){ text.apply(f,Data(Void,lAlphabet),Data(Void,rAlphabet)) } fcn [private] encodeL(letter,left,right){ // encode a letter index:=right.index(letter); enc  :=left[index].toChar(); permute(left,right,index); println(left.text," ",right.text," ",index); enc } fcn [private] decodeL(letter,left,right){ // decode a letter index:=left.index(letter); dec  :=right[index].toChar(); permute(left,right,index); dec } fcn [private] permute(left,right,index){ left.append(left.pop(0,index)); // rotate index times left.insert(13,left.pop(1)); // rotate [1..13] once   right.append(right.pop(0,index+1)); # rotate index+1 times, idx==25==noop right.insert(13,right.pop(2)); // rotate [2..13] once } }
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
#Phix
Phix
constant N = 15 -- accurate to 30, nan/inf for anything over 514 (gmp version is below). sequence catalan = {}, -- (>=1 only) p = repeat(1,N+1) atom p1 for i=1 to N do p1 = p[1]*2 catalan = append(catalan,p1-p[2]) for j=1 to N-i+1 do p1 += p[j+1] p[j] = p1 end for --  ?p[1..N-i+1] end for ?catalan
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
#PicoLisp
PicoLisp
(de bino (N K) (let f '((N) (if (=0 N) 1 (apply * (range 1 N))) ) (/ (f N) (* (f (- N K)) (f K)) ) ) )   (for N 15 (println (- (bino (* 2 N) N) (bino (* 2 N) (inc N)) ) ) ) (bye)
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#Modula-2
Modula-2
MODULE dog;   IMPORT InOut;   TYPE String = ARRAY [0..31] OF CHAR;   VAR dog, Dog, DOG : String;   (* No compiler error, so the rest is simple *)   BEGIN InOut.WriteString ("Three happy dogs."); InOut.WriteLn END dog.
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#Nanoquery
Nanoquery
dog = "Benjamin" Dog = "Samba" DOG = "Bernie"   print format("The three dogs are named %s, %s, and %s.\n", dog, Dog, DOG)
http://rosettacode.org/wiki/Case-sensitivity_of_identifiers
Case-sensitivity of identifiers
Three dogs (Are there three dogs or one dog?) is a code snippet used to illustrate the lettercase sensitivity of the programming language. For a case-sensitive language, the identifiers dog, Dog and DOG are all different and we should get the output: The three dogs are named Benjamin, Samba and Bernie. For a language that is lettercase insensitive, we get the following output: There is just one dog named Bernie. Related task Unicode variable names
#Nemerle
Nemerle
def dog = "Benjamin"; def Dog = "Samba"; def DOG = "Bernie"; WriteLine($"The three dogs are named $dog, $Dog, and $DOG");
http://rosettacode.org/wiki/Cartesian_product_of_two_or_more_lists
Cartesian product of two or more lists
Task Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language. Demonstrate that your function/method correctly returns: {1, 2} × {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)} and, in contrast: {3, 4} × {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)} Also demonstrate, using 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}
#J
J
{ 1776 1789 ; 7 12 ; 4 14 23 ; 0 1 NB. result is 4 dimensional array with shape 2 2 3 2 ┌────────────┬────────────┐ │1776 7 4 0 │1776 7 4 1 │ ├────────────┼────────────┤ │1776 7 14 0 │1776 7 14 1 │ ├────────────┼────────────┤ │1776 7 23 0 │1776 7 23 1 │ └────────────┴────────────┘   ┌────────────┬────────────┐ │1776 12 4 0 │1776 12 4 1 │ ├────────────┼────────────┤ │1776 12 14 0│1776 12 14 1│ ├────────────┼────────────┤ │1776 12 23 0│1776 12 23 1│ └────────────┴────────────┘     ┌────────────┬────────────┐ │1789 7 4 0 │1789 7 4 1 │ ├────────────┼────────────┤ │1789 7 14 0 │1789 7 14 1 │ ├────────────┼────────────┤ │1789 7 23 0 │1789 7 23 1 │ └────────────┴────────────┘   ┌────────────┬────────────┐ │1789 12 4 0 │1789 12 4 1 │ ├────────────┼────────────┤ │1789 12 14 0│1789 12 14 1│ ├────────────┼────────────┤ │1789 12 23 0│1789 12 23 1│ └────────────┴────────────┘ { 1 2 3 ; 30 ; 50 100 NB. result is a 2-dimensional array with shape 2 3 ┌───────┬────────┐ │1 30 50│1 30 100│ ├───────┼────────┤ │2 30 50│2 30 100│ ├───────┼────────┤ │3 30 50│3 30 100│ └───────┴────────┘ { 1 2 3 ; '' ; 50 100 NB. result is an empty 3-dimensional array with shape 3 0 2  
http://rosettacode.org/wiki/Catalan_numbers
Catalan numbers
Catalan numbers You are encouraged to solve this task according to the task description, using any language you may know. Catalan numbers are a sequence of numbers which can be defined directly: C n = 1 n + 1 ( 2 n n ) = ( 2 n ) ! ( n + 1 ) ! n !  for  n ≥ 0. {\displaystyle C_{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
#C
C
#include <stdio.h>   typedef unsigned long long ull;   ull binomial(ull m, ull n) { ull r = 1, d = m - n; if (d > n) { n = d; d = m - n; }   while (m > n) { r *= m--; while (d > 1 && ! (r%d) ) r /= d--; }   return r; }   ull catalan1(int n) { return binomial(2 * n, n) / (1 + n); }   ull catalan2(int n) { int i; ull r = !n;   for (i = 0; i < n; i++) r += catalan2(i) * catalan2(n - 1 - i); return r; }   ull catalan3(int n) { return n ? 2 * (2 * n - 1) * catalan3(n - 1) / (1 + n) : 1; }   int main(void) { int i; puts("\tdirect\tsumming\tfrac"); for (i = 0; i < 16; i++) { printf("%d\t%llu\t%llu\t%llu\n", i, catalan1(i), catalan2(i), catalan3(i)); }   return 0; }
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#Forth
Forth
include lib/compare.4th include 4pp/lib/foos.4pp   [ASSERT] \ enable assertions   :: Cat class method: dynamicCat \ virtual method end-class {    :static staticCat { 2 } ; \ static method  :method { s" Mew!" } ; defines dynamicCat } \ for unrelated classes, ; \ method names have to differ   :: Dog class method: dynamicDog \ virtual method end-class {    :static staticDog { 5 } ;  :method { s" Woof!" } ; defines dynamicDog } \ for unrelated classes, ; \ method names have to differ   static Cat c \ create two static objects static Dog d   : main assert( class -> staticCat 2 = ) \ check for valid method return assert( class -> staticDog 5 = ) \ of a static method   assert( c -> staticCat 2 = ) \ check for valid method return assert( d -> staticDog 5 = ) \ of a static method   assert( c => dynamicCat s" Mew!" compare 0= ) assert( d => dynamicDog s" Woof!" compare 0= ) ; \ same for dynamic methods   main
http://rosettacode.org/wiki/Call_an_object_method
Call an object method
In object-oriented programming a method is a function associated with a particular class or object. In most forms of object oriented implementations methods can be static, associated with the class itself; or instance, associated with an instance of a class. Show how to call a static or class method, and an instance method of a class.
#Fortran
Fortran
  ! type declaration type my_type contains procedure, pass :: method1 procedure, pass, pointer :: method2 end type my_type   ! declare object of type my_type type(my_type) :: mytype_object   !static call call mytype_object%method1() ! call method1 defined as subroutine !instance? mytype_object%method2() ! call method2 defined as function