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/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, as a type, has the values and operations of its own. The operations of are usually called methods of the root type. Both operations and values are called polymorphic. A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument. The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual. Operations with multiple arguments and/or the results of the class are called multi-methods. A further generalization of is the operation with arguments and/or results from different classes. single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x). multiple-dispatch languages allow many arguments and/or results to control the dispatch. A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type. This type is sometimes called the most specific type of a [polymorphic] value. The type tag of the value is used in order to resolve the dispatch. The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class. In many OO languages the type of the class of T and T itself are considered equivalent. In some languages they are distinct (like in Ada). When class T and T are equivalent, there is no way to distinguish polymorphic and specific values. Task Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
#BaCon
BaCon
  PRAGMA COMPILER g++ PRAGMA OPTIONS -Wno-write-strings -Wno-pointer-arith -fpermissive   OPTION PARSE FALSE     '---The class does the declaring for you   CLASS Books public: const char* title; const char* author; const char* subject; int book_id; END CLASS     '---pointer to an object declaration (we use a class called Books) DECLARE Book1 TYPE Books '--- the correct syntax for class Book1 = Books()     '--- initialize the strings const char* in c++ Book1.title = "C++ Programming to bacon " Book1.author = "anyone" Book1.subject ="RECORD Tutorial" Book1.book_id = 1234567     PRINT "Book title  : " ,Book1.title FORMAT "%s%s\n" PRINT "Book author  : ", Book1.author FORMAT "%s%s\n" PRINT "Book subject : ", Book1.subject FORMAT "%s%s\n" PRINT "Book book_id : ", Book1.book_id FORMAT "%s%d\n"  
http://rosettacode.org/wiki/Cistercian_numerals
Cistercian numerals
Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999. How they work All Cistercian numerals begin with a vertical line segment, which by itself represents the number 0. Then, glyphs representing the digits 1 through 9 are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number: The upper-right quadrant represents the ones place. The upper-left quadrant represents the tens place. The lower-right quadrant represents the hundreds place. The lower-left quadrant represents the thousands place. Please consult the following image for examples of Cistercian numerals showing each glyph: [1] Task Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile). Use the routine to show the following Cistercian numerals: 0 1 20 300 4000 5555 6789 And a number of your choice! Notes Due to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed — especially for text output. See also Numberphile - The Forgotten Number System dcode.fr - Online Cistercian numeral converter
#D
D
import std.stdio;   class Cistercian { private immutable SIZE = 15; private char[SIZE][SIZE] canvas;   public this(int n) { initN(); draw(n); }   private void initN() { foreach (ref row; canvas) { row[] = ' '; row[5] = 'x'; } }   private void horizontal(int c1, int c2, int r) { for (int c = c1; c <= c2; c++) { canvas[r][c] = 'x'; } }   private void vertical(int r1, int r2, int c) { for (int r = r1; r <= r2; r++) { canvas[r][c] = 'x'; } }   private void diagd(int c1, int c2, int r) { for (int c = c1; c <= c2; c++) { canvas[r + c - c1][c] = 'x'; } }   private void diagu(int c1, int c2, int r) { for (int c = c1; c <= c2; c++) { canvas[r - c + c1][c] = 'x'; } }   private void draw(int v) { auto thousands = v / 1000; v %= 1000;   auto hundreds = v / 100; v %= 100;   auto tens = v / 10; auto ones = v % 10;   drawPart(1000 * thousands); drawPart(100 * hundreds); drawPart(10 * tens); drawPart(ones); }   private void drawPart(int v) { switch(v) { case 0: break;   case 1: horizontal(6, 10, 0); break; case 2: horizontal(6, 10, 4); break; case 3: diagd(6, 10, 0); break; case 4: diagu(6, 10, 4); break; case 5: drawPart(1); drawPart(4); break; case 6: vertical(0, 4, 10); break; case 7: drawPart(1); drawPart(6); break; case 8: drawPart(2); drawPart(6); break; case 9: drawPart(1); drawPart(8); break;   case 10: horizontal(0, 4, 0); break; case 20: horizontal(0, 4, 4); break; case 30: diagu(0, 4, 4); break; case 40: diagd(0, 4, 0); break; case 50: drawPart(10); drawPart(40); break; case 60: vertical(0, 4, 0); break; case 70: drawPart(10); drawPart(60); break; case 80: drawPart(20); drawPart(60); break; case 90: drawPart(10); drawPart(80); break;   case 100: horizontal(6, 10, 14); break; case 200: horizontal(6, 10, 10); break; case 300: diagu(6, 10, 14); break; case 400: diagd(6, 10, 10); break; case 500: drawPart(100); drawPart(400); break; case 600: vertical(10, 14, 10); break; case 700: drawPart(100); drawPart(600); break; case 800: drawPart(200); drawPart(600); break; case 900: drawPart(100); drawPart(800); break;   case 1000: horizontal(0, 4, 14); break; case 2000: horizontal(0, 4, 10); break; case 3000: diagd(0, 4, 10); break; case 4000: diagu(0, 4, 14); break; case 5000: drawPart(1000); drawPart(4000); break; case 6000: vertical(10, 14, 0); break; case 7000: drawPart(1000); drawPart(6000); break; case 8000: drawPart(2000); drawPart(6000); break; case 9000: drawPart(1000); drawPart(8000); break;   default: import std.conv; assert(false, "Not handled: " ~ v.to!string); } }   public void toString(scope void delegate(const(char)[]) sink) const { foreach (row; canvas) { sink(row); sink("\n"); } } }   void main() { foreach (number; [0, 1, 20, 300, 4000, 5555, 6789, 9999]) { writeln(number, ':'); auto c = new Cistercian(number); writeln(c); } }
http://rosettacode.org/wiki/Colour_bars/Display
Colour bars/Display
Task Display a series of vertical color bars across the width of the display. The color bars should either use:   the system palette,   or   the sequence of colors:   black   red   green   blue   magenta   cyan   yellow   white
#R
R
  pal <- c("black", "red", "green", "blue", "magenta", "cyan", "yellow", "white") par(mar = rep(0, 4)) image(matrix(1:8), col = pal, axes = FALSE)  
http://rosettacode.org/wiki/Colour_bars/Display
Colour bars/Display
Task Display a series of vertical color bars across the width of the display. The color bars should either use:   the system palette,   or   the sequence of colors:   black   red   green   blue   magenta   cyan   yellow   white
#Racket
Racket
  #lang racket/gui   (define-values [W H] (get-display-size #t))   (define colors '("Black" "Red" "Green" "Blue" "Magenta" "Cyan" "Yellow" "White"))   (define (paint-pinstripe canvas dc) (send dc set-pen "black" 0 'transparent) (for ([x (in-range 0 W (/ W (length colors)))] [c colors]) (send* dc (set-brush c 'solid) (draw-rectangle x 0 W H))))   (define full-frame% (class frame% (define/override (on-subwindow-char r e) (when (eq? 'escape (send e get-key-code)) (send this show #f))) (super-new [label "Color bars"] [width W] [height H] [style '(no-caption no-resize-border hide-menu-bar no-system-menu)]) (define c (new canvas% [parent this] [paint-callback paint-pinstripe])) (send this show #t)))   (void (new full-frame%))  
http://rosettacode.org/wiki/Colour_bars/Display
Colour bars/Display
Task Display a series of vertical color bars across the width of the display. The color bars should either use:   the system palette,   or   the sequence of colors:   black   red   green   blue   magenta   cyan   yellow   white
#Raku
Raku
my ($x,$y) = 1280, 720;   my @colors = map -> $r, $g, $b { Buf.new: |(($r, $g, $b) xx $x div 8) }, 0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 0, 255, 0, 255, 255, 255, 255, 0, 255, 255, 255;   my $img = open "colorbars.ppm", :w orelse die "Can't create colorbars.ppm: $_";   $img.print: qq:to/EOH/; P6 # colorbars.ppm $x $y 255 EOH   for ^$y { for ^@colors -> $h { $img.write: @colors[$h]; } }   $img.close;
http://rosettacode.org/wiki/Closest-pair_problem
Closest-pair problem
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a function to find the closest two points among a set of given points in two dimensions,   i.e. to solve the   Closest pair of points problem   in the   planar   case. The straightforward solution is a   O(n2)   algorithm   (which we can call brute-force algorithm);   the pseudo-code (using indexes) could be simply: bruteForceClosestPair of P(1), P(2), ... P(N) if N < 2 then return ∞ else minDistance ← |P(1) - P(2)| minPoints ← { P(1), P(2) } foreach i ∈ [1, N-1] foreach j ∈ [i+1, N] if |P(i) - P(j)| < minDistance then minDistance ← |P(i) - P(j)| minPoints ← { P(i), P(j) } endif endfor endfor return minDistance, minPoints endif A better algorithm is based on the recursive divide&conquer approach,   as explained also at   Wikipedia's Closest pair of points problem,   which is   O(n log n);   a pseudo-code could be: closestPair of (xP, yP) where xP is P(1) .. P(N) sorted by x coordinate, and yP is P(1) .. P(N) sorted by y coordinate (ascending order) if N ≤ 3 then return closest points of xP using brute-force algorithm else xL ← points of xP from 1 to ⌈N/2⌉ xR ← points of xP from ⌈N/2⌉+1 to N xm ← xP(⌈N/2⌉)x yL ← { p ∈ yP : px ≤ xm } yR ← { p ∈ yP : px > xm } (dL, pairL) ← closestPair of (xL, yL) (dR, pairR) ← closestPair of (xR, yR) (dmin, pairMin) ← (dR, pairR) if dL < dR then (dmin, pairMin) ← (dL, pairL) endif yS ← { p ∈ yP : |xm - px| < dmin } nS ← number of points in yS (closest, closestPair) ← (dmin, pairMin) for i from 1 to nS - 1 k ← i + 1 while k ≤ nS and yS(k)y - yS(i)y < dmin if |yS(k) - yS(i)| < closest then (closest, closestPair) ← (|yS(k) - yS(i)|, {yS(k), yS(i)}) endif k ← k + 1 endwhile endfor return closest, closestPair endif References and further readings   Closest pair of points problem   Closest Pair (McGill)   Closest Pair (UCSB)   Closest pair (WUStL)   Closest pair (IUPUI)
#BBC_BASIC
BBC BASIC
DIM x(9), y(9)   FOR I% = 0 TO 9 READ x(I%), y(I%) NEXT   min = 1E30 FOR I% = 0 TO 8 FOR J% = I%+1 TO 9 dsq = (x(I%) - x(J%))^2 + (y(I%) - y(J%))^2 IF dsq < min min = dsq : mini% = I% : minj% = J% NEXT NEXT I% PRINT "Closest pair is ";mini% " and ";minj% " at distance "; SQR(min) END   DATA 0.654682, 0.925557 DATA 0.409382, 0.619391 DATA 0.891663, 0.888594 DATA 0.716629, 0.996200 DATA 0.477721, 0.946355 DATA 0.925092, 0.818220 DATA 0.624291, 0.142924 DATA 0.211332, 0.221507 DATA 0.293786, 0.691701 DATA 0.839186, 0.728260  
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of running any but the last function, to demonstrate that the function indeed remembers its value. Goal Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. In imperative languages, one would generally use a loop with a mutable counter variable. For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run. See also: Multiple distinct objects
#Fantom
Fantom
  class Closures { Void main () { // define a list of functions, which take no arguments and return an Int |->Int|[] functions := [,]   // create and store a function which returns i*i for i in 0 to 10 (0..10).each |Int i| { functions.add (|->Int| { i*i }) }   // show result of calling function at index position 7 echo ("Function at index: " + 7 + " outputs " + functions[7].call) } }  
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of running any but the last function, to demonstrate that the function indeed remembers its value. Goal Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. In imperative languages, one would generally use a loop with a mutable counter variable. For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run. See also: Multiple distinct objects
#Forth
Forth
: xt-array here { a } 10 cells allot 10 0 do :noname i ]] literal dup * ; [[ a i cells + ! loop a ;   xt-array 5 cells + @ execute .
http://rosettacode.org/wiki/Circular_primes
Circular primes
Definitions A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime. For example: 1193 is a circular prime, since 1931, 9311 and 3119 are all also prime. Note that a number which is a cyclic permutation of a smaller circular prime is not considered to be itself a circular prime. So 13 is a circular prime, but 31 is not. A repunit (denoted by R) is a number whose base 10 representation contains only the digit 1. For example: R(2) = 11 and R(5) = 11111 are repunits. Task Find the first 19 circular primes. If your language has access to arbitrary precision integer arithmetic, given that they are all repunits, find the next 4 circular primes. (Stretch) Determine which of the following repunits are probably circular primes: R(5003), R(9887), R(15073), R(25031), R(35317) and R(49081). The larger ones may take a long time to process so just do as many as you reasonably can. See also Wikipedia article - Circular primes. Wikipedia article - Repunit. OEIS sequence A016114 - Circular primes.
#Haskell
Haskell
import Math.NumberTheory.Primes (Prime, unPrime, nextPrime) import Math.NumberTheory.Primes.Testing (isPrime, millerRabinV) import Text.Printf (printf)   rotated :: [Integer] -> [Integer] rotated xs | any (< head xs) xs = [] | otherwise = map asNum $ take (pred $ length xs) $ rotate xs where rotate [] = [] rotate (d:ds) = ds <> [d] : rotate (ds <> [d])   asNum :: [Integer] -> Integer asNum [] = 0 asNum n@(d:ds) | all (==1) n = read $ concatMap show n | otherwise = (d * (10 ^ length ds)) + asNum ds   digits :: Integer -> [Integer] digits 0 = [] digits n = digits d <> [r] where (d, r) = n `quotRem` 10   isCircular :: Bool -> Integer -> Bool isCircular repunit n | repunit = millerRabinV 0 n | n < 10 = True | even n = False | null rotations = False | any (<n) rotations = False | otherwise = all isPrime rotations where rotations = rotated $ digits n   repunits :: [Integer] repunits = go 2 where go n = asNum (replicate n 1) : go (succ n)   asRepunit :: Int -> Integer asRepunit n = asNum $ replicate n 1   main :: IO () main = do printf "The first 19 circular primes are:\n%s\n\n" $ circular primes printf "The next 4 circular primes, in repunit format are:\n" mapM_ (printf "R(%d) ") $ reps repunits printf "\n\nThe following repunits are probably circular primes:\n" mapM_ (uncurry (printf "R(%d) : %s\n") . checkReps) [5003, 9887, 15073, 25031, 35317, 49081] where primes = map unPrime [nextPrime 1..] circular = show . take 19 . filter (isCircular False) reps = map (sum . digits). tail . take 5 . filter (isCircular True) checkReps = (,) <$> id <*> show . isCircular True . asRepunit
http://rosettacode.org/wiki/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a few values to it. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Axe
Axe
1→{L₁} 2→{L₁+1} 3→{L₁+2} 4→{L₁+3} Disp {L₁}►Dec,i Disp {L₁+1}►Dec,i Disp {L₁+2}►Dec,i Disp {L₁+3}►Dec,i
http://rosettacode.org/wiki/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 If it is more "natural" in your language to start counting from   1   (unity) instead of   0   (zero), the combinations can be of the integers from   1   to   n. See also The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#Glee
Glee
5!3 >>> ,,\   $$(5!3) give all combinations of 3 out of 5 $$(>>>) sorted up, $$(,,\) printed with crlf delimiters.
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include if-then-else and switch. Less common are arithmetic if, ternary operator and Hash-based conditionals. Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
#PARI.2FGP
PARI/GP
if(condition, do_if_true, do_if_false)
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#TorqueScript
TorqueScript
//This is a one line comment. There are no other commenting options in TorqueScript.
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#TPP
TPP
--## comments are prefixed with a long handed double paintbrush
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Transd
Transd
// This is a line comment. /* This is a single line block comment.*/ /* This is a multi-line block comment.*/  
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, as a type, has the values and operations of its own. The operations of are usually called methods of the root type. Both operations and values are called polymorphic. A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument. The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual. Operations with multiple arguments and/or the results of the class are called multi-methods. A further generalization of is the operation with arguments and/or results from different classes. single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x). multiple-dispatch languages allow many arguments and/or results to control the dispatch. A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type. This type is sometimes called the most specific type of a [polymorphic] value. The type tag of the value is used in order to resolve the dispatch. The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class. In many OO languages the type of the class of T and T itself are considered equivalent. In some languages they are distinct (like in Ada). When class T and T are equivalent, there is no way to distinguish polymorphic and specific values. Task Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
#BASIC
BASIC
DECLARE SUB MyClassDelete (pthis AS MyClass) DECLARE SUB MyClassSomeMethod (pthis AS MyClass) DECLARE SUB MyClassInit (pthis AS MyClass)   TYPE MyClass Variable AS INTEGER END TYPE   DIM obj AS MyClass MyClassInit obj MyClassSomeMethod obj   SUB MyClassInit (pthis AS MyClass) pthis.Variable = 0 END SUB   SUB MyClassSomeMethod (pthis AS MyClass) pthis.Variable = 1 END SUB
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, as a type, has the values and operations of its own. The operations of are usually called methods of the root type. Both operations and values are called polymorphic. A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument. The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual. Operations with multiple arguments and/or the results of the class are called multi-methods. A further generalization of is the operation with arguments and/or results from different classes. single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x). multiple-dispatch languages allow many arguments and/or results to control the dispatch. A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type. This type is sometimes called the most specific type of a [polymorphic] value. The type tag of the value is used in order to resolve the dispatch. The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class. In many OO languages the type of the class of T and T itself are considered equivalent. In some languages they are distinct (like in Ada). When class T and T are equivalent, there is no way to distinguish polymorphic and specific values. Task Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"CLASSLIB"   REM Declare the class: DIM MyClass{variable, @constructor, _method} DEF MyClass.@constructor MyClass.variable = PI : ENDPROC DEF MyClass._method = MyClass.variable ^ 2   REM Register the class: PROC_class(MyClass{})   REM Instantiate the class: PROC_new(myclass{}, MyClass{})   REM Call the method: PRINT FN(myclass._method)   REM Discard the instance: PROC_discard(myclass{})
http://rosettacode.org/wiki/Cistercian_numerals
Cistercian numerals
Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999. How they work All Cistercian numerals begin with a vertical line segment, which by itself represents the number 0. Then, glyphs representing the digits 1 through 9 are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number: The upper-right quadrant represents the ones place. The upper-left quadrant represents the tens place. The lower-right quadrant represents the hundreds place. The lower-left quadrant represents the thousands place. Please consult the following image for examples of Cistercian numerals showing each glyph: [1] Task Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile). Use the routine to show the following Cistercian numerals: 0 1 20 300 4000 5555 6789 And a number of your choice! Notes Due to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed — especially for text output. See also Numberphile - The Forgotten Number System dcode.fr - Online Cistercian numeral converter
#F.23
F#
  // Cistercian numerals. Nigel Galloway: February 2nd., 2021 let N=[|[[|' ';' ';' '|];[|' ';' ';' '|];[|' ';' ';' '|]]; [[|'#';'#';'#'|];[|' ';' ';' '|];[|' ';' ';' '|]]; [[|' ';' ';' '|];[|'#';'#';'#'|];[|' ';' ';' '|]]; [[|'#';' ';' '|];[|' ';'#';' '|];[|' ';' ';'#'|]]; [[|' ';' ';'#'|];[|' ';'#';' '|];[|'#';' ';' '|]]; [[|'#';'#';'#'|];[|' ';'#';' '|];[|'#';' ';' '|]]; [[|' ';' ';'#'|];[|' ';' ';'#'|];[|' ';' ';'#'|]]; [[|'#';'#';'#'|];[|' ';' ';'#'|];[|' ';' ';'#'|]]; [[|' ';' ';'#'|];[|' ';' ';'#'|];[|'#';'#';'#'|]]; [[|'#';'#';'#'|];[|' ';' ';'#'|];[|'#';'#';'#'|]];|]   let fN i g e l=N.[l]|>List.iter2(fun n g->printfn "%sO%s" ((Array.rev>>System.String)n) (System.String g)) N.[e] printfn " O" N.[g]|>List.rev|>List.iter2(fun n g->printfn "%sO%s" ((Array.rev>>System.String)n) (System.String g)) (N.[i]|>List.rev)   [(0,0,0,0);(0,0,0,1);(0,0,2,0);(0,3,0,0);(4,0,0,0);(5,5,5,5);(6,7,8,9)]|>List.iter(fun(i,g,e,l)->printfn "\n%d%d%d%d\n____" i g e l; fN i g e l)  
http://rosettacode.org/wiki/Colour_bars/Display
Colour bars/Display
Task Display a series of vertical color bars across the width of the display. The color bars should either use:   the system palette,   or   the sequence of colors:   black   red   green   blue   magenta   cyan   yellow   white
#REXX
REXX
/*REXX program displays eight colored vertical bars on a full screen. */ parse value scrsize() with sd sw . /*the screen depth and width. */ barWidth=sw%8 /*calculate the bar width. */ _.=copies('db'x, barWidth) /*the bar, full width. */ _.8=left(_.,barWidth-1) /*the last bar width, less one. */ $ = x2c('1b5b73') || x2c("1b5b313b33376d") /* the preamble, and the header. */ hdr.1 = x2c('1b5b303b33306d') /* " color black. */ hdr.2 = x2c('1b5b313b33316d') /* " color red. */ hdr.3 = x2c('1b5b313b33326d') /* " color green. */ hdr.4 = x2c('1b5b313b33346d') /* " color blue. */ hdr.5 = x2c('1b5b313b33356d') /* " color magenta. */ hdr.6 = x2c('1b5b313b33366d') /* " color cyan. */ hdr.7 = x2c('1b5b313b33336d') /* " color yellow. */ hdr.8 = x2c('1b5b313b33376d') /* " color white. */ tail = x2c('1b5b751b5b303b313b33363b34303b306d') /* " epilogue, and the trailer.*/ /* [↓] last bar width is shrunk. */ do j=1 for 8 /*build the line, color by color. */ $=$ || hdr.j || _.j /*append the color header + bar. */ end /*j*/ /* [↑] color order is the list. */ /* [↓] the tail is overkill. */ $=$ || tail /*append the epilogue (trailer). */ /* [↓] show full screen of bars. */ do k=1 for sd /*SD = screen depth (from above). */ say $ /*have REXX display line of bars. */ end /*k*/ /* [↑] Note: SD could be zero. */ /*stick a fork in it, we're done. */
http://rosettacode.org/wiki/Colour_bars/Display
Colour bars/Display
Task Display a series of vertical color bars across the width of the display. The color bars should either use:   the system palette,   or   the sequence of colors:   black   red   green   blue   magenta   cyan   yellow   white
#Ring
Ring
  load "guilib.ring"   new qapp { win1 = new qwidget() { setwindowtitle("drawing using qpainter") setwinicon(self,"C:\Ring\bin\image\browser.png") setgeometry(100,100,500,600) label1 = new qlabel(win1) { setgeometry(10,10,400,400) settext("") } new qpushbutton(win1) { setgeometry(200,400,100,30) settext("draw") setclickevent("draw()") } show() } exec() }   func draw p1 = new qpicture() color = new qcolor() { setrgb(0,0,255,255) } pen = new qpen() { setcolor(color) setwidth(1) } new qpainter() { begin(p1) setpen(pen)   //Black, Red, Green, Blue, Magenta, Cyan, Yellow, White   for n = 1 to 8 color2 = new qcolor(){ switch n on 1 r=0 g=0 b=0 on 2 r=255 g=0 b=0 on 3 r=0 g=255 b=0 on 4 r=0 g=0 b=255 on 5 r=255 g=0 b=255 on 6 r=0 g=255 b=255 on 7 r=255 g=255 b=0 on 8 r=255 g=255 b=255 off setrgb(r,g,b,255) } mybrush = new qbrush() {setstyle(1) setcolor(color2)} setbrush(mybrush) drawrect(n*25,25,25,70) next   endpaint() } label1 { setpicture(p1) show() }  
http://rosettacode.org/wiki/Closest-pair_problem
Closest-pair problem
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a function to find the closest two points among a set of given points in two dimensions,   i.e. to solve the   Closest pair of points problem   in the   planar   case. The straightforward solution is a   O(n2)   algorithm   (which we can call brute-force algorithm);   the pseudo-code (using indexes) could be simply: bruteForceClosestPair of P(1), P(2), ... P(N) if N < 2 then return ∞ else minDistance ← |P(1) - P(2)| minPoints ← { P(1), P(2) } foreach i ∈ [1, N-1] foreach j ∈ [i+1, N] if |P(i) - P(j)| < minDistance then minDistance ← |P(i) - P(j)| minPoints ← { P(i), P(j) } endif endfor endfor return minDistance, minPoints endif A better algorithm is based on the recursive divide&conquer approach,   as explained also at   Wikipedia's Closest pair of points problem,   which is   O(n log n);   a pseudo-code could be: closestPair of (xP, yP) where xP is P(1) .. P(N) sorted by x coordinate, and yP is P(1) .. P(N) sorted by y coordinate (ascending order) if N ≤ 3 then return closest points of xP using brute-force algorithm else xL ← points of xP from 1 to ⌈N/2⌉ xR ← points of xP from ⌈N/2⌉+1 to N xm ← xP(⌈N/2⌉)x yL ← { p ∈ yP : px ≤ xm } yR ← { p ∈ yP : px > xm } (dL, pairL) ← closestPair of (xL, yL) (dR, pairR) ← closestPair of (xR, yR) (dmin, pairMin) ← (dR, pairR) if dL < dR then (dmin, pairMin) ← (dL, pairL) endif yS ← { p ∈ yP : |xm - px| < dmin } nS ← number of points in yS (closest, closestPair) ← (dmin, pairMin) for i from 1 to nS - 1 k ← i + 1 while k ≤ nS and yS(k)y - yS(i)y < dmin if |yS(k) - yS(i)| < closest then (closest, closestPair) ← (|yS(k) - yS(i)|, {yS(k), yS(i)}) endif k ← k + 1 endwhile endfor return closest, closestPair endif References and further readings   Closest pair of points problem   Closest Pair (McGill)   Closest Pair (UCSB)   Closest pair (WUStL)   Closest pair (IUPUI)
#C
C
class Segment { public Segment(PointF p1, PointF p2) { P1 = p1; P2 = p2; }   public readonly PointF P1; public readonly PointF P2;   public float Length() { return (float)Math.Sqrt(LengthSquared()); }   public float LengthSquared() { return (P1.X - P2.X) * (P1.X - P2.X) + (P1.Y - P2.Y) * (P1.Y - P2.Y); } }
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of running any but the last function, to demonstrate that the function indeed remembers its value. Goal Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. In imperative languages, one would generally use a loop with a mutable counter variable. For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run. See also: Multiple distinct objects
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Type Closure Private: index As Integer Public: Declare Constructor(index As Integer = 0) Declare Function Square As Integer End Type   Constructor Closure(index As Integer = 0) This.index = index End Constructor   Function Closure.Square As Integer Return index * index End Function   Dim a(1 To 10) As Closure   ' create Closure objects which capture their index For i As Integer = 1 To 10 a(i) = Closure(i) Next   ' call the Square method on all but the last object For i As Integer = 1 to 9 Print a(i).Square Next   Print Print "Press any key to quit" Sleep
http://rosettacode.org/wiki/Circular_primes
Circular primes
Definitions A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime. For example: 1193 is a circular prime, since 1931, 9311 and 3119 are all also prime. Note that a number which is a cyclic permutation of a smaller circular prime is not considered to be itself a circular prime. So 13 is a circular prime, but 31 is not. A repunit (denoted by R) is a number whose base 10 representation contains only the digit 1. For example: R(2) = 11 and R(5) = 11111 are repunits. Task Find the first 19 circular primes. If your language has access to arbitrary precision integer arithmetic, given that they are all repunits, find the next 4 circular primes. (Stretch) Determine which of the following repunits are probably circular primes: R(5003), R(9887), R(15073), R(25031), R(35317) and R(49081). The larger ones may take a long time to process so just do as many as you reasonably can. See also Wikipedia article - Circular primes. Wikipedia article - Repunit. OEIS sequence A016114 - Circular primes.
#J
J
    R=: [: ". 'x' ,~ #&'1' assert 11111111111111111111111111111111x -: R 32   Filter=: (#~`)(`:6)   rotations=: (|."0 1~ i.@#)&.(10&#.inv) assert 123 231 312 -: rotations 123   primes_less_than=: i.&.:(p:inv) assert 2 3 5 7 11 -: primes_less_than 12     NB. circular y --> y is the order of magnitude. circular=: monad define P25=: ([: -. (0 e. 1 3 7 9 e.~ 10 #.inv ])&>)Filter primes_less_than 10^y NB. Q25 are primes with 1 3 7 9 digits P=: 2 5 , P25 en=: # P group=: en # 0 next=: 1 for_i. i. # group do. if. 0 = i { group do. NB. if untested j =: P i. rotations i { P NB. j are the indexes of the rotated numbers in the list of primes if. en e. j do. NB. if any are unfound j=: j -. en NB. prepare to mark them all as searched, and failed. g=: _1 else. g=: next NB. mark the set as found in a new group. Because we can. next=: >: next end. group=: g j} group NB. apply the tested mark end. end. group </. P )  
http://rosettacode.org/wiki/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a few values to it. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#BBC_BASIC
BBC BASIC
DIM text$(1) text$(0) = "Hello " text$(1) = "world!"
http://rosettacode.org/wiki/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 If it is more "natural" in your language to start counting from   1   (unity) instead of   0   (zero), the combinations can be of the integers from   1   to   n. See also The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#Go
Go
package main   import ( "fmt" )   func main() { comb(5, 3, func(c []int) { fmt.Println(c) }) }   func comb(n, m int, emit func([]int)) { s := make([]int, m) last := m - 1 var rc func(int, int) rc = func(i, next int) { for j := next; j < n; j++ { s[i] = j if i == last { emit(s) } else { rc(i+1, j+1) } } return } rc(0, 0) }
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include if-then-else and switch. Less common are arithmetic if, ternary operator and Hash-based conditionals. Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
#Pascal
Pascal
IF condition1 THEN procedure1 ELSE procedure3;   IF condition1 THEN BEGIN procedure1; procedure2 END ELSE procedure3;   IF condition1 THEN BEGIN procedure1; procedure2 END ELSE BEGIN procedure3; procedure4 END;
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT - This is a comment  
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#TXR
TXR
@# old-style comment to end of line @; new-style comment to end of line @(bind a ; comment within expression "foo")
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#UNIX_Shell
UNIX Shell
#!/bin/sh # A leading hash symbol begins a comment. echo "Hello" # Comments can appear after a statement.   # The hash symbol must be at the beginning of a word. echo This_Is#Not_A_Comment #Comment
http://rosettacode.org/wiki/Church_numerals
Church numerals
Task In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all. Church one applies its first argument f just once to its second argument x, yielding f(x) Church two applies its first argument f twice to its second argument x, yielding f(f(x)) and each successive Church numeral applies its first argument one additional time to its second argument, f(f(f(x))), f(f(f(f(x)))) ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument. Arithmetic operations on natural numbers can be similarly represented as functions on Church numerals. In your language define: Church Zero, a Church successor function (a function on a Church numeral which returns the next Church numeral in the series), functions for Addition, Multiplication and Exponentiation over Church numerals, a function to convert integers to corresponding Church numerals, and a function to convert Church numerals to corresponding integers. You should: Derive Church numerals three and four in terms of Church zero and a Church successor function. use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4, similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function, convert each result back to an integer, and return it or print it to the console.
#AppleScript
AppleScript
--------------------- CHURCH NUMERALS --------------------   -- churchZero :: (a -> a) -> a -> a on churchZero(f, x) x end churchZero     -- churchSucc :: ((a -> a) -> a -> a) -> (a -> a) -> a -> a on churchSucc(n) script on |λ|(f) script property mf : mReturn(f) on |λ|(x) mf's |λ|(mReturn(n)'s |λ|(mf)'s |λ|(x)) end |λ| end script end |λ| end script end churchSucc     -- churchFromInt(n) :: Int -> (b -> b) -> b -> b on churchFromInt(n) script on |λ|(f) foldr(my compose, my |id|, replicate(n, f)) end |λ| end script end churchFromInt     -- intFromChurch :: ((Int -> Int) -> Int -> Int) -> Int on intFromChurch(cn) mReturn(cn)'s |λ|(my succ)'s |λ|(0) end intFromChurch     on churchAdd(m, n) script on |λ|(f) script property mf : mReturn(m) property nf : mReturn(n) on |λ|(x) nf's |λ|(f)'s |λ|(mf's |λ|(f)'s |λ|(x)) end |λ| end script end |λ| end script end churchAdd     on churchMult(m, n) script on |λ|(f) script property mf : mReturn(m) property nf : mReturn(n) on |λ|(x) mf's |λ|(nf's |λ|(f))'s |λ|(x) end |λ| end script end |λ| end script end churchMult     on churchExp(m, n) n's |λ|(m) end churchExp     --------------------------- TEST ------------------------- on run set cThree to churchFromInt(3) set cFour to churchFromInt(4)   map(intFromChurch, ¬ {churchAdd(cThree, cFour), churchMult(cThree, cFour), ¬ churchExp(cFour, cThree), churchExp(cThree, cFour)}) end run     ------------------------- GENERIC ------------------------   -- compose (<<<) :: (b -> c) -> (a -> b) -> a -> c on compose(f, g) script property mf : mReturn(f) property mg : mReturn(g) on |λ|(x) mf's |λ|(mg's |λ|(x)) end |λ| end script end compose     -- id :: a -> a on |id|(x) x end |id|     -- foldr :: (a -> b -> b) -> b -> [a] -> b on foldr(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from lng to 1 by -1 set v to |λ|(item i of xs, v, i, xs) end repeat return v end tell end foldr     -- map :: (a -> b) -> [a] -> [b] on map(f, xs) tell mReturn(f) set lng to length of xs set lst to {} repeat with i from 1 to lng set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map     -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: First-class m => (a -> b) -> m (a -> b) on mReturn(f) if class of f is script then f else script property |λ| : f end script end if end mReturn     -- Egyptian multiplication - progressively doubling a list, appending -- stages of doubling to an accumulator where needed for binary -- assembly of a target length -- replicate :: Int -> a -> [a] on replicate(n, a) set out to {} if n < 1 then return out set dbl to {a}   repeat while (n > 1) if (n mod 2) > 0 then set out to out & dbl set n to (n div 2) set dbl to (dbl & dbl) end repeat return out & dbl end replicate     -- succ :: Int -> Int on succ(x) 1 + x end succ
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, as a type, has the values and operations of its own. The operations of are usually called methods of the root type. Both operations and values are called polymorphic. A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument. The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual. Operations with multiple arguments and/or the results of the class are called multi-methods. A further generalization of is the operation with arguments and/or results from different classes. single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x). multiple-dispatch languages allow many arguments and/or results to control the dispatch. A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type. This type is sometimes called the most specific type of a [polymorphic] value. The type tag of the value is used in order to resolve the dispatch. The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class. In many OO languages the type of the class of T and T itself are considered equivalent. In some languages they are distinct (like in Ada). When class T and T are equivalent, there is no way to distinguish polymorphic and specific values. Task Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
#BQN
BQN
ExClass ← { 𝕊 value: # Constructor portion priv ← value priv2 ⇐ 0 ChangePriv ⇐ { priv ↩ 𝕩 } DispPriv ⇐ {𝕊: •Show priv‿priv2 }   }   obj ← ExClass 5 obj.DispPriv@ obj.ChangePriv 6 obj.DispPriv@
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, as a type, has the values and operations of its own. The operations of are usually called methods of the root type. Both operations and values are called polymorphic. A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument. The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual. Operations with multiple arguments and/or the results of the class are called multi-methods. A further generalization of is the operation with arguments and/or results from different classes. single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x). multiple-dispatch languages allow many arguments and/or results to control the dispatch. A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type. This type is sometimes called the most specific type of a [polymorphic] value. The type tag of the value is used in order to resolve the dispatch. The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class. In many OO languages the type of the class of T and T itself are considered equivalent. In some languages they are distinct (like in Ada). When class T and T are equivalent, there is no way to distinguish polymorphic and specific values. Task Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
#blz
blz
  # Constructors can take parameters (that automatically become properties) constructor Ball(color, radius)   # Objects can also have functions (closures) :volume return 4/3 * {pi} * (radius ** 3) end :show return "a " + color + " ball with radius " + radius end   end   red_ball = Ball("red", 2) print(red_ball) # => a red ball with radius 2  
http://rosettacode.org/wiki/Cistercian_numerals
Cistercian numerals
Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999. How they work All Cistercian numerals begin with a vertical line segment, which by itself represents the number 0. Then, glyphs representing the digits 1 through 9 are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number: The upper-right quadrant represents the ones place. The upper-left quadrant represents the tens place. The lower-right quadrant represents the hundreds place. The lower-left quadrant represents the thousands place. Please consult the following image for examples of Cistercian numerals showing each glyph: [1] Task Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile). Use the routine to show the following Cistercian numerals: 0 1 20 300 4000 5555 6789 And a number of your choice! Notes Due to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed — especially for text output. See also Numberphile - The Forgotten Number System dcode.fr - Online Cistercian numeral converter
#Factor
Factor
USING: combinators continuations formatting grouping io kernel literals math.order math.text.utils multiline sequences splitting ;   CONSTANT: numerals $[ HEREDOC: END + +-+ + + + + +-+ + + +-+ + + +-+ | | | |\ |/ |/ | | | | | | | | | | +-+ | + + + | + | + +-+ +-+ | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | + + + + + + + + + + END "\n" split harvest [ 5 group ] map flip ]   : precedence ( char char -- char ) 2dup [ CHAR: + = ] either? [ 2drop CHAR: + ] [ max ] if ;   : overwrite ( glyph glyph -- newglyph ) [ [ precedence ] 2map ] 2map ;   : flip-slashes ( str -- new-str ) [ { { CHAR: / [ CHAR: \ ] } { CHAR: \ [ CHAR: / ] } [ ] } case ] map ;   : hflip ( seq -- newseq ) [ reverse flip-slashes ] map ; : vflip ( seq -- newseq ) reverse [ flip-slashes ] map ;   : get-digits ( n -- seq ) 1 digit-groups 4 0 pad-tail ;   : check-cistercian ( n -- ) 0 9999 between? [ "Must be from 0 to 9999." throw ] unless ;   : .cistercian ( n -- ) [ check-cistercian ] [ "%d:\n" printf ] [ get-digits ] tri [ numerals nth ] map [ { [ ] [ hflip ] [ vflip ] [ hflip vflip ] } spread ] with-datastack [ ] [ overwrite ] map-reduce [ print ] each ;   { 0 1 20 300 4000 5555 6789 8015 } [ .cistercian nl ] each
http://rosettacode.org/wiki/Colour_bars/Display
Colour bars/Display
Task Display a series of vertical color bars across the width of the display. The color bars should either use:   the system palette,   or   the sequence of colors:   black   red   green   blue   magenta   cyan   yellow   white
#Ruby
Ruby
  # Array of web colors black, red, green, blue, magenta, cyan, yellow, white PALETTE = %w[#000000 #ff0000 #00ff00 #0000ff #ff00ff #00ffff #ffffff].freeze   def settings full_screen end   def setup PALETTE.each_with_index do |col, idx| fill color(col) rect(idx * width / 8, 0, width / 8, height) end end  
http://rosettacode.org/wiki/Colour_bars/Display
Colour bars/Display
Task Display a series of vertical color bars across the width of the display. The color bars should either use:   the system palette,   or   the sequence of colors:   black   red   green   blue   magenta   cyan   yellow   white
#Rust
Rust
use pixels::{Pixels, SurfaceTexture}; // 0.2.0 use winit::event::*; // 0.24.0 use winit::event_loop::{ControlFlow, EventLoop}; use winit::window::{Fullscreen, WindowBuilder};   fn main() { let event_loop = EventLoop::new(); let window = WindowBuilder::new() .with_title("Colour Bars") .with_decorations(false) .with_fullscreen(Some(Fullscreen::Borderless(None))) .build(&event_loop).unwrap(); let size = window.inner_size(); let texture = SurfaceTexture::new(size.width, size.height, &window); let mut image_buffer = Pixels::new(8, 1, texture).unwrap(); let frame = image_buffer.get_frame(); frame.copy_from_slice(&[ 0x00, 0x00, 0x00, 0xFF, // black 0xFF, 0x00, 0x00, 0xFF, // red 0x00, 0xFF, 0x00, 0xFF, // green 0x00, 0x00, 0xFF, 0xFF, // blue 0xFF, 0x00, 0xFF, 0xFF, // magenta 0x00, 0xFF, 0xFF, 0xFF, // cyan 0xFF, 0xFF, 0x00, 0xFF, // yellow 0xFF, 0xFF, 0xFF, 0xFF, // white ]);   image_buffer.render().unwrap();   event_loop.run(move |ev, _, flow| { match ev { Event::WindowEvent { event: WindowEvent::KeyboardInput { input, .. }, .. } => { if input.virtual_keycode == Some(VirtualKeyCode::Escape) { *flow = ControlFlow::Exit; } } Event::RedrawRequested(_) | Event::WindowEvent { event: WindowEvent::Focused(true), .. } => { image_buffer.render().unwrap(); } _ => {} } }); }
http://rosettacode.org/wiki/Closest-pair_problem
Closest-pair problem
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a function to find the closest two points among a set of given points in two dimensions,   i.e. to solve the   Closest pair of points problem   in the   planar   case. The straightforward solution is a   O(n2)   algorithm   (which we can call brute-force algorithm);   the pseudo-code (using indexes) could be simply: bruteForceClosestPair of P(1), P(2), ... P(N) if N < 2 then return ∞ else minDistance ← |P(1) - P(2)| minPoints ← { P(1), P(2) } foreach i ∈ [1, N-1] foreach j ∈ [i+1, N] if |P(i) - P(j)| < minDistance then minDistance ← |P(i) - P(j)| minPoints ← { P(i), P(j) } endif endfor endfor return minDistance, minPoints endif A better algorithm is based on the recursive divide&conquer approach,   as explained also at   Wikipedia's Closest pair of points problem,   which is   O(n log n);   a pseudo-code could be: closestPair of (xP, yP) where xP is P(1) .. P(N) sorted by x coordinate, and yP is P(1) .. P(N) sorted by y coordinate (ascending order) if N ≤ 3 then return closest points of xP using brute-force algorithm else xL ← points of xP from 1 to ⌈N/2⌉ xR ← points of xP from ⌈N/2⌉+1 to N xm ← xP(⌈N/2⌉)x yL ← { p ∈ yP : px ≤ xm } yR ← { p ∈ yP : px > xm } (dL, pairL) ← closestPair of (xL, yL) (dR, pairR) ← closestPair of (xR, yR) (dmin, pairMin) ← (dR, pairR) if dL < dR then (dmin, pairMin) ← (dL, pairL) endif yS ← { p ∈ yP : |xm - px| < dmin } nS ← number of points in yS (closest, closestPair) ← (dmin, pairMin) for i from 1 to nS - 1 k ← i + 1 while k ≤ nS and yS(k)y - yS(i)y < dmin if |yS(k) - yS(i)| < closest then (closest, closestPair) ← (|yS(k) - yS(i)|, {yS(k), yS(i)}) endif k ← k + 1 endwhile endfor return closest, closestPair endif References and further readings   Closest pair of points problem   Closest Pair (McGill)   Closest Pair (UCSB)   Closest pair (WUStL)   Closest pair (IUPUI)
#C.23
C#
class Segment { public Segment(PointF p1, PointF p2) { P1 = p1; P2 = p2; }   public readonly PointF P1; public readonly PointF P2;   public float Length() { return (float)Math.Sqrt(LengthSquared()); }   public float LengthSquared() { return (P1.X - P2.X) * (P1.X - P2.X) + (P1.Y - P2.Y) * (P1.Y - P2.Y); } }
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of running any but the last function, to demonstrate that the function indeed remembers its value. Goal Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. In imperative languages, one would generally use a loop with a mutable counter variable. For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run. See also: Multiple distinct objects
#Go
Go
package main   import "fmt"   func main() { fs := make([]func() int, 10) for i := range fs { i := i fs[i] = func() int { return i * i } } fmt.Println("func #0:", fs[0]()) fmt.Println("func #3:", fs[3]()) }
http://rosettacode.org/wiki/Circular_primes
Circular primes
Definitions A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime. For example: 1193 is a circular prime, since 1931, 9311 and 3119 are all also prime. Note that a number which is a cyclic permutation of a smaller circular prime is not considered to be itself a circular prime. So 13 is a circular prime, but 31 is not. A repunit (denoted by R) is a number whose base 10 representation contains only the digit 1. For example: R(2) = 11 and R(5) = 11111 are repunits. Task Find the first 19 circular primes. If your language has access to arbitrary precision integer arithmetic, given that they are all repunits, find the next 4 circular primes. (Stretch) Determine which of the following repunits are probably circular primes: R(5003), R(9887), R(15073), R(25031), R(35317) and R(49081). The larger ones may take a long time to process so just do as many as you reasonably can. See also Wikipedia article - Circular primes. Wikipedia article - Repunit. OEIS sequence A016114 - Circular primes.
#Java
Java
import java.math.BigInteger; import java.util.Arrays;   public class CircularPrimes { public static void main(String[] args) { System.out.println("First 19 circular primes:"); int p = 2; for (int count = 0; count < 19; ++p) { if (isCircularPrime(p)) { if (count > 0) System.out.print(", "); System.out.print(p); ++count; } } System.out.println(); System.out.println("Next 4 circular primes:"); int repunit = 1, digits = 1; for (; repunit < p; ++digits) repunit = 10 * repunit + 1; BigInteger bignum = BigInteger.valueOf(repunit); for (int count = 0; count < 4; ) { if (bignum.isProbablePrime(15)) { if (count > 0) System.out.print(", "); System.out.printf("R(%d)", digits); ++count; } ++digits; bignum = bignum.multiply(BigInteger.TEN); bignum = bignum.add(BigInteger.ONE); } System.out.println(); testRepunit(5003); testRepunit(9887); testRepunit(15073); testRepunit(25031); }   private static boolean isPrime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) return false; } return true; }   private static int cycle(int n) { int m = n, p = 1; while (m >= 10) { p *= 10; m /= 10; } return m + 10 * (n % p); }   private static boolean isCircularPrime(int p) { if (!isPrime(p)) return false; int p2 = cycle(p); while (p2 != p) { if (p2 < p || !isPrime(p2)) return false; p2 = cycle(p2); } return true; }   private static void testRepunit(int digits) { BigInteger repunit = repunit(digits); if (repunit.isProbablePrime(15)) System.out.printf("R(%d) is probably prime.\n", digits); else System.out.printf("R(%d) is not prime.\n", digits); }   private static BigInteger repunit(int digits) { char[] ch = new char[digits]; Arrays.fill(ch, '1'); return new BigInteger(new String(ch)); } }
http://rosettacode.org/wiki/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a few values to it. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#bc
bc
#define cSize( a ) ( sizeof(a)/sizeof(a[0]) ) /* a.size() */ int ar[10]; /* Collection<Integer> ar = new ArrayList<Integer>(10); */ ar[0] = 1; /* ar.set(0, 1); */ ar[1] = 2;   int* p; /* Iterator<Integer> p; Integer pValue; */ for (p=ar; /* for( p = ar.itereator(), pValue=p.next(); */ p<(ar+cSize(ar)); /* p.hasNext(); */ p++) { /* pValue=p.next() ) { */ printf("%d\n",*p); /* System.out.println(pValue); */ } /* } */
http://rosettacode.org/wiki/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 If it is more "natural" in your language to start counting from   1   (unity) instead of   0   (zero), the combinations can be of the integers from   1   to   n. See also The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#Groovy
Groovy
def comb comb = { m, list -> def n = list.size() m == 0 ? [[]] : (0..(n-m)).inject([]) { newlist, k -> def sublist = (k+1 == n) ? [] : list[(k+1)..<n] newlist += comb(m-1, sublist).collect { [list[k]] + it } } }
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include if-then-else and switch. Less common are arithmetic if, ternary operator and Hash-based conditionals. Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
#Perl
Perl
if ($expression) { do_something; }
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Unlambda
Unlambda
# this is a comment.
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Ursa
Ursa
# this is a comment # this is another comment  
http://rosettacode.org/wiki/Church_numerals
Church numerals
Task In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all. Church one applies its first argument f just once to its second argument x, yielding f(x) Church two applies its first argument f twice to its second argument x, yielding f(f(x)) and each successive Church numeral applies its first argument one additional time to its second argument, f(f(f(x))), f(f(f(f(x)))) ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument. Arithmetic operations on natural numbers can be similarly represented as functions on Church numerals. In your language define: Church Zero, a Church successor function (a function on a Church numeral which returns the next Church numeral in the series), functions for Addition, Multiplication and Exponentiation over Church numerals, a function to convert integers to corresponding Church numerals, and a function to convert Church numerals to corresponding integers. You should: Derive Church numerals three and four in terms of Church zero and a Church successor function. use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4, similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function, convert each result back to an integer, and return it or print it to the console.
#C.23
C#
using System;   public delegate Church Church(Church f);   public static class ChurchNumeral { public static readonly Church ChurchZero = _ => x => x; public static readonly Church ChurchOne = f => f;   public static Church Successor(this Church n) => f => x => f(n(f)(x)); public static Church Add(this Church m, Church n) => f => x => m(f)(n(f)(x)); public static Church Multiply(this Church m, Church n) => f => m(n(f)); public static Church Exponent(this Church m, Church n) => n(m); public static Church IsZero(this Church n) => n(_ => ChurchZero)(ChurchOne); public static Church Predecessor(this Church n) => f => x => n(g => h => h(g(f)))(_ => x)(a => a); public static Church Subtract(this Church m, Church n) => n(Predecessor)(m); static Church looper(this Church v, Church d) => v(_ => v.divr(d).Successor())(ChurchZero); static Church divr(this Church n, Church d) => n.Subtract(d).looper(d); public static Church Divide(this Church dvdnd, Church dvsr) => (dvdnd.Successor()).divr(dvsr);   public static Church FromInt(int i) => i <= 0 ? ChurchZero : Successor(FromInt(i - 1));   public static int ToInt(this Church ch) { int count = 0; ch(x => { count++; return x; })(null); return count; }   public static void Main() { Church c3 = FromInt(3); Church c4 = c3.Successor(); Church c11 = FromInt(11); Church c12 = c11.Successor(); int sum = c3.Add(c4).ToInt(); int product = c3.Multiply(c4).ToInt(); int exp43 = c4.Exponent(c3).ToInt(); int exp34 = c3.Exponent(c4).ToInt(); int tst0 = ChurchZero.IsZero().ToInt(); int pred4 = c4.Predecessor().ToInt(); int sub43 = c4.Subtract(c3).ToInt(); int div11by3 = c11.Divide(c3).ToInt(); int div12by3 = c12.Divide(c3).ToInt(); Console.Write($"{sum} {product} {exp43} {exp34} {tst0} "); Console.WriteLine($"{pred4} {sub43} {div11by3} {div12by3}"); } }
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, as a type, has the values and operations of its own. The operations of are usually called methods of the root type. Both operations and values are called polymorphic. A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument. The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual. Operations with multiple arguments and/or the results of the class are called multi-methods. A further generalization of is the operation with arguments and/or results from different classes. single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x). multiple-dispatch languages allow many arguments and/or results to control the dispatch. A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type. This type is sometimes called the most specific type of a [polymorphic] value. The type tag of the value is used in order to resolve the dispatch. The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class. In many OO languages the type of the class of T and T itself are considered equivalent. In some languages they are distinct (like in Ada). When class T and T are equivalent, there is no way to distinguish polymorphic and specific values. Task Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
#Bracmat
Bracmat
( ( resolution = (x=) (y=) (new=.!arg:(?(its.x),?(its.y))) ) & new$(resolution,640,480):?VGA & new$(resolution,1920,1080):?1080p & out$("VGA: horizontal " !(VGA..x) " vertical " !(VGA..y)));
http://rosettacode.org/wiki/Cistercian_numerals
Cistercian numerals
Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999. How they work All Cistercian numerals begin with a vertical line segment, which by itself represents the number 0. Then, glyphs representing the digits 1 through 9 are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number: The upper-right quadrant represents the ones place. The upper-left quadrant represents the tens place. The lower-right quadrant represents the hundreds place. The lower-left quadrant represents the thousands place. Please consult the following image for examples of Cistercian numerals showing each glyph: [1] Task Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile). Use the routine to show the following Cistercian numerals: 0 1 20 300 4000 5555 6789 And a number of your choice! Notes Due to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed — especially for text output. See also Numberphile - The Forgotten Number System dcode.fr - Online Cistercian numeral converter
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import "fmt"   var n = make([][]string, 15)   func initN() { for i := 0; i < 15; i++ { n[i] = make([]string, 11) for j := 0; j < 11; j++ { n[i][j] = " " } n[i][5] = "x" } }   func horiz(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r][c] = "x" } }   func verti(r1, r2, c int) { for r := r1; r <= r2; r++ { n[r][c] = "x" } }   func diagd(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r+c-c1][c] = "x" } }   func diagu(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r-c+c1][c] = "x" } }   var draw map[int]func() // map contains recursive closures   func initDraw() { draw = map[int]func(){ 1: func() { horiz(6, 10, 0) }, 2: func() { horiz(6, 10, 4) }, 3: func() { diagd(6, 10, 0) }, 4: func() { diagu(6, 10, 4) }, 5: func() { draw[1](); draw[4]() }, 6: func() { verti(0, 4, 10) }, 7: func() { draw[1](); draw[6]() }, 8: func() { draw[2](); draw[6]() }, 9: func() { draw[1](); draw[8]() },   10: func() { horiz(0, 4, 0) }, 20: func() { horiz(0, 4, 4) }, 30: func() { diagu(0, 4, 4) }, 40: func() { diagd(0, 4, 0) }, 50: func() { draw[10](); draw[40]() }, 60: func() { verti(0, 4, 0) }, 70: func() { draw[10](); draw[60]() }, 80: func() { draw[20](); draw[60]() }, 90: func() { draw[10](); draw[80]() },   100: func() { horiz(6, 10, 14) }, 200: func() { horiz(6, 10, 10) }, 300: func() { diagu(6, 10, 14) }, 400: func() { diagd(6, 10, 10) }, 500: func() { draw[100](); draw[400]() }, 600: func() { verti(10, 14, 10) }, 700: func() { draw[100](); draw[600]() }, 800: func() { draw[200](); draw[600]() }, 900: func() { draw[100](); draw[800]() },   1000: func() { horiz(0, 4, 14) }, 2000: func() { horiz(0, 4, 10) }, 3000: func() { diagd(0, 4, 10) }, 4000: func() { diagu(0, 4, 14) }, 5000: func() { draw[1000](); draw[4000]() }, 6000: func() { verti(10, 14, 0) }, 7000: func() { draw[1000](); draw[6000]() }, 8000: func() { draw[2000](); draw[6000]() }, 9000: func() { draw[1000](); draw[8000]() }, } }   func printNumeral() { for i := 0; i < 15; i++ { for j := 0; j < 11; j++ { fmt.Printf("%s ", n[i][j]) } fmt.Println() } fmt.Println() }   func main() { initDraw() numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999} for _, number := range numbers { initN() fmt.Printf("%d:\n", number) thousands := number / 1000 number %= 1000 hundreds := number / 100 number %= 100 tens := number / 10 ones := number % 10 if thousands > 0 { draw[thousands*1000]() } if hundreds > 0 { draw[hundreds*100]() } if tens > 0 { draw[tens*10]() } if ones > 0 { draw[ones]() } printNumeral() } }
http://rosettacode.org/wiki/Colour_bars/Display
Colour bars/Display
Task Display a series of vertical color bars across the width of the display. The color bars should either use:   the system palette,   or   the sequence of colors:   black   red   green   blue   magenta   cyan   yellow   white
#Scala
Scala
import java.awt.Color import scala.swing._   class ColorBars extends Component { override def paintComponent(g:Graphics2D)={ val colors=List(Color.BLACK, Color.RED, Color.GREEN, Color.BLUE, Color.MAGENTA, Color.CYAN, Color.YELLOW, Color.WHITE) val colCount=colors.size val deltaX=size.width.toDouble/colCount for(x <- 0 until colCount){ val startX=(deltaX*x).toInt val endX=(deltaX*(x+1)).toInt g.setColor(colors(x)) g.fillRect(startX, 0, endX-startX, size.height) } } }
http://rosettacode.org/wiki/Colour_bars/Display
Colour bars/Display
Task Display a series of vertical color bars across the width of the display. The color bars should either use:   the system palette,   or   the sequence of colors:   black   red   green   blue   magenta   cyan   yellow   white
#Sidef
Sidef
require('GD');   var colors = Hash.new( white => [255, 255, 255], red => [255, 0, 0], green => [0, 255, 0], blue => [0, 0, 255], magenta => [255, 0, 255], yellow => [255, 255, 0], cyan => [0, 255, 255], black => [0, 0, 0], );   var barwidth = 160/8; var image = %s'GD::Image'.new(160, 100); var start = 0;   colors.values.each { |rgb| var paintcolor = image.colorAllocate(rgb...); image.filledRectangle(start * barwidth, 0, start*barwidth + barwidth - 1, 99, paintcolor); start++; };   %f'colorbars.png'.open('>:raw').print(image.png);
http://rosettacode.org/wiki/Closest-pair_problem
Closest-pair problem
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a function to find the closest two points among a set of given points in two dimensions,   i.e. to solve the   Closest pair of points problem   in the   planar   case. The straightforward solution is a   O(n2)   algorithm   (which we can call brute-force algorithm);   the pseudo-code (using indexes) could be simply: bruteForceClosestPair of P(1), P(2), ... P(N) if N < 2 then return ∞ else minDistance ← |P(1) - P(2)| minPoints ← { P(1), P(2) } foreach i ∈ [1, N-1] foreach j ∈ [i+1, N] if |P(i) - P(j)| < minDistance then minDistance ← |P(i) - P(j)| minPoints ← { P(i), P(j) } endif endfor endfor return minDistance, minPoints endif A better algorithm is based on the recursive divide&conquer approach,   as explained also at   Wikipedia's Closest pair of points problem,   which is   O(n log n);   a pseudo-code could be: closestPair of (xP, yP) where xP is P(1) .. P(N) sorted by x coordinate, and yP is P(1) .. P(N) sorted by y coordinate (ascending order) if N ≤ 3 then return closest points of xP using brute-force algorithm else xL ← points of xP from 1 to ⌈N/2⌉ xR ← points of xP from ⌈N/2⌉+1 to N xm ← xP(⌈N/2⌉)x yL ← { p ∈ yP : px ≤ xm } yR ← { p ∈ yP : px > xm } (dL, pairL) ← closestPair of (xL, yL) (dR, pairR) ← closestPair of (xR, yR) (dmin, pairMin) ← (dR, pairR) if dL < dR then (dmin, pairMin) ← (dL, pairL) endif yS ← { p ∈ yP : |xm - px| < dmin } nS ← number of points in yS (closest, closestPair) ← (dmin, pairMin) for i from 1 to nS - 1 k ← i + 1 while k ≤ nS and yS(k)y - yS(i)y < dmin if |yS(k) - yS(i)| < closest then (closest, closestPair) ← (|yS(k) - yS(i)|, {yS(k), yS(i)}) endif k ← k + 1 endwhile endfor return closest, closestPair endif References and further readings   Closest pair of points problem   Closest Pair (McGill)   Closest Pair (UCSB)   Closest pair (WUStL)   Closest pair (IUPUI)
#C.2B.2B
C++
/* Author: Kevin Bacon Date: 04/03/2014 Task: Closest-pair problem */   #include <iostream> #include <vector> #include <utility> #include <cmath> #include <random> #include <chrono> #include <algorithm> #include <iterator>   typedef std::pair<double, double> point_t; typedef std::pair<point_t, point_t> points_t;   double distance_between(const point_t& a, const point_t& b) { return std::sqrt(std::pow(b.first - a.first, 2) + std::pow(b.second - a.second, 2)); }   std::pair<double, points_t> find_closest_brute(const std::vector<point_t>& points) { if (points.size() < 2) { return { -1, { { 0, 0 }, { 0, 0 } } }; } auto minDistance = std::abs(distance_between(points.at(0), points.at(1))); points_t minPoints = { points.at(0), points.at(1) }; for (auto i = std::begin(points); i != (std::end(points) - 1); ++i) { for (auto j = i + 1; j < std::end(points); ++j) { auto newDistance = std::abs(distance_between(*i, *j)); if (newDistance < minDistance) { minDistance = newDistance; minPoints.first = *i; minPoints.second = *j; } } } return { minDistance, minPoints }; }   std::pair<double, points_t> find_closest_optimized(const std::vector<point_t>& xP, const std::vector<point_t>& yP) { if (xP.size() <= 3) { return find_closest_brute(xP); } auto N = xP.size(); auto xL = std::vector<point_t>(); auto xR = std::vector<point_t>(); std::copy(std::begin(xP), std::begin(xP) + (N / 2), std::back_inserter(xL)); std::copy(std::begin(xP) + (N / 2), std::end(xP), std::back_inserter(xR)); auto xM = xP.at((N-1) / 2).first; auto yL = std::vector<point_t>(); auto yR = std::vector<point_t>(); std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yL), [&xM](const point_t& p) { return p.first <= xM; }); std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yR), [&xM](const point_t& p) { return p.first > xM; }); auto p1 = find_closest_optimized(xL, yL); auto p2 = find_closest_optimized(xR, yR); auto minPair = (p1.first <= p2.first) ? p1 : p2; auto yS = std::vector<point_t>(); std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yS), [&minPair, &xM](const point_t& p) { return std::abs(xM - p.first) < minPair.first; }); auto result = minPair; for (auto i = std::begin(yS); i != (std::end(yS) - 1); ++i) { for (auto k = i + 1; k != std::end(yS) && ((k->second - i->second) < minPair.first); ++k) { auto newDistance = std::abs(distance_between(*k, *i)); if (newDistance < result.first) { result = { newDistance, { *k, *i } }; } } } return result; }   void print_point(const point_t& point) { std::cout << "(" << point.first << ", " << point.second << ")"; }   int main(int argc, char * argv[]) { std::default_random_engine re(std::chrono::system_clock::to_time_t( std::chrono::system_clock::now())); std::uniform_real_distribution<double> urd(-500.0, 500.0); std::vector<point_t> points(100); std::generate(std::begin(points), std::end(points), [&urd, &re]() { return point_t { 1000 + urd(re), 1000 + urd(re) }; }); auto answer = find_closest_brute(points); std::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) { return a.first < b.first; }); auto xP = points; std::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) { return a.second < b.second; }); auto yP = points; std::cout << "Min distance (brute): " << answer.first << " "; print_point(answer.second.first); std::cout << ", "; print_point(answer.second.second); answer = find_closest_optimized(xP, yP); std::cout << "\nMin distance (optimized): " << answer.first << " "; print_point(answer.second.first); std::cout << ", "; print_point(answer.second.second); return 0; }
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of running any but the last function, to demonstrate that the function indeed remembers its value. Goal Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. In imperative languages, one would generally use a loop with a mutable counter variable. For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run. See also: Multiple distinct objects
#Groovy
Groovy
def closures = (0..9).collect{ i -> { -> i*i } }
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of running any but the last function, to demonstrate that the function indeed remembers its value. Goal Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. In imperative languages, one would generally use a loop with a mutable counter variable. For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run. See also: Multiple distinct objects
#Haskell
Haskell
fs = map (\i _ -> i * i) [1 .. 10]
http://rosettacode.org/wiki/Circular_primes
Circular primes
Definitions A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime. For example: 1193 is a circular prime, since 1931, 9311 and 3119 are all also prime. Note that a number which is a cyclic permutation of a smaller circular prime is not considered to be itself a circular prime. So 13 is a circular prime, but 31 is not. A repunit (denoted by R) is a number whose base 10 representation contains only the digit 1. For example: R(2) = 11 and R(5) = 11111 are repunits. Task Find the first 19 circular primes. If your language has access to arbitrary precision integer arithmetic, given that they are all repunits, find the next 4 circular primes. (Stretch) Determine which of the following repunits are probably circular primes: R(5003), R(9887), R(15073), R(25031), R(35317) and R(49081). The larger ones may take a long time to process so just do as many as you reasonably can. See also Wikipedia article - Circular primes. Wikipedia article - Repunit. OEIS sequence A016114 - Circular primes.
#jq
jq
  def is_circular_prime: def circle: range(0;length) as $i | .[$i:] + .[:$i]; tostring as $s | [$s|circle|tonumber] as $c | . == ($c|min) and all($c|unique[]; is_prime);   def circular_primes: 2, (range(3; infinite; 2) | select(is_circular_prime));   # Probably only useful with unbounded-precision integer arithmetic: def repunits: 1 | recurse(10*. + 1);  
http://rosettacode.org/wiki/Circular_primes
Circular primes
Definitions A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime. For example: 1193 is a circular prime, since 1931, 9311 and 3119 are all also prime. Note that a number which is a cyclic permutation of a smaller circular prime is not considered to be itself a circular prime. So 13 is a circular prime, but 31 is not. A repunit (denoted by R) is a number whose base 10 representation contains only the digit 1. For example: R(2) = 11 and R(5) = 11111 are repunits. Task Find the first 19 circular primes. If your language has access to arbitrary precision integer arithmetic, given that they are all repunits, find the next 4 circular primes. (Stretch) Determine which of the following repunits are probably circular primes: R(5003), R(9887), R(15073), R(25031), R(35317) and R(49081). The larger ones may take a long time to process so just do as many as you reasonably can. See also Wikipedia article - Circular primes. Wikipedia article - Repunit. OEIS sequence A016114 - Circular primes.
#Julia
Julia
using Lazy, Primes   function iscircularprime(n)  !isprime(n) && return false dig = digits(n) return all(i -> (m = evalpoly(10, circshift(dig, i))) >= n && isprime(m), 1:length(dig)-1) end   filtcircular(n, rang) = Int.(collect(take(n, filter(iscircularprime, rang)))) isprimerepunit(n) = isprime(evalpoly(BigInt(10), ones(Int, n))) filtrep(n, rang) = collect(take(n, filter(isprimerepunit, rang)))   println("The first 19 circular primes are:\n", filtcircular(19, Lazy.range(2))) print("\nThe next 4 circular primes, in repunit format, are: ", mapreduce(n -> "R($n) ", *, filtrep(4, Lazy.range(6))))   println("\n\nChecking larger repunits:") for i in [5003, 9887, 15073, 25031, 35317, 49081] println("R($i) is ", isprimerepunit(i) ? "prime." : "not prime.") end  
http://rosettacode.org/wiki/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a few values to it. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#C
C
#define cSize( a ) ( sizeof(a)/sizeof(a[0]) ) /* a.size() */ int ar[10]; /* Collection<Integer> ar = new ArrayList<Integer>(10); */ ar[0] = 1; /* ar.set(0, 1); */ ar[1] = 2;   int* p; /* Iterator<Integer> p; Integer pValue; */ for (p=ar; /* for( p = ar.itereator(), pValue=p.next(); */ p<(ar+cSize(ar)); /* p.hasNext(); */ p++) { /* pValue=p.next() ) { */ printf("%d\n",*p); /* System.out.println(pValue); */ } /* } */
http://rosettacode.org/wiki/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 If it is more "natural" in your language to start counting from   1   (unity) instead of   0   (zero), the combinations can be of the integers from   1   to   n. See also The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#Haskell
Haskell
comb :: Int -> [a] -> [[a]] comb 0 _ = [[]] comb _ [] = [] comb m (x:xs) = map (x:) (comb (m-1) xs) ++ comb m xs
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include if-then-else and switch. Less common are arithmetic if, ternary operator and Hash-based conditionals. Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
#Phix
Phix
with javascript_semantics if name="Pete" then -- do something elsif age>50 then -- do something elsif age<20 then -- do something else -- do something end if
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Ursala
Ursala
# this is single line a comment   # this is a\ continued comment   (# this is a multi-line comment #)   (# comments in (# this form #) can (# be (# arbitrarily #) #) nested #)   ---- this is also a comment\ and can be continued   ### The whole rest of the file after three hashes is a comment.
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#VBA
VBA
' This is a VBA comment
http://rosettacode.org/wiki/Church_numerals
Church numerals
Task In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all. Church one applies its first argument f just once to its second argument x, yielding f(x) Church two applies its first argument f twice to its second argument x, yielding f(f(x)) and each successive Church numeral applies its first argument one additional time to its second argument, f(f(f(x))), f(f(f(f(x)))) ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument. Arithmetic operations on natural numbers can be similarly represented as functions on Church numerals. In your language define: Church Zero, a Church successor function (a function on a Church numeral which returns the next Church numeral in the series), functions for Addition, Multiplication and Exponentiation over Church numerals, a function to convert integers to corresponding Church numerals, and a function to convert Church numerals to corresponding integers. You should: Derive Church numerals three and four in terms of Church zero and a Church successor function. use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4, similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function, convert each result back to an integer, and return it or print it to the console.
#Chapel
Chapel
class Church { // identity Church function by default proc this(f: shared Church): shared Church { return f; } }   // utility Church functions... class ComposeChurch : Church { const l, r: shared Church; override proc this(f: shared Church): shared Church { return l(r(f)); } }   proc composeChurch(chl: shared Church, chr: shared Church) : shared Church { return new shared ComposeChurch(chl, chr): shared Church; }   class ConstChurch : Church { const ch: shared Church; override proc this(f: shared Church): shared Church { return ch; } }   proc constChurch(ch: shared Church): shared Church { return new shared ConstChurch(ch): shared Church; }   // Church constants... const cIdentityChurch: shared Church = new shared Church(); const cChurchZero = constChurch(cIdentityChurch); const cChurchOne = cIdentityChurch; // default is identity!   // Church functions... class SuccChurch: Church { const curr: shared Church; override proc this(f: shared Church): shared Church { return composeChurch(f, curr(f)); } }   proc succChurch(ch: shared Church): shared Church { return new shared SuccChurch(ch) : shared Church; }   class AddChurch: Church { const chf, chs: shared Church; override proc this(f: shared Church): shared Church { return composeChurch(chf(f), chs(f)); } }   proc addChurch(cha: shared Church, chb: shared Church): shared Church { return new shared AddChurch(cha, chb) : shared Church; }   class MultChurch: Church { const chf, chs: shared Church; override proc this(f: shared Church): shared Church { return composeChurch(chf, chs)(f); } }   proc multChurch(cha: shared Church, chb: shared Church): shared Church { return new shared MultChurch(cha, chb) : shared Church; }   class ExpChurch : Church { const b, e : shared Church; override proc this(f : shared Church): shared Church { return e(b)(f); } }   proc expChurch(chbs: shared Church, chexp: shared Church): shared Church { return new shared ExpChurch(chbs, chexp) : shared Church; }   class IsZeroChurch : Church { const c : shared Church; override proc this(f : shared Church): shared Church { return c(constChurch(cChurchZero))(cChurchOne)(f); } }   proc isZeroChurch(ch: shared Church): shared Church { return new shared IsZeroChurch(ch) : shared Church; }   class PredChurch : Church { const c : shared Church; class XFunc : Church { const cf, fnc: shared Church; class GFunc : Church { const fnc: shared Church; class HFunc : Church { const fnc, g: shared Church; override proc this(f : shared Church): shared Church { return f(g(fnc)); } } override proc this(f : shared Church): shared Church { return new shared HFunc(fnc, f): shared Church; } } override proc this(f : shared Church): shared Church { const prd = new shared GFunc(fnc): shared Church; return cf(prd)(constChurch(f))(cIdentityChurch); } } override proc this(f : shared Church): shared Church { return new shared XFunc(c, f) : shared Church; } }   proc predChurch(ch: shared Church): shared Church { return new shared PredChurch(ch) : shared Church; }   class SubChurch : Church { const a, b : shared Church; class PredFunc : Church { override proc this(f : shared Church): shared Church { return new shared PredChurch(f): shared Church; } } override proc this(f : shared Church): shared Church { const prdf = new shared PredFunc(): shared Church; return b(prdf)(a)(f); } }   proc subChurch(cha: shared Church, chb: shared Church): shared Church { return new shared SubChurch(cha, chb) : shared Church; }   class DivrChurch : Church { const v, d : shared Church; override proc this(f : shared Church): shared Church { const loopr = constChurch(succChurch(divr(v, d))); return v(loopr)(cChurchZero)(f); } }   proc divr(n: shared Church, d : shared Church): shared Church { return new shared DivrChurch(subChurch(n, d), d): shared Church; }   proc divChurch(chdvdnd: shared Church, chdvsr: shared Church): shared Church { return divr(succChurch(chdvdnd), chdvsr); }   // conversion functions... proc loopChurch(i: int, ch: shared Church) : shared Church { // tail call... return if (i <= 0) then ch else loopChurch(i - 1, succChurch(ch)); }   proc churchFromInt(n: int): shared Church { return loopChurch(n, cChurchZero); // can't embed "worker" proc! }   class IntChurch : Church { const value: int; }   class IncChurch : Church { override proc this(f: shared Church): shared Church { const tst = f: IntChurch; if tst != nil { return new shared IntChurch(tst.value + 1): shared Church; } else return f; } // shouldn't happen! }   proc intFromChurch(ch: shared Church): int { const zero = new shared IntChurch(0): shared Church; const tst = ch(new shared IncChurch(): shared Church)(zero): IntChurch; if tst != nil { return tst.value; } else return -1; // should never happen! }   // testing... const ch3 = churchFromInt(3); const ch4 = succChurch(ch3); const ch11 = churchFromInt(11); const ch12 = succChurch(ch11); write(intFromChurch(addChurch(ch3, ch4)), ", "); write(intFromChurch(multChurch(ch3, ch4)), ", "); write(intFromChurch(expChurch(ch3, ch4)), ", "); write(intFromChurch(expChurch(ch4, ch3)), ", "); write(intFromChurch(isZeroChurch(cChurchZero)), ", "); write(intFromChurch(isZeroChurch(ch3)), ", "); write(intFromChurch(predChurch(ch4)), ", "); write(intFromChurch(predChurch(cChurchZero)), ", "); write(intFromChurch(subChurch(ch11, ch3)), ", "); write(intFromChurch(divChurch(ch11, ch3)), ", "); writeln(intFromChurch(divChurch(ch12, ch3)));
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, as a type, has the values and operations of its own. The operations of are usually called methods of the root type. Both operations and values are called polymorphic. A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument. The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual. Operations with multiple arguments and/or the results of the class are called multi-methods. A further generalization of is the operation with arguments and/or results from different classes. single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x). multiple-dispatch languages allow many arguments and/or results to control the dispatch. A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type. This type is sometimes called the most specific type of a [polymorphic] value. The type tag of the value is used in order to resolve the dispatch. The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class. In many OO languages the type of the class of T and T itself are considered equivalent. In some languages they are distinct (like in Ada). When class T and T are equivalent, there is no way to distinguish polymorphic and specific values. Task Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
#C
C
  #include <stdlib.h>   typedef struct sMyClass { int variable; } *MyClass;   MyClass MyClass_new() { MyClass pthis = malloc(sizeof *pthis); pthis->variable = 0; return pthis; }   void MyClass_delete(MyClass* pthis) { if (pthis) { free(*pthis); *pthis = NULL; } }   void MyClass_someMethod(MyClass pthis) { pthis->variable = 1; }   MyClass obj = MyClass_new(); MyClass_someMethod(obj); MyClass_delete(&obj);
http://rosettacode.org/wiki/Cistercian_numerals
Cistercian numerals
Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999. How they work All Cistercian numerals begin with a vertical line segment, which by itself represents the number 0. Then, glyphs representing the digits 1 through 9 are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number: The upper-right quadrant represents the ones place. The upper-left quadrant represents the tens place. The lower-right quadrant represents the hundreds place. The lower-left quadrant represents the thousands place. Please consult the following image for examples of Cistercian numerals showing each glyph: [1] Task Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile). Use the routine to show the following Cistercian numerals: 0 1 20 300 4000 5555 6789 And a number of your choice! Notes Due to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed — especially for text output. See also Numberphile - The Forgotten Number System dcode.fr - Online Cistercian numeral converter
#Go
Go
package main   import "fmt"   var n = make([][]string, 15)   func initN() { for i := 0; i < 15; i++ { n[i] = make([]string, 11) for j := 0; j < 11; j++ { n[i][j] = " " } n[i][5] = "x" } }   func horiz(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r][c] = "x" } }   func verti(r1, r2, c int) { for r := r1; r <= r2; r++ { n[r][c] = "x" } }   func diagd(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r+c-c1][c] = "x" } }   func diagu(c1, c2, r int) { for c := c1; c <= c2; c++ { n[r-c+c1][c] = "x" } }   var draw map[int]func() // map contains recursive closures   func initDraw() { draw = map[int]func(){ 1: func() { horiz(6, 10, 0) }, 2: func() { horiz(6, 10, 4) }, 3: func() { diagd(6, 10, 0) }, 4: func() { diagu(6, 10, 4) }, 5: func() { draw[1](); draw[4]() }, 6: func() { verti(0, 4, 10) }, 7: func() { draw[1](); draw[6]() }, 8: func() { draw[2](); draw[6]() }, 9: func() { draw[1](); draw[8]() },   10: func() { horiz(0, 4, 0) }, 20: func() { horiz(0, 4, 4) }, 30: func() { diagu(0, 4, 4) }, 40: func() { diagd(0, 4, 0) }, 50: func() { draw[10](); draw[40]() }, 60: func() { verti(0, 4, 0) }, 70: func() { draw[10](); draw[60]() }, 80: func() { draw[20](); draw[60]() }, 90: func() { draw[10](); draw[80]() },   100: func() { horiz(6, 10, 14) }, 200: func() { horiz(6, 10, 10) }, 300: func() { diagu(6, 10, 14) }, 400: func() { diagd(6, 10, 10) }, 500: func() { draw[100](); draw[400]() }, 600: func() { verti(10, 14, 10) }, 700: func() { draw[100](); draw[600]() }, 800: func() { draw[200](); draw[600]() }, 900: func() { draw[100](); draw[800]() },   1000: func() { horiz(0, 4, 14) }, 2000: func() { horiz(0, 4, 10) }, 3000: func() { diagd(0, 4, 10) }, 4000: func() { diagu(0, 4, 14) }, 5000: func() { draw[1000](); draw[4000]() }, 6000: func() { verti(10, 14, 0) }, 7000: func() { draw[1000](); draw[6000]() }, 8000: func() { draw[2000](); draw[6000]() }, 9000: func() { draw[1000](); draw[8000]() }, } }   func printNumeral() { for i := 0; i < 15; i++ { for j := 0; j < 11; j++ { fmt.Printf("%s ", n[i][j]) } fmt.Println() } fmt.Println() }   func main() { initDraw() numbers := []int{0, 1, 20, 300, 4000, 5555, 6789, 9999} for _, number := range numbers { initN() fmt.Printf("%d:\n", number) thousands := number / 1000 number %= 1000 hundreds := number / 100 number %= 100 tens := number / 10 ones := number % 10 if thousands > 0 { draw[thousands*1000]() } if hundreds > 0 { draw[hundreds*100]() } if tens > 0 { draw[tens*10]() } if ones > 0 { draw[ones]() } printNumeral() } }
http://rosettacode.org/wiki/Colour_bars/Display
Colour bars/Display
Task Display a series of vertical color bars across the width of the display. The color bars should either use:   the system palette,   or   the sequence of colors:   black   red   green   blue   magenta   cyan   yellow   white
#SmileBASIC
SmileBASIC
FOR I=0 TO 7 READ R,G,B GFILL I*50,0,I*50+49,239,RGB(R,G,B) NEXT REPEAT UNTIL BUTTON(0) AND #B   DATA 0,0,0 DATA 255,0,0 DATA 0,255,0 DATA 0,0,255 DATA 255,0,255 DATA 0,255,255 DATA 255,255,0 DATA 255,255,255
http://rosettacode.org/wiki/Colour_bars/Display
Colour bars/Display
Task Display a series of vertical color bars across the width of the display. The color bars should either use:   the system palette,   or   the sequence of colors:   black   red   green   blue   magenta   cyan   yellow   white
#Tcl
Tcl
package require Tcl 8.5 package require Tk 8.5   wm attributes . -fullscreen 1 pack [canvas .c -highlightthick 0] -fill both -expand 1 set colors {black red green blue magenta cyan yellow white}   for {set x 0} {$x < [winfo screenwidth .c]} {incr x 8} { .c create rectangle $x 0 [expr {$x+7}] [winfo screenheight .c] \ -fill [lindex $colors 0] -outline {} set colors [list {*}[lrange $colors 1 end] [lindex $colors 0]] }
http://rosettacode.org/wiki/Closest-pair_problem
Closest-pair problem
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a function to find the closest two points among a set of given points in two dimensions,   i.e. to solve the   Closest pair of points problem   in the   planar   case. The straightforward solution is a   O(n2)   algorithm   (which we can call brute-force algorithm);   the pseudo-code (using indexes) could be simply: bruteForceClosestPair of P(1), P(2), ... P(N) if N < 2 then return ∞ else minDistance ← |P(1) - P(2)| minPoints ← { P(1), P(2) } foreach i ∈ [1, N-1] foreach j ∈ [i+1, N] if |P(i) - P(j)| < minDistance then minDistance ← |P(i) - P(j)| minPoints ← { P(i), P(j) } endif endfor endfor return minDistance, minPoints endif A better algorithm is based on the recursive divide&conquer approach,   as explained also at   Wikipedia's Closest pair of points problem,   which is   O(n log n);   a pseudo-code could be: closestPair of (xP, yP) where xP is P(1) .. P(N) sorted by x coordinate, and yP is P(1) .. P(N) sorted by y coordinate (ascending order) if N ≤ 3 then return closest points of xP using brute-force algorithm else xL ← points of xP from 1 to ⌈N/2⌉ xR ← points of xP from ⌈N/2⌉+1 to N xm ← xP(⌈N/2⌉)x yL ← { p ∈ yP : px ≤ xm } yR ← { p ∈ yP : px > xm } (dL, pairL) ← closestPair of (xL, yL) (dR, pairR) ← closestPair of (xR, yR) (dmin, pairMin) ← (dR, pairR) if dL < dR then (dmin, pairMin) ← (dL, pairL) endif yS ← { p ∈ yP : |xm - px| < dmin } nS ← number of points in yS (closest, closestPair) ← (dmin, pairMin) for i from 1 to nS - 1 k ← i + 1 while k ≤ nS and yS(k)y - yS(i)y < dmin if |yS(k) - yS(i)| < closest then (closest, closestPair) ← (|yS(k) - yS(i)|, {yS(k), yS(i)}) endif k ← k + 1 endwhile endfor return closest, closestPair endif References and further readings   Closest pair of points problem   Closest Pair (McGill)   Closest Pair (UCSB)   Closest pair (WUStL)   Closest pair (IUPUI)
#Clojure
Clojure
  (defn distance [[x1 y1] [x2 y2]] (let [dx (- x2 x1), dy (- y2 y1)] (Math/sqrt (+ (* dx dx) (* dy dy)))))   (defn brute-force [points] (let [n (count points)] (when (< 1 n) (apply min-key first (for [i (range 0 (dec n)), :let [p1 (nth points i)], j (range (inc i) n), :let [p2 (nth points j)]] [(distance p1 p2) p1 p2])))))   (defn combine [yS [dmin pmin1 pmin2]] (apply min-key first (conj (for [[p1 p2] (partition 2 1 yS)  :let [[_ py1] p1 [_ py2] p2]  :while (< (- py1 py2) dmin)] [(distance p1 p2) p1 p2]) [dmin pmin1 pmin2])))   (defn closest-pair ([points] (closest-pair (sort-by first points) (sort-by second points))) ([xP yP] (if (< (count xP) 4) (brute-force xP) (let [[xL xR] (partition-all (Math/ceil (/ (count xP) 2)) xP) [xm _] (last xL) {yL true yR false} (group-by (fn [[px _]] (<= px xm)) yP) dL&pairL (closest-pair xL yL) dR&pairR (closest-pair xR yR) [dmin pmin1 pmin2] (min-key first dL&pairL dR&pairR) {yS true} (group-by (fn [[px _]] (< (Math/abs (- xm px)) dmin)) yP)] (combine yS [dmin pmin1 pmin2])))))  
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of running any but the last function, to demonstrate that the function indeed remembers its value. Goal Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. In imperative languages, one would generally use a loop with a mutable counter variable. For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run. See also: Multiple distinct objects
#Icon_and_Unicon
Icon and Unicon
procedure main(args) # Closure/Variable Capture every put(L := [], vcapture(1 to 10)) # build list of index closures write("Randomly selecting L[",i := ?*L,"] = ",L[i]()) # L[i]() calls the closure end   # The anonymous 'function', as a co-expression. Most of the code is standard # boilerplate needed to use a co-expression as an anonymous function.   procedure vcapture(x) # vcapture closes over its argument return makeProc { repeat { (x[1]^2) @ &source } } end   procedure makeProc(A) # the makeProc PDCO from the UniLib Utils package return (@A[1], A[1]) end
http://rosettacode.org/wiki/Circular_primes
Circular primes
Definitions A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime. For example: 1193 is a circular prime, since 1931, 9311 and 3119 are all also prime. Note that a number which is a cyclic permutation of a smaller circular prime is not considered to be itself a circular prime. So 13 is a circular prime, but 31 is not. A repunit (denoted by R) is a number whose base 10 representation contains only the digit 1. For example: R(2) = 11 and R(5) = 11111 are repunits. Task Find the first 19 circular primes. If your language has access to arbitrary precision integer arithmetic, given that they are all repunits, find the next 4 circular primes. (Stretch) Determine which of the following repunits are probably circular primes: R(5003), R(9887), R(15073), R(25031), R(35317) and R(49081). The larger ones may take a long time to process so just do as many as you reasonably can. See also Wikipedia article - Circular primes. Wikipedia article - Repunit. OEIS sequence A016114 - Circular primes.
#Kotlin
Kotlin
import java.math.BigInteger   val SMALL_PRIMES = listOf( 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997 )   fun isPrime(n: BigInteger): Boolean { if (n < 2.toBigInteger()) { return false }   for (sp in SMALL_PRIMES) { val spb = sp.toBigInteger() if (n == spb) { return true } if (n % spb == BigInteger.ZERO) { return false } if (n < spb * spb) { //if (n > SMALL_PRIMES.last().toBigInteger()) { // println("Next: $n") //} return true } }   return n.isProbablePrime(10) }   fun cycle(n: BigInteger): BigInteger { var m = n var p = 1 while (m >= BigInteger.TEN) { p *= 10 m /= BigInteger.TEN } return m + BigInteger.TEN * (n % p.toBigInteger()) }   fun isCircularPrime(p: BigInteger): Boolean { if (!isPrime(p)) { return false } var p2 = cycle(p) while (p2 != p) { if (p2 < p || !isPrime(p2)) { return false } p2 = cycle(p2) } return true }   fun testRepUnit(digits: Int) { var repUnit = BigInteger.ONE var count = digits - 1 while (count > 0) { repUnit = BigInteger.TEN * repUnit + BigInteger.ONE count-- } if (isPrime(repUnit)) { println("R($digits) is probably prime.") } else { println("R($digits) is not prime.") } }   fun main() { println("First 19 circular primes:") var p = 2 var count = 0 while (count < 19) { if (isCircularPrime(p.toBigInteger())) { if (count > 0) { print(", ") } print(p) count++ } p++ } println()   println("Next 4 circular primes:") var repUnit = BigInteger.ONE var digits = 1 count = 0 while (repUnit < p.toBigInteger()) { repUnit = BigInteger.TEN * repUnit + BigInteger.ONE digits++ } while (count < 4) { if (isPrime(repUnit)) { print("R($digits) ") count++ } repUnit = BigInteger.TEN * repUnit + BigInteger.ONE digits++ } println()   testRepUnit(5003) testRepUnit(9887) testRepUnit(15073) testRepUnit(25031) testRepUnit(35317) testRepUnit(49081) }
http://rosettacode.org/wiki/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a few values to it. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#C.23
C#
  // Creates and initializes a new integer Array int[] intArray = new int[5] { 1, 2, 3, 4, 5 }; //same as int[] intArray = new int[]{ 1, 2, 3, 4, 5 }; //same as int[] intArray = { 1, 2, 3, 4, 5 };   //Arrays are zero-based string[] stringArr = new string[5]; stringArr[0] = "string";  
http://rosettacode.org/wiki/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 If it is more "natural" in your language to start counting from   1   (unity) instead of   0   (zero), the combinations can be of the integers from   1   to   n. See also The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#Icon_and_Unicon
Icon and Unicon
procedure main() return combinations(3,5,0) end   procedure combinations(m,n,z) # demonstrate combinations /z := 1   write(m," combinations of ",n," integers starting from ",z) every put(L := [], z to n - 1 + z by 1) # generate list of n items from z write("Intial list\n",list2string(L)) write("Combinations:") every write(list2string(lcomb(L,m))) end   procedure list2string(L) # helper function every (s := "[") ||:= " " || (!L|"]") return s end   link lists
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include if-then-else and switch. Less common are arithmetic if, ternary operator and Hash-based conditionals. Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
#PHL
PHL
var a = 5; if (a == 5) { doSomething(); } else if (a > 0) { doSomethingElse(); } else { error(); }
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#VBScript
VBScript
' This is a VBScript comment
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Verbexx
Verbexx
  ////////////////////////////////////////////////////////////////////////////////////////////// // // Line Comments: // ============= // @VAR v1 = 10; // Line comments start from the "//" and continue to end of the line. // (normal code can appear on the same line, before the //) // // Line comments can span a complete line, or start in the middle of a line. /// //// Additional // chars and /* /* /[ ]/ and /] are ignored //// Line comments can be appear to be nested, since any additional // is ignored. /// // Note: // can appear in strings without triggering a line comment // // cannot appear inside an operator (or verbname), since a line comment // would start // /////////////////////////////////////////////////////////////////////////////////////////////   /******************************************************************************************** * * Block Comments: * ============== * ********************************************************************************************/ //* //* These start with /* and end with the next */ . They cannot be nested, since the first */ //* will end the block comment. For example, the comment, /* /* */ */ would end after the //* first */. Note that /* is ignored inside a block comment, as are // /[ /] and /]. //* //* Also note that something like the following will cause trouble in a block comment: //* //* /* comments // //* * more comments // */ (the // does not prevent the */ from ending //* * (no longer part of the comment) // block comment) //* */ //* //* Note: /* can appear in strings without triggering the start of a block comment //* /* cannot appear inside an operator (or verbname), since a line comment will //* start, although */ is allowed inside an operator (verbname). Commenting //* out such a verbname may cause problems. //* //* Note: Since string literals are not recognized in block comments, */ appearing //* in a string literal inside a block comment (perhaps commented-out code) //* will cause the block comment to end. //* //* Note: It is an error to start a block comment and not end it, so that it is still //* in progresss when the end-of-file is reached. //* //* Block comments can appear inside lines of code: //* /*1*/@VAR/*2*/v2/*3*/=/*4*/20/*5*/;/*6*/ // a line comment can follow block comments on the // same line   /[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][] /[] [] /[] Nestable Block Comments: [] [] ======================== []/ [] []/ [][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][]/   //[] //[] These start with /[ and end with the next matching ]/ . Additional occurrences //[] of /[ ... ]/ can appear inside a nestable block comment. The nestable block comment //[] will end only when the nest level reaches 0. Note that /* is ignored inside a nestable //[] block comment, as are */ // and /]. //[] //[] Nestable block comments can be used to comment out blocks of code containing line //[] comments or regular comments, and even balanced and well-formed nestable block comments. //[] //[] Note: /[ can appear in strings without triggering the start of a block comment. //[] However, strings literals are not recognized inside a nestable block comment, so //[] any appearances of /[ and /] inside a string literal in a nestable block commment //[] will affect the nest level, and may cause problems. //[] //[] Note: It is an error to start a nestable block comment and not end it, so that it is //[] still in progresss when the end of file is reached. //[] //[] Nestable block comments can appear inside lines of code: //[] /[1]/@VAR/[2]/v3/[3]/=/[4]/30/[5]/;/[6]/ // a line comment can follow nestable block comments // on the same line   @SAY v1 v2 v3; // should see: 10 20 30   /] /=================================================================================================\ | | | /] starts a block comment that lasts until the end of the current file. Everything after | | the /] is ignored. | | | \=================================================================================================/  
http://rosettacode.org/wiki/Church_numerals
Church numerals
Task In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all. Church one applies its first argument f just once to its second argument x, yielding f(x) Church two applies its first argument f twice to its second argument x, yielding f(f(x)) and each successive Church numeral applies its first argument one additional time to its second argument, f(f(f(x))), f(f(f(f(x)))) ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument. Arithmetic operations on natural numbers can be similarly represented as functions on Church numerals. In your language define: Church Zero, a Church successor function (a function on a Church numeral which returns the next Church numeral in the series), functions for Addition, Multiplication and Exponentiation over Church numerals, a function to convert integers to corresponding Church numerals, and a function to convert Church numerals to corresponding integers. You should: Derive Church numerals three and four in terms of Church zero and a Church successor function. use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4, similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function, convert each result back to an integer, and return it or print it to the console.
#Clojure
Clojure
(defn zero [f] identity) (defn succ [n] (fn [f] (fn [x] (f ((n f) x))))) (defn add [n,m] (fn [f] (fn [x] ((m f)((n f) x))))) (defn mult [n,m] (fn [f] (fn [x] ((m (n f)) x)))) (defn power [b,e] (e b))   (defn to-int [c] ((c inc) 0))   (defn from-int [n] (letfn [(countdown [i] (if (zero? i) zero (succ (countdown (- i 1)))))] (countdown n)))   (def three (succ (succ (succ zero)))) (def four (from-int 4))   (doseq [n [(add three four) (mult three four) (power three four) (power four three)]] (println (to-int n)))
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, as a type, has the values and operations of its own. The operations of are usually called methods of the root type. Both operations and values are called polymorphic. A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument. The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual. Operations with multiple arguments and/or the results of the class are called multi-methods. A further generalization of is the operation with arguments and/or results from different classes. single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x). multiple-dispatch languages allow many arguments and/or results to control the dispatch. A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type. This type is sometimes called the most specific type of a [polymorphic] value. The type tag of the value is used in order to resolve the dispatch. The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class. In many OO languages the type of the class of T and T itself are considered equivalent. In some languages they are distinct (like in Ada). When class T and T are equivalent, there is no way to distinguish polymorphic and specific values. Task Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
#C.23
C#
public class MyClass { public MyClass() { } public void SomeMethod() { } private int _variable; public int Variable { get { return _variable; } set { _variable = value; } } public static void Main() { // instantiate it MyClass instance = new MyClass(); // invoke the method instance.SomeMethod(); // set the variable instance.Variable = 99; // get the variable System.Console.WriteLine( "Variable=" + instance.Variable.ToString() ); } }
http://rosettacode.org/wiki/Cistercian_numerals
Cistercian numerals
Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999. How they work All Cistercian numerals begin with a vertical line segment, which by itself represents the number 0. Then, glyphs representing the digits 1 through 9 are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number: The upper-right quadrant represents the ones place. The upper-left quadrant represents the tens place. The lower-right quadrant represents the hundreds place. The lower-left quadrant represents the thousands place. Please consult the following image for examples of Cistercian numerals showing each glyph: [1] Task Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile). Use the routine to show the following Cistercian numerals: 0 1 20 300 4000 5555 6789 And a number of your choice! Notes Due to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed — especially for text output. See also Numberphile - The Forgotten Number System dcode.fr - Online Cistercian numeral converter
#J
J
main'jc.svg'[load'jc.ijs' open browser to /tmp/jc.svg
http://rosettacode.org/wiki/Cistercian_numerals
Cistercian numerals
Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999. How they work All Cistercian numerals begin with a vertical line segment, which by itself represents the number 0. Then, glyphs representing the digits 1 through 9 are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number: The upper-right quadrant represents the ones place. The upper-left quadrant represents the tens place. The lower-right quadrant represents the hundreds place. The lower-left quadrant represents the thousands place. Please consult the following image for examples of Cistercian numerals showing each glyph: [1] Task Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile). Use the routine to show the following Cistercian numerals: 0 1 20 300 4000 5555 6789 And a number of your choice! Notes Due to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed — especially for text output. See also Numberphile - The Forgotten Number System dcode.fr - Online Cistercian numeral converter
#Java
Java
import java.util.Arrays; import java.util.List;   public class Cistercian { private static final int SIZE = 15; private final char[][] canvas = new char[SIZE][SIZE];   public Cistercian(int n) { initN(); draw(n); }   public void initN() { for (var row : canvas) { Arrays.fill(row, ' '); row[5] = 'x'; } }   private void horizontal(int c1, int c2, int r) { for (int c = c1; c <= c2; c++) { canvas[r][c] = 'x'; } }   private void vertical(int r1, int r2, int c) { for (int r = r1; r <= r2; r++) { canvas[r][c] = 'x'; } }   private void diagd(int c1, int c2, int r) { for (int c = c1; c <= c2; c++) { canvas[r + c - c1][c] = 'x'; } }   private void diagu(int c1, int c2, int r) { for (int c = c1; c <= c2; c++) { canvas[r - c + c1][c] = 'x'; } }   private void draw(int v) { var thousands = v / 1000; v %= 1000;   var hundreds = v / 100; v %= 100;   var tens = v / 10; var ones = v % 10;   drawPart(1000 * thousands); drawPart(100 * hundreds); drawPart(10 * tens); drawPart(ones); }   private void drawPart(int v) { switch (v) { case 1: horizontal(6, 10, 0); break; case 2: horizontal(6, 10, 4); break; case 3: diagd(6, 10, 0); break; case 4: diagu(6, 10, 4); break; case 5: drawPart(1); drawPart(4); break; case 6: vertical(0, 4, 10); break; case 7: drawPart(1); drawPart(6); break; case 8: drawPart(2); drawPart(6); break; case 9: drawPart(1); drawPart(8); break;   case 10: horizontal(0, 4, 0); break; case 20: horizontal(0, 4, 4); break; case 30: diagu(0, 4, 4); break; case 40: diagd(0, 4, 0); break; case 50: drawPart(10); drawPart(40); break; case 60: vertical(0, 4, 0); break; case 70: drawPart(10); drawPart(60); break; case 80: drawPart(20); drawPart(60); break; case 90: drawPart(10); drawPart(80); break;   case 100: horizontal(6, 10, 14); break; case 200: horizontal(6, 10, 10); break; case 300: diagu(6, 10, 14); break; case 400: diagd(6, 10, 10); break; case 500: drawPart(100); drawPart(400); break; case 600: vertical(10, 14, 10); break; case 700: drawPart(100); drawPart(600); break; case 800: drawPart(200); drawPart(600); break; case 900: drawPart(100); drawPart(800); break;   case 1000: horizontal(0, 4, 14); break; case 2000: horizontal(0, 4, 10); break; case 3000: diagd(0, 4, 10); break; case 4000: diagu(0, 4, 14); break; case 5000: drawPart(1000); drawPart(4000); break; case 6000: vertical(10, 14, 0); break; case 7000: drawPart(1000); drawPart(6000); break; case 8000: drawPart(2000); drawPart(6000); break; case 9000: drawPart(1000); drawPart(8000); break;   } }   @Override public String toString() { StringBuilder builder = new StringBuilder(); for (var row : canvas) { builder.append(row); builder.append('\n'); } return builder.toString(); }   public static void main(String[] args) { for (int number : List.of(0, 1, 20, 300, 4000, 5555, 6789, 9999)) { System.out.printf("%d:\n", number); var c = new Cistercian(number); System.out.println(c); } } }
http://rosettacode.org/wiki/Colour_bars/Display
Colour bars/Display
Task Display a series of vertical color bars across the width of the display. The color bars should either use:   the system palette,   or   the sequence of colors:   black   red   green   blue   magenta   cyan   yellow   white
#UNIX_Shell
UNIX Shell
#!/bin/sh clear WIDTH=`tput cols` HEIGHT=`tput lines` NUMBARS=8 BARWIDTH=`expr $WIDTH / $NUMBARS`   l="1" # Set the line counter to 1 while [ "$l" -lt $HEIGHT ]; do b="0" # Bar counter while [ "$b" -lt $NUMBARS ]; do tput setab $b s="0" while [ "$s" -lt $BARWIDTH ]; do echo -n " " s=`expr $s + 1` done b=`expr $b + 1` done echo # newline l=`expr $l + 1` done   tput sgr0 # reset
http://rosettacode.org/wiki/Colour_bars/Display
Colour bars/Display
Task Display a series of vertical color bars across the width of the display. The color bars should either use:   the system palette,   or   the sequence of colors:   black   red   green   blue   magenta   cyan   yellow   white
#Wren
Wren
import "graphics" for Canvas, Color import "dome" for Window   class Game { static init() { Window.title = "Color bars" __width = 400 __height = 400 Canvas.resize(__width, __height) Window.resize(__width, __height) var colors = [ Color.hex("000000"), // black Color.hex("FF0000"), // red Color.hex("00FF00"), // green Color.hex("0000FF"), // blue Color.hex("FF00FF"), // magenta Color.hex("00FFFF"), // cyan Color.hex("FFFF00"), // yellow Color.hex("FFFFFF") // white ] drawBars(colors) }   static drawBars(colors) { var w = __width / colors.count var h = __height for (i in 0...colors.count) { Canvas.rectfill(w*i, 0, w, h, colors[i]) } }   static update() {}   static draw(dt) {} }
http://rosettacode.org/wiki/Closest-pair_problem
Closest-pair problem
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a function to find the closest two points among a set of given points in two dimensions,   i.e. to solve the   Closest pair of points problem   in the   planar   case. The straightforward solution is a   O(n2)   algorithm   (which we can call brute-force algorithm);   the pseudo-code (using indexes) could be simply: bruteForceClosestPair of P(1), P(2), ... P(N) if N < 2 then return ∞ else minDistance ← |P(1) - P(2)| minPoints ← { P(1), P(2) } foreach i ∈ [1, N-1] foreach j ∈ [i+1, N] if |P(i) - P(j)| < minDistance then minDistance ← |P(i) - P(j)| minPoints ← { P(i), P(j) } endif endfor endfor return minDistance, minPoints endif A better algorithm is based on the recursive divide&conquer approach,   as explained also at   Wikipedia's Closest pair of points problem,   which is   O(n log n);   a pseudo-code could be: closestPair of (xP, yP) where xP is P(1) .. P(N) sorted by x coordinate, and yP is P(1) .. P(N) sorted by y coordinate (ascending order) if N ≤ 3 then return closest points of xP using brute-force algorithm else xL ← points of xP from 1 to ⌈N/2⌉ xR ← points of xP from ⌈N/2⌉+1 to N xm ← xP(⌈N/2⌉)x yL ← { p ∈ yP : px ≤ xm } yR ← { p ∈ yP : px > xm } (dL, pairL) ← closestPair of (xL, yL) (dR, pairR) ← closestPair of (xR, yR) (dmin, pairMin) ← (dR, pairR) if dL < dR then (dmin, pairMin) ← (dL, pairL) endif yS ← { p ∈ yP : |xm - px| < dmin } nS ← number of points in yS (closest, closestPair) ← (dmin, pairMin) for i from 1 to nS - 1 k ← i + 1 while k ≤ nS and yS(k)y - yS(i)y < dmin if |yS(k) - yS(i)| < closest then (closest, closestPair) ← (|yS(k) - yS(i)|, {yS(k), yS(i)}) endif k ← k + 1 endwhile endfor return closest, closestPair endif References and further readings   Closest pair of points problem   Closest Pair (McGill)   Closest Pair (UCSB)   Closest pair (WUStL)   Closest pair (IUPUI)
#Common_Lisp
Common Lisp
(defun point-distance (p1 p2) (destructuring-bind (x1 . y1) p1 (destructuring-bind (x2 . y2) p2 (let ((dx (- x2 x1)) (dy (- y2 y1))) (sqrt (+ (* dx dx) (* dy dy)))))))   (defun closest-pair-bf (points) (let ((pair (list (first points) (second points))) (dist (point-distance (first points) (second points)))) (dolist (p1 points (values pair dist)) (dolist (p2 points) (unless (eq p1 p2) (let ((pdist (point-distance p1 p2))) (when (< pdist dist) (setf (first pair) p1 (second pair) p2 dist pdist))))))))   (defun closest-pair (points) (labels ((cp (xp &aux (length (length xp))) (if (<= length 3) (multiple-value-bind (pair distance) (closest-pair-bf xp) (values pair distance (sort xp '< :key 'cdr))) (let* ((xr (nthcdr (1- (floor length 2)) xp)) (xm (/ (+ (caar xr) (caadr xr)) 2))) (psetf xr (rest xr) (rest xr) '()) (multiple-value-bind (lpair ldist yl) (cp xp) (multiple-value-bind (rpair rdist yr) (cp xr) (multiple-value-bind (dist pair) (if (< ldist rdist) (values ldist lpair) (values rdist rpair)) (let* ((all-ys (merge 'vector yl yr '< :key 'cdr)) (ys (remove-if #'(lambda (p) (> (abs (- (car p) xm)) dist)) all-ys)) (ns (length ys))) (dotimes (i ns) (do ((k (1+ i) (1+ k))) ((or (= k ns) (> (- (cdr (aref ys k)) (cdr (aref ys i))) dist))) (let ((pd (point-distance (aref ys i) (aref ys k)))) (when (< pd dist) (setf dist pd (first pair) (aref ys i) (second pair) (aref ys k)))))) (values pair dist all-ys))))))))) (multiple-value-bind (pair distance) (cp (sort (copy-list points) '< :key 'car)) (values pair distance))))
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of running any but the last function, to demonstrate that the function indeed remembers its value. Goal Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. In imperative languages, one would generally use a loop with a mutable counter variable. For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run. See also: Multiple distinct objects
#Io
Io
blist := list(0,1,2,3,4,5,6,7,8,9) map(i,block(i,block(i*i)) call(i)) writeln(blist at(3) call) // prints 9
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of running any but the last function, to demonstrate that the function indeed remembers its value. Goal Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. In imperative languages, one would generally use a loop with a mutable counter variable. For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run. See also: Multiple distinct objects
#J
J
constF=:3 :0 {.''`(y "_) )
http://rosettacode.org/wiki/Circular_primes
Circular primes
Definitions A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime. For example: 1193 is a circular prime, since 1931, 9311 and 3119 are all also prime. Note that a number which is a cyclic permutation of a smaller circular prime is not considered to be itself a circular prime. So 13 is a circular prime, but 31 is not. A repunit (denoted by R) is a number whose base 10 representation contains only the digit 1. For example: R(2) = 11 and R(5) = 11111 are repunits. Task Find the first 19 circular primes. If your language has access to arbitrary precision integer arithmetic, given that they are all repunits, find the next 4 circular primes. (Stretch) Determine which of the following repunits are probably circular primes: R(5003), R(9887), R(15073), R(25031), R(35317) and R(49081). The larger ones may take a long time to process so just do as many as you reasonably can. See also Wikipedia article - Circular primes. Wikipedia article - Repunit. OEIS sequence A016114 - Circular primes.
#Lua
Lua
-- Circular primes, in Lua, 6/22/2020 db local function isprime(n) if n < 2 then return false end if n % 2 == 0 then return n==2 end if n % 3 == 0 then return n==3 end for f = 5, math.sqrt(n), 6 do if n % f == 0 or n % (f+2) == 0 then return false end end return true end   local function iscircularprime(p) local n = math.floor(math.log10(p)) local m, q = 10^n, p for i = 0, n do if (q < p or not isprime(q)) then return false end q = (q % m) * 10 + math.floor(q / m) end return true end   local p, dp, list, N = 2, 1, {}, 19 while #list < N do if iscircularprime(p) then list[#list+1] = p end p, dp = p + dp, 2 end print(table.concat(list, ", "))
http://rosettacode.org/wiki/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a few values to it. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#C.2B.2B
C++
int a[5]; // array of 5 ints (since int is POD, the members are not initialized) a[0] = 1; // indexes start at 0   int primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; // arrays can be initialized on creation   #include <string> std::string strings[4]; // std::string is no POD, therefore all array members are default-initialized // (for std::string this means initialized with empty strings)
http://rosettacode.org/wiki/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 If it is more "natural" in your language to start counting from   1   (unity) instead of   0   (zero), the combinations can be of the integers from   1   to   n. See also The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#IS-BASIC
IS-BASIC
100 PROGRAM "Combinat.bas" 110 LET MMAX=3:LET NMAX=5 120 NUMERIC COMB(0 TO MMAX) 130 CALL GENERATE(1) 140 DEF GENERATE(M) 150 NUMERIC N,I 160 IF M>MMAX THEN 170 FOR I=1 TO MMAX 180 PRINT COMB(I); 190 NEXT 200 PRINT 220 ELSE 230 FOR N=0 TO NMAX-1 240 IF M=1 OR N>COMB(M-1) THEN 250 LET COMB(M)=N 260 CALL GENERATE(M+1) 270 END IF 280 NEXT 290 END IF 300 END DEF
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include if-then-else and switch. Less common are arithmetic if, ternary operator and Hash-based conditionals. Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
#PHP
PHP
<?php   $foo = 3;   if ($foo == 2) //do something   if ($foo == 3) //do something else //do something else   if ($foo != 0) { //do something } else { //do another thing }   ?>
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Verilog
Verilog
// Single line commment.   /* Multiple line comment. */
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#VHDL
VHDL
-- Single line commment in VHDL
http://rosettacode.org/wiki/Comments
Comments
Task Show all ways to include text in a language source file that's completely ignored by the compiler or interpreter. Related tasks   Documentation   Here_document See also   Wikipedia   xkcd (Humor: hand gesture denoting // for "commenting out" people.)
#Vim_Script
Vim Script
let a = 4 " A valid comment echo "foo" " Not a comment but an argument that misses the closing quote
http://rosettacode.org/wiki/Chowla_numbers
Chowla numbers
Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n   is a positive integer The sequence is named after   Sarvadaman D. S. Chowla,   (22 October 1907 ──► 10 December 1995), a London born Indian American mathematician specializing in number theory. German mathematician Carl Friedrich Gauss (1777─1855) said: "Mathematics is the queen of the sciences ─ and number theory is the queen of mathematics". Definitions Chowla numbers can also be expressed as: chowla(n) = sum of divisors of n excluding unity and n chowla(n) = sum( divisors(n)) - 1 - n chowla(n) = sum( properDivisors(n)) - 1 chowla(n) = sum(aliquotDivisors(n)) - 1 chowla(n) = aliquot(n) - 1 chowla(n) = sigma(n) - 1 - n chowla(n) = sigmaProperDivisiors(n) - 1   chowla(a*b) = a + b,   if a and b are distinct primes if chowla(n) = 0,  and n > 1, then n is prime if chowla(n) = n - 1, and n > 1, then n is a perfect number Task   create a   chowla   function that returns the   chowla number   for a positive integer   n   Find and display   (1 per line)   for the 1st   37   integers:   the integer   (the index)   the chowla number for that integer   For finding primes, use the   chowla   function to find values of zero   Find and display the   count   of the primes up to              100   Find and display the   count   of the primes up to           1,000   Find and display the   count   of the primes up to         10,000   Find and display the   count   of the primes up to       100,000   Find and display the   count   of the primes up to    1,000,000   Find and display the   count   of the primes up to  10,000,000   For finding perfect numbers, use the   chowla   function to find values of   n - 1   Find and display all   perfect numbers   up to   35,000,000   use commas within appropriate numbers   show all output here Related tasks   totient function   perfect numbers   Proper divisors   Sieve of Eratosthenes See also   the OEIS entry for   A48050 Chowla's function.
#11l
11l
F chowla(n) V sum = 0 V i = 2 L i * i <= n I n % i == 0 sum += i V j = n I/ i I i != j sum += j i++ R sum   L(n) 1..37 print(‘chowla(’n‘) = ’chowla(n))   V count = 0 V power = 100 L(n) 2..10'000'000 I chowla(n) == 0 count++ I n % power == 0 print(‘There are ’count‘ primes < ’power) power *= 10   count = 0 V limit = 350'000'000 V k = 2 V kk = 3 L V p = k * kk I p > limit L.break I chowla(p) == p - 1 print(p‘ is a perfect number’) count++ k = kk + 1 kk += k print(‘There are ’count‘ perfect numbers < ’limit)
http://rosettacode.org/wiki/Church_numerals
Church numerals
Task In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all. Church one applies its first argument f just once to its second argument x, yielding f(x) Church two applies its first argument f twice to its second argument x, yielding f(f(x)) and each successive Church numeral applies its first argument one additional time to its second argument, f(f(f(x))), f(f(f(f(x)))) ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument. Arithmetic operations on natural numbers can be similarly represented as functions on Church numerals. In your language define: Church Zero, a Church successor function (a function on a Church numeral which returns the next Church numeral in the series), functions for Addition, Multiplication and Exponentiation over Church numerals, a function to convert integers to corresponding Church numerals, and a function to convert Church numerals to corresponding integers. You should: Derive Church numerals three and four in terms of Church zero and a Church successor function. use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4, similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function, convert each result back to an integer, and return it or print it to the console.
#Crystal
Crystal
struct Church # can't be generic! getter church : (Church -> Church) | Int32 def initialize(@church) end def apply(ch) chf = @church chf.responds_to?(:call) ? chf.call(ch) : self end def compose(chr) chlf = @church chrf = chr.church if chlf.responds_to?(:call) && chrf.responds_to?(:call) Church.new(-> (f : Church) { chlf.call(chrf.call(f)) }) else self end end end   # Church Numeral constants... CHURCH_ZERO = begin Church.new(-> (f : Church) { Church.new(-> (x : Church) { x }) }) end   CHURCH_ONE = begin Church.new(-> (f : Church) { f }) end   # Church Numeral functions... def succChurch -> (ch : Church) { Church.new(-> (f : Church) { f.compose(ch.apply(f)) }) } end   def addChurch -> (cha : Church, chb : Church) { Church.new(-> (f : Church) { cha.apply(f).compose(chb.apply(f)) }) } end   def multChurch -> (cha : Church, chb : Church) { cha.compose(chb) } end   def expChurch -> (chbs : Church, chexp : Church) { chexp.apply(chbs) } end   def isZeroChurch liftZero = Church.new(-> (f : Church) { CHURCH_ZERO }) -> (ch : Church) { ch.apply(liftZero).apply(CHURCH_ONE) } end   def predChurch -> (ch : Church) { Church.new(-> (f : Church) { Church.new(-> (x : Church) { prd = Church.new(-> (g : Church) { Church.new(-> (h : Church) { h.apply(g.apply(f)) }) }) frst = Church.new(-> (d : Church) { x }) id = Church.new(-> (a : Church) { a }) ch.apply(prd).apply(frst).apply(id) }) }) } end   def subChurch -> (cha : Church, chb : Church) { chb.apply(Church.new(predChurch)).apply(cha) } end   def divr # can't be nested in another def... -> (n : Church, d: Church) { tstr = -> (v : Church) { loopr = Church.new(-> (a : Church) { succChurch.call(divr.call(v, d)) }) # recurse until zero v.apply(loopr).apply(CHURCH_ZERO) } tstr.call(subChurch.call(n, d)) } end   def divChurch -> (chdvdnd : Church, chdvsr : Church) { divr.call(succChurch.call(chdvdnd), chdvsr) } end   # conversion functions... def intToChurch(i) : Church rslt = CHURCH_ZERO cntr = 0 while cntr < i rslt = succChurch.call(rslt) cntr += 1 end rslt end   def churchToInt(ch) : Int32 succInt32 = Church.new(-> (v : Church) { vi = v.church vi.is_a?(Int32) ? Church.new(vi + 1) : v }) rslt = ch.apply(succInt32).apply(Church.new(0)).church rslt.is_a?(Int32) ? rslt : -1 end   # testing... ch3 = intToChurch(3) ch4 = succChurch.call(ch3) ch11 = intToChurch(11) ch12 = succChurch.call(ch11) add = churchToInt(addChurch.call(ch3, ch4)) mult = churchToInt(multChurch.call(ch3, ch4)) exp1 = churchToInt(expChurch.call(ch3, ch4)) exp2 = churchToInt(expChurch.call(ch4, ch3)) iszero1 = churchToInt(isZeroChurch.call(CHURCH_ZERO)) iszero2 = churchToInt(isZeroChurch.call(ch3)) pred1 = churchToInt(predChurch.call(ch4)) pred2 = churchToInt(predChurch.call(CHURCH_ZERO)) sub = churchToInt(subChurch.call(ch11, ch3)) div1 = churchToInt(divChurch.call(ch11, ch3)) div2 = churchToInt(divChurch.call(ch12, ch3)) print("#{add} #{mult} #{exp1} #{exp2} #{iszero1} #{iszero2} ") print("#{pred1} #{pred2} #{sub} #{div1} #{div2}\r\n")
http://rosettacode.org/wiki/Church_numerals
Church numerals
Task In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all. Church one applies its first argument f just once to its second argument x, yielding f(x) Church two applies its first argument f twice to its second argument x, yielding f(f(x)) and each successive Church numeral applies its first argument one additional time to its second argument, f(f(f(x))), f(f(f(f(x)))) ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument. Arithmetic operations on natural numbers can be similarly represented as functions on Church numerals. In your language define: Church Zero, a Church successor function (a function on a Church numeral which returns the next Church numeral in the series), functions for Addition, Multiplication and Exponentiation over Church numerals, a function to convert integers to corresponding Church numerals, and a function to convert Church numerals to corresponding integers. You should: Derive Church numerals three and four in terms of Church zero and a Church successor function. use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4, similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function, convert each result back to an integer, and return it or print it to the console.
#Elm
Elm
module Main exposing ( main )   import Html exposing ( Html, text )   type alias Church a = (a -> a) -> a -> a   churchZero : Church a -- a Church constant churchZero = always identity   succChurch : Church a -> Church a succChurch ch = \ f -> f << ch f -- add one recursion   addChurch : Church a -> Church a -> Church a addChurch chaf chbf = \ f -> chaf f << chbf f   multChurch : Church a -> Church a -> Church a multChurch = (<<)   expChurch : Church a -> (Church a -> Church a) -> Church a expChurch = (\ f x y -> f y x) identity -- `flip` inlined   churchFromInt : Int -> Church a churchFromInt n = if n <= 0 then churchZero else succChurch <| churchFromInt (n - 1)   intFromChurch : Church Int -> Int intFromChurch cn = cn ((+) 1) 0 -- `succ` inlined   --------------------------- TEST ------------------------- main : Html Never main = let cThree = churchFromInt 3 cFour = succChurch cThree in [ addChurch cThree cFour , multChurch cThree cFour , expChurch cThree cFour , expChurch cFour cThree ] |> List.map intFromChurch |> Debug.toString |> text
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, as a type, has the values and operations of its own. The operations of are usually called methods of the root type. Both operations and values are called polymorphic. A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument. The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual. Operations with multiple arguments and/or the results of the class are called multi-methods. A further generalization of is the operation with arguments and/or results from different classes. single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x). multiple-dispatch languages allow many arguments and/or results to control the dispatch. A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type. This type is sometimes called the most specific type of a [polymorphic] value. The type tag of the value is used in order to resolve the dispatch. The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class. In many OO languages the type of the class of T and T itself are considered equivalent. In some languages they are distinct (like in Ada). When class T and T are equivalent, there is no way to distinguish polymorphic and specific values. Task Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
#C.2B.2B
C++
class MyClass { public: void someMethod(); // member function = method MyClass(); // constructor private: int variable; // member variable = instance variable };   // implementation of constructor MyClass::MyClass(): variable(0) { // here could be more code }   // implementation of member function void MyClass::someMethod() { variable = 1; // alternatively: this->variable = 1 }   // Create an instance as variable MyClass instance;   // Create an instance on free store MyClass* pInstance = new MyClass; // Instances allocated with new must be explicitly destroyed when not needed any more: delete pInstance;
http://rosettacode.org/wiki/Cistercian_numerals
Cistercian numerals
Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999. How they work All Cistercian numerals begin with a vertical line segment, which by itself represents the number 0. Then, glyphs representing the digits 1 through 9 are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number: The upper-right quadrant represents the ones place. The upper-left quadrant represents the tens place. The lower-right quadrant represents the hundreds place. The lower-left quadrant represents the thousands place. Please consult the following image for examples of Cistercian numerals showing each glyph: [1] Task Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile). Use the routine to show the following Cistercian numerals: 0 1 20 300 4000 5555 6789 And a number of your choice! Notes Due to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed — especially for text output. See also Numberphile - The Forgotten Number System dcode.fr - Online Cistercian numeral converter
#JavaScript
JavaScript
  // html document.write(` <p><input id="num" type="number" min="0" max="9999" value="0" onchange="showCist()"></p> <p><canvas id="cist" width="200" height="300"></canvas></p> <p> <!-- EXAMPLES (can be deleted for normal use) --> <button onclick="set(0)">0</button> <button onclick="set(1)">1</button> <button onclick="set(20)">20</button> <button onclick="set(300)">300</button> <button onclick="set(4000)">4000</button> <button onclick="set(5555)">5555</button> <button onclick="set(6789)">6789</button> <button onclick="set(Math.floor(Math.random()*1e4))">Random</button> </p> `);   // to show given examples // can be deleted for normal use function set(num) { document.getElementById('num').value = num; showCist(); }   const SW = 10; // stroke width let canvas = document.getElementById('cist'), cx = canvas.getContext('2d');   function showCist() { // reset canvas cx.clearRect(0, 0, canvas.width, canvas.height); cx.lineWidth = SW; cx.beginPath(); cx.moveTo(100, 0+.5*SW); cx.lineTo(100, 300-.5*SW); cx.stroke();   let num = document.getElementById('num').value; while (num.length < 4) num = '0' + num; // fills leading zeros to $num   /***********************\ | POINTS: | | ********************* | | | | a --- b --- c | | | | | | | d --- e --- f | | | | | | | g --- h --- i | | | | | | | j --- k --- l | | | \***********************/ let a = [0+SW, 0+SW], b = [100, 0+SW], c = [200-SW, 0+SW], d = [0+SW, 100], e = [100, 100], f = [200-SW, 100], g = [0+SW, 200], h = [100, 200], i = [200-SW, 200], j = [0+SW, 300-SW], k = [100, 300-SW], l = [200-SW, 300-SW];   function draw() { let x = 1; cx.beginPath(); cx.moveTo(arguments[0][0], arguments[0][1]); while (x < arguments.length) { cx.lineTo(arguments[x][0], arguments[x][1]); x++; } cx.stroke(); }   // 1000s switch (num[0]) { case '1': draw(j, k); break; case '2': draw(g, h); break; case '3': draw(g, k); break; case '4': draw(j, h); break; case '5': draw(k, j, h); break; case '6': draw(g, j); break; case '7': draw(g, j, k); break; case '8': draw(j, g, h); break; case '9': draw(h, g, j, k); break; } // 100s switch (num[1]) { case '1': draw(k, l); break; case '2': draw(h, i); break; case '3': draw(k, i); break; case '4': draw(h, l); break; case '5': draw(h, l, k); break; case '6': draw(i, l); break; case '7': draw(k, l, i); break; case '8': draw(h, i, l); break; case '9': draw(h, i, l, k); break; } // 10s switch (num[2]) { case '1': draw(a, b); break; case '2': draw(d, e); break; case '3': draw(d, b); break; case '4': draw(a, e); break; case '5': draw(b, a, e); break; case '6': draw(a, d); break; case '7': draw(d, a, b); break; case '8': draw(a, d, e); break; case '9': draw(b, a, d, e); break; } // 1s switch (num[3]) { case '1': draw(b, c); break; case '2': draw(e, f); break; case '3': draw(b, f); break; case '4': draw(e, c); break; case '5': draw(b, c, e); break; case '6': draw(c, f); break; case '7': draw(b, c, f); break; case '8': draw(e, f, c); break; case '9': draw(b, c, f, e); break; } }  
http://rosettacode.org/wiki/Colour_bars/Display
Colour bars/Display
Task Display a series of vertical color bars across the width of the display. The color bars should either use:   the system palette,   or   the sequence of colors:   black   red   green   blue   magenta   cyan   yellow   white
#XPL0
XPL0
include c:\cxpl\codes; \intrinsic code declarations int W, X0, X1, Y, C; [SetVid($13); \320x200x8 graphics W:= 320/8; \width of color bar (pixels) for C:= 0 to 8-1 do [X0:= W*C; X1:= X0+W-1; for Y:= 0 to 200-1 do [Move(X0, Y); Line(X1, Y, C)]; ]; C:= ChIn(1); \wait for keystroke SetVid(3); \restore normal text mode ]
http://rosettacode.org/wiki/Closest-pair_problem
Closest-pair problem
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a function to find the closest two points among a set of given points in two dimensions,   i.e. to solve the   Closest pair of points problem   in the   planar   case. The straightforward solution is a   O(n2)   algorithm   (which we can call brute-force algorithm);   the pseudo-code (using indexes) could be simply: bruteForceClosestPair of P(1), P(2), ... P(N) if N < 2 then return ∞ else minDistance ← |P(1) - P(2)| minPoints ← { P(1), P(2) } foreach i ∈ [1, N-1] foreach j ∈ [i+1, N] if |P(i) - P(j)| < minDistance then minDistance ← |P(i) - P(j)| minPoints ← { P(i), P(j) } endif endfor endfor return minDistance, minPoints endif A better algorithm is based on the recursive divide&conquer approach,   as explained also at   Wikipedia's Closest pair of points problem,   which is   O(n log n);   a pseudo-code could be: closestPair of (xP, yP) where xP is P(1) .. P(N) sorted by x coordinate, and yP is P(1) .. P(N) sorted by y coordinate (ascending order) if N ≤ 3 then return closest points of xP using brute-force algorithm else xL ← points of xP from 1 to ⌈N/2⌉ xR ← points of xP from ⌈N/2⌉+1 to N xm ← xP(⌈N/2⌉)x yL ← { p ∈ yP : px ≤ xm } yR ← { p ∈ yP : px > xm } (dL, pairL) ← closestPair of (xL, yL) (dR, pairR) ← closestPair of (xR, yR) (dmin, pairMin) ← (dR, pairR) if dL < dR then (dmin, pairMin) ← (dL, pairL) endif yS ← { p ∈ yP : |xm - px| < dmin } nS ← number of points in yS (closest, closestPair) ← (dmin, pairMin) for i from 1 to nS - 1 k ← i + 1 while k ≤ nS and yS(k)y - yS(i)y < dmin if |yS(k) - yS(i)| < closest then (closest, closestPair) ← (|yS(k) - yS(i)|, {yS(k), yS(i)}) endif k ← k + 1 endwhile endfor return closest, closestPair endif References and further readings   Closest pair of points problem   Closest Pair (McGill)   Closest Pair (UCSB)   Closest pair (WUStL)   Closest pair (IUPUI)
#Crystal
Crystal
import std.stdio, std.typecons, std.math, std.algorithm, std.random, std.traits, std.range, std.complex;   auto bruteForceClosestPair(T)(in T[] points) pure nothrow @nogc { // return pairwise(points.length.iota, points.length.iota) // .reduce!(min!((i, j) => abs(points[i] - points[j]))); auto minD = Unqual!(typeof(T.re)).infinity; T minI, minJ; foreach (immutable i, const p1; points.dropBackOne) foreach (const p2; points[i + 1 .. $]) { immutable dist = abs(p1 - p2); if (dist < minD) { minD = dist; minI = p1; minJ = p2; } } return tuple(minD, minI, minJ); }   auto closestPair(T)(T[] points) pure nothrow { static Tuple!(typeof(T.re), T, T) inner(in T[] xP, /*in*/ T[] yP) pure nothrow { if (xP.length <= 3) return xP.bruteForceClosestPair; const Pl = xP[0 .. $ / 2]; const Pr = xP[$ / 2 .. $]; immutable xDiv = Pl.back.re; auto Yr = yP.partition!(p => p.re <= xDiv); immutable dl_pairl = inner(Pl, yP[0 .. yP.length - Yr.length]); immutable dr_pairr = inner(Pr, Yr); immutable dm_pairm = dl_pairl[0]<dr_pairr[0] ? dl_pairl : dr_pairr; immutable dm = dm_pairm[0]; const nextY = yP.filter!(p => abs(p.re - xDiv) < dm).array;   if (nextY.length > 1) { auto minD = typeof(T.re).infinity; size_t minI, minJ; foreach (immutable i; 0 .. nextY.length - 1) foreach (immutable j; i + 1 .. min(i + 8, nextY.length)) { immutable double dist = abs(nextY[i] - nextY[j]); if (dist < minD) { minD = dist; minI = i; minJ = j; } } return dm <= minD ? dm_pairm : typeof(return)(minD, nextY[minI], nextY[minJ]); } else return dm_pairm; }   points.sort!q{ a.re < b.re }; const xP = points.dup; points.sort!q{ a.im < b.im }; return inner(xP, points); }   void main() { alias C = complex; auto pts = [C(5,9), C(9,3), C(2), C(8,4), C(7,4), C(9,10), C(1,9), C(8,2), C(0,10), C(9,6)]; pts.writeln; writeln("bruteForceClosestPair: ", pts.bruteForceClosestPair); writeln(" closestPair: ", pts.closestPair);   rndGen.seed = 1; Complex!double[10_000] points; foreach (ref p; points) p = C(uniform(0.0, 1000.0) + uniform(0.0, 1000.0)); writeln("bruteForceClosestPair: ", points.bruteForceClosestPair); writeln(" closestPair: ", points.closestPair); }
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of running any but the last function, to demonstrate that the function indeed remembers its value. Goal Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. In imperative languages, one would generally use a loop with a mutable counter variable. For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run. See also: Multiple distinct objects
#Java
Java
import java.util.function.Supplier; import java.util.ArrayList;   public class ValueCapture { public static void main(String[] args) { ArrayList<Supplier<Integer>> funcs = new ArrayList<>(); for (int i = 0; i < 10; i++) { int j = i; funcs.add(() -> j * j); }   Supplier<Integer> foo = funcs.get(3); System.out.println(foo.get()); // prints "9" } }
http://rosettacode.org/wiki/Circular_primes
Circular primes
Definitions A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime. For example: 1193 is a circular prime, since 1931, 9311 and 3119 are all also prime. Note that a number which is a cyclic permutation of a smaller circular prime is not considered to be itself a circular prime. So 13 is a circular prime, but 31 is not. A repunit (denoted by R) is a number whose base 10 representation contains only the digit 1. For example: R(2) = 11 and R(5) = 11111 are repunits. Task Find the first 19 circular primes. If your language has access to arbitrary precision integer arithmetic, given that they are all repunits, find the next 4 circular primes. (Stretch) Determine which of the following repunits are probably circular primes: R(5003), R(9887), R(15073), R(25031), R(35317) and R(49081). The larger ones may take a long time to process so just do as many as you reasonably can. See also Wikipedia article - Circular primes. Wikipedia article - Repunit. OEIS sequence A016114 - Circular primes.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[RepUnit, CircularPrimeQ] RepUnit[n_] := (10^n - 1)/9 CircularPrimeQ[n_Integer] := Module[{id = IntegerDigits[n], nums, t}, AllTrue[ Range[Length[id]] , Function[{z}, t = FromDigits[RotateLeft[id, z]]; If[t < n, False , PrimeQ[t] ] ] ] ] Select[Range[200000], CircularPrimeQ]   res = {}; Dynamic[res] Do[ If[CircularPrimeQ[RepUnit[n]], AppendTo[res, n]] , {n, 1000} ]   Scan[Print@*PrimeQ@*RepUnit, {5003, 9887, 15073, 25031, 35317, 49081}]
http://rosettacode.org/wiki/Circular_primes
Circular primes
Definitions A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime. For example: 1193 is a circular prime, since 1931, 9311 and 3119 are all also prime. Note that a number which is a cyclic permutation of a smaller circular prime is not considered to be itself a circular prime. So 13 is a circular prime, but 31 is not. A repunit (denoted by R) is a number whose base 10 representation contains only the digit 1. For example: R(2) = 11 and R(5) = 11111 are repunits. Task Find the first 19 circular primes. If your language has access to arbitrary precision integer arithmetic, given that they are all repunits, find the next 4 circular primes. (Stretch) Determine which of the following repunits are probably circular primes: R(5003), R(9887), R(15073), R(25031), R(35317) and R(49081). The larger ones may take a long time to process so just do as many as you reasonably can. See also Wikipedia article - Circular primes. Wikipedia article - Repunit. OEIS sequence A016114 - Circular primes.
#Nim
Nim
import bignum import strformat   const SmallPrimes = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]   let One = newInt(1) Two = newInt(2) Ten = newInt(10)   #---------------------------------------------------------------------------------------------------   proc isPrime(n: Int): bool =   if n < Two: return false   for sp in SmallPrimes: # let spb = newInt(sp) if n == sp: return true if (n mod sp).isZero: return false if n < sp * sp: return true   result = probablyPrime(n, 25) != 0   #---------------------------------------------------------------------------------------------------   proc cycle(n: Int): Int =   var m = n var p = 1 while m >= Ten: p *= 10 m = m div 10 result = m + Ten * (n mod p)   #---------------------------------------------------------------------------------------------------   proc isCircularPrime(p: Int): bool =   if not p.isPrime(): return false   var p2 = cycle(p) while p2 != p: if p2 < p or not p2.isPrime(): return false p2 = cycle(p2) result = true   #---------------------------------------------------------------------------------------------------   proc testRepunit(digits: int) =   var repunit = One var count = digits - 1 while count > 0: repunit = Ten * repunit + One dec count if repunit.isPrime(): echo fmt"R({digits}) is probably prime." else: echo fmt"R({digits}) is not prime."   #---------------------------------------------------------------------------------------------------   echo "First 19 circular primes:" var p = 2 var line = "" var count = 0 while count < 19: if newInt(p).isCircularPrime(): if count > 0: line.add(", ") line.add($p) inc count inc p echo line   echo "" echo "Next 4 circular primes:" var repunit = One var digits = 1 while repunit < p: repunit = Ten * repunit + One inc digits line = "" count = 0 while count < 4: if repunit.isPrime(): if count > 0: line.add(' ') line.add(fmt"R({digits})") inc count repunit = Ten * repunit + One inc digits echo line   echo "" testRepUnit(5003) testRepUnit(9887) testRepUnit(15073) testRepUnit(25031) testRepUnit(35317) testRepUnit(49081)
http://rosettacode.org/wiki/Collections
Collections
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. Task Create a collection, and add a few values to it. See also Array Associative array: Creation, Iteration Collections Compound data type Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal Linked list Queue: Definition, Usage Set Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal Stack
#Clojure
Clojure
{1 "a", "Q" 10} ; commas are treated as whitespace (hash-map 1 "a" "Q" 10) ; equivalent to the above (let [my-map {1 "a"}] (assoc my-map "Q" 10)) ; "adding" an element
http://rosettacode.org/wiki/Combinations
Combinations
Task Given non-negative integers   m   and   n,   generate all size   m   combinations   of the integers from   0   (zero)   to   n-1   in sorted order   (each combination is sorted and the entire table is sorted). Example 3   comb   5     is: 0 1 2 0 1 3 0 1 4 0 2 3 0 2 4 0 3 4 1 2 3 1 2 4 1 3 4 2 3 4 If it is more "natural" in your language to start counting from   1   (unity) instead of   0   (zero), the combinations can be of the integers from   1   to   n. See also The number of samples of size k from n objects. With   combinations and permutations   generation tasks. Order Unimportant Order Important Without replacement ( n k ) = n C k = n ( n − 1 ) … ( n − k + 1 ) k ( k − 1 ) … 1 {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} _{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}} n P k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle ^{n}\operatorname {P} _{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)} Task: Combinations Task: Permutations With replacement ( n + k − 1 k ) = n + k − 1 C k = ( n + k − 1 ) ! ( n − 1 ) ! k ! {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} _{k}={(n+k-1)! \over (n-1)!k!}} n k {\displaystyle n^{k}} Task: Combinations with repetitions Task: Permutations with repetitions
#J
J
require'stats'
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include if-then-else and switch. Less common are arithmetic if, ternary operator and Hash-based conditionals. Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
#Picat
Picat
go => N = 10,    % "direct" test that will fail if not satisfied N < 14,    % if/then/elseif/else if N < 14 then println("less than 14") elseif N == 14 then println("is 14") else println("not less than 14") end,    % From Prolog: (condition -> then ; else) ( N < 14 -> println("less than 14")  ; println("not less than 14") ),    % Ret = cond(condition, then, else) println(cond(N < 14, "less than 14", "not less than 14")),    % as a predicate test_pred(N),    % as condition in a function's head println(test_func(N)),   println(ok), % all tests are ok   nl.   % as a predicate test_pred(N) ?=> N < 14, println("less than 14"). test_pred(N) => N >= 14, println("not less than 14").   % condition in function head test_func(N) = "less than 14", N < 14 => true. test_func(_N) = "not less than 14" => true.