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/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
#C.2B.2B
C++
#include <iostream> #include <functional> #include <vector>   int main() { std::vector<std::function<int()> > funcs; for (int i = 0; i < 10; i++) funcs.push_back([=]() { return i * i; }); for ( std::function<int( )> f : funcs ) std::cout << f( ) << std::endl ; return 0; }
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.
#C
C
#include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <gmp.h>   bool is_prime(uint32_t n) { if (n == 2) return true; if (n < 2 || n % 2 == 0) return false; for (uint32_t p = 3; p * p <= n; p += 2) { if (n % p == 0) return false; } return true; }   // e.g. returns 2341 if n = 1234 uint32_t cycle(uint32_t n) { uint32_t m = n, p = 1; while (m >= 10) { p *= 10; m /= 10; } return m + 10 * (n % p); }   bool is_circular_prime(uint32_t p) { if (!is_prime(p)) return false; uint32_t p2 = cycle(p); while (p2 != p) { if (p2 < p || !is_prime(p2)) return false; p2 = cycle(p2); } return true; }   void test_repunit(uint32_t digits) { char* str = malloc(digits + 1); if (str == 0) { fprintf(stderr, "Out of memory\n"); exit(1); } memset(str, '1', digits); str[digits] = 0; mpz_t bignum; mpz_init_set_str(bignum, str, 10); free(str); if (mpz_probab_prime_p(bignum, 10)) printf("R(%u) is probably prime.\n", digits); else printf("R(%u) is not prime.\n", digits); mpz_clear(bignum); }   int main() { uint32_t p = 2; printf("First 19 circular primes:\n"); for (int count = 0; count < 19; ++p) { if (is_circular_prime(p)) { if (count > 0) printf(", "); printf("%u", p); ++count; } } printf("\n"); printf("Next 4 circular primes:\n"); uint32_t repunit = 1, digits = 1; for (; repunit < p; ++digits) repunit = 10 * repunit + 1; mpz_t bignum; mpz_init_set_ui(bignum, repunit); for (int count = 0; count < 4; ) { if (mpz_probab_prime_p(bignum, 15)) { if (count > 0) printf(", "); printf("R(%u)", digits); ++count; } ++digits; mpz_mul_ui(bignum, bignum, 10); mpz_add_ui(bignum, bignum, 1); } mpz_clear(bignum); printf("\n"); test_repunit(5003); test_repunit(9887); test_repunit(15073); test_repunit(25031); test_repunit(35317); test_repunit(49081); return 0; }
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
#ABAP
ABAP
  REPORT z_test_rosetta_collection.   CLASS lcl_collection DEFINITION CREATE PUBLIC.   PUBLIC SECTION. METHODS: start. ENDCLASS.   CLASS lcl_collection IMPLEMENTATION. METHOD start. DATA(itab) = VALUE int4_table( ( 1 ) ( 2 ) ( 3 ) ).   cl_demo_output=>display( itab ). ENDMETHOD. ENDCLASS.   START-OF-SELECTION. NEW lcl_collection( )->start( ).  
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
#Emacs_Lisp
Emacs Lisp
(defun comb-recurse (m n n-max) (cond ((zerop m) '(())) ((= n-max n) '()) (t (append (mapcar #'(lambda (rest) (cons n rest)) (comb-recurse (1- m) (1+ n) n-max)) (comb-recurse m (1+ n) n-max)))))   (defun comb (m n) (comb-recurse m 0 n))   (comb 3 5)
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.
#Objective-C
Objective-C
let condition = true   if condition then 1 (* evaluate something *) else 2 (* evaluate 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.)
#Set_lang
Set lang
> Comments start where a > (greater than symbol) starts set a 0 > Comments may start after a Set command
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.)
#SETL
SETL
print("This is not a comment"); -- This is a comment $ For nostalgic reasons, this is also 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.)
#Sidef
Sidef
# this is commented
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
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { Module Bars { barwidth=x.twips div 8 barheight=y.twips barcolors=(0,#ff0000,#00ff00, #0000ff, #FF00FF, #00ffff, #ffff00, #ffffff) For i=0 to 7 Move i*barwidth, 0 \\ gradient fill. Here second color are the same as first color Fill barwidth, barheight, array(barcolors, i), array(barcolors, i) Next i } \\ first draw on console Call Bars Declare Form1 Form Layer Form1 { window 12, 10000,8000; \\ now draw on Form1 layer, above console, in a window Call Bars } Method Form1, "Show", 1 ' open modal Declare Form1 Nothing } Checkit  
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
#Maple
Maple
  with(plottools): plots:-display([rectangle([0, 0], [.3, 2.1], color = black), rectangle([.3, 0], [.6, 2.1], color = red), rectangle([.6, 0], [.9, 2.1], color = green), rectangle([.9, 0], [1.2, 2.1], color = magenta), rectangle([1.2, 0], [1.5, 2.1], color = cyan), rectangle([1.5, 0], [1.8, 2.1], color = white), rectangle([1.8, 0], [2.1, 2.1], color = yellow)])  
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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ArrayPlot[ ConstantArray[{Black, Red, Green, Blue, Magenta, Cyan, Yellow, White}, 5]]
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
#Ceylon
Ceylon
shared void run() {   //create a list of closures with a list comprehension value closures = [for(i in 0:10) () => i ^ 2];   for(i->closure in closures.indexed) { print("closure number ``i`` returns: ``closure()``"); } }
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
#Clojure
Clojure
(def funcs (map #(fn [] (* % %)) (range 11))) (printf "%d\n%d\n" ((nth funcs 3)) ((nth funcs 4)))
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.
#C.2B.2B
C++
#include <cstdint> #include <algorithm> #include <iostream> #include <sstream> #include <gmpxx.h>   typedef mpz_class integer;   bool is_prime(const integer& n, int reps = 50) { return mpz_probab_prime_p(n.get_mpz_t(), reps); }   std::string to_string(const integer& n) { std::ostringstream out; out << n; return out.str(); }   bool is_circular_prime(const integer& p) { if (!is_prime(p)) return false; std::string str(to_string(p)); for (size_t i = 0, n = str.size(); i + 1 < n; ++i) { std::rotate(str.begin(), str.begin() + 1, str.end()); integer p2(str, 10); if (p2 < p || !is_prime(p2)) return false; } return true; }   integer next_repunit(const integer& n) { integer p = 1; while (p < n) p = 10 * p + 1; return p; }   integer repunit(int digits) { std::string str(digits, '1'); integer p(str); return p; }   void test_repunit(int digits) { if (is_prime(repunit(digits), 10)) std::cout << "R(" << digits << ") is probably prime\n"; else std::cout << "R(" << digits << ") is not prime\n"; }   int main() { integer p = 2; std::cout << "First 19 circular primes:\n"; for (int count = 0; count < 19; ++p) { if (is_circular_prime(p)) { if (count > 0) std::cout << ", "; std::cout << p; ++count; } } std::cout << '\n'; std::cout << "Next 4 circular primes:\n"; p = next_repunit(p); std::string str(to_string(p)); int digits = str.size(); for (int count = 0; count < 4; ) { if (is_prime(p, 15)) { if (count > 0) std::cout << ", "; std::cout << "R(" << digits << ")"; ++count; } p = repunit(++digits); } std::cout << '\n'; test_repunit(5003); test_repunit(9887); test_repunit(15073); test_repunit(25031); test_repunit(35317); test_repunit(49081); return 0; }
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
#Ada
Ada
procedure Array_Collection is   A : array (-3 .. -1) of Integer := (1, 2, 3);   begin   A (-3) := 3; A (-2) := 2; A (-1) := 1;   end Array_Collection;
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
#Erlang
Erlang
  -module(comb). -compile(export_all).   comb(0,_) -> [[]]; comb(_,[]) -> []; comb(N,[H|T]) -> [[H|L] || L <- comb(N-1,T)]++comb(N,T).  
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.
#OCaml
OCaml
let condition = true   if condition then 1 (* evaluate something *) else 2 (* evaluate 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.)
#Simula
Simula
COMMENT This is a comment for Simula 67;
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.)
#Slate
Slate
"basically the same as smalltalk"
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.)
#Smalltalk
Smalltalk
"Comments traditionally are in double quotes." "Multiline comments are also supported. Comments are saved as metadata along with the source to a method. A comment just after a method signature is often given to explain the usage of the method. The class browser may display such comments specially."
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
#Nim
Nim
import gintro/[glib, gobject, gtk, gio, cairo]   const Width = 400 Height = 300   #---------------------------------------------------------------------------------------------------   proc draw(area: DrawingArea; context: Context) = ## Draw the color bars.   const Colors = [[0.0, 0.0, 0.0], [255.0, 0.0, 0.0], [0.0, 255.0, 0.0], [0.0, 0.0, 255.0], [255.0, 0.0, 255.0], [0.0, 255.0, 255.0], [255.0, 255.0, 0.0], [255.0, 255.0, 255.0]]   const RectWidth = float(Width div Colors.len) RectHeight = float(Height)   var x = 0.0 for color in Colors: context.rectangle(x, 0, RectWidth, RectHeight) context.setSource(color) context.fill() x += RectWidth   #---------------------------------------------------------------------------------------------------   proc onDraw(area: DrawingArea; context: Context; data: pointer): bool = ## Callback to draw/redraw the drawing area contents.   area.draw(context) result = true   #---------------------------------------------------------------------------------------------------   proc activate(app: Application) = ## Activate the application.   let window = app.newApplicationWindow() window.setSizeRequest(Width, Height) window.setTitle("Color bars")   # Create the drawing area. let area = newDrawingArea() window.add(area)   # Connect the "draw" event to the callback to draw the spiral. discard area.connect("draw", ondraw, pointer(nil))   window.showAll()   #———————————————————————————————————————————————————————————————————————————————————————————————————   let app = newApplication(Application, "Rosetta.ColorBars") discard app.connect("activate", activate) discard app.run()
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
#OCaml
OCaml
open Graphics   let round x = int_of_float (floor (x +. 0.5))   let () = open_graph ""; let cols = size_x () in let rows = size_y () in let colors = [| black; red; green; blue; magenta; cyan; yellow; white |] in let n = Array.length colors in let bar_width = (float cols) /. (float n) in Array.iteri (fun i color -> let x1 = bar_width *. (float i) in let x2 = bar_width *. (float (succ i)) in set_color color; fill_rect (round x1) 0 (round x2) rows; ) colors; ignore (read_key ()); ;;
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
#CoffeeScript
CoffeeScript
  # Generate an array of functions. funcs = ( for i in [ 0...10 ] then do ( i ) -> -> i * i )   # Call each function to demonstrate value capture. console.log func() for func in funcs  
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
#Common_Lisp
Common Lisp
CL-USER> (defparameter alist (loop for i from 1 to 10 collect (cons i (let ((i i)) (lambda () (* i i)))))) ALIST CL-USER> (funcall (cdr (assoc 2 alist))) 4 CL-USER> (funcall (cdr (assoc 8 alist))) 64
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.
#D
D
import std.bigint; import std.stdio;   immutable PRIMES = [ 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 ];   bool isPrime(BigInt n) { if (n < 2) { return false; }   foreach (p; PRIMES) { if (n == p) { return true; } if (n % p == 0) { return false; } if (p * p > n) { return true; } }   for (auto m = BigInt(PRIMES[$ - 1]); m * m <= n ; m += 2) { if (n % m == 0) { return false; } }   return true; }   // e.g. returns 2341 if n = 1234 BigInt cycle(BigInt n) { BigInt m = n; BigInt p = 1; while (m >= 10) { p *= 10; m /= 10; } return m + 10 * (n % p); }   bool isCircularPrime(BigInt p) { if (!isPrime(p)) { return false; } for (auto p2 = cycle(p); p2 != p; p2 = cycle(p2)) { if (p2 < p || !isPrime(p2)) { return false; } } return true; }   BigInt repUnit(int len) { BigInt n = 0; while (len > 0) { n = 10 * n + 1; len--; } return n; }   void main() { writeln("First 19 circular primes:"); int count = 0; foreach (p; PRIMES) { if (isCircularPrime(BigInt(p))) { if (count > 0) { write(", "); } write(p); count++; } } for (auto p = BigInt(PRIMES[$ - 1]) + 2; count < 19; p += 2) { if (isCircularPrime(BigInt(p))) { if (count > 0) { write(", "); } write(p); count++; } } writeln; }
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
#Aime
Aime
list l;
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
#ERRE
ERRE
  PROGRAM COMBINATIONS   CONST M_MAX=3,N_MAX=5   DIM COMBINATION[M_MAX],STACK[100,1]   PROCEDURE GENERATE(M) LOCAL I IF (M>M_MAX) THEN FOR I=1 TO M_MAX DO PRINT(COMBINATION[I];" ";) END FOR PRINT ELSE FOR N=1 TO N_MAX DO IF ((M=1) OR (N>COMBINATION[M-1])) THEN COMBINATION[M]=N  ! --- PUSH STACK ----------- STACK[SP,0]=M STACK[SP,1]=N SP=SP+1  ! --------------------------   GENERATE(M+1)    ! --- POP STACK ------------ SP=SP-1 M=STACK[SP,0] N=STACK[SP,1]  ! -------------------------- END IF END FOR END IF END PROCEDURE   BEGIN GENERATE(1) END PROGRAM  
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.
#Octave
Octave
if (condition) % body endif   if (condition) % body else % otherwise body endif   if (condition1) % body elseif (condition2) % body 2 else % otherwise body endif
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.)
#smart_BASIC
smart BASIC
'Single line comments are preceded by a single quote or the command REM   PRINT "Hello" 'Single line comments may follow code   PRINT "Hello" REM You can also use the command REM following code   /* Multi-line comments are surrounded by mirrored slash and asterisk */   /*Multi-line comments do not have to actually have multiple lines*/   /* Spaces before or after comment bounds are optional.*/   /* A comment can also follow another comment */ 'Like this   Some programmers like to do this to allow for /* Procedural comments */ followed by 'Programmer's notes.
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.)
#SNOBOL4
SNOBOL4
  * An asterisk in column 1 is the standard Snobol comment * mechanism, marking the entire line as a comment. There * are no block or multiline comments.   * Comments may begin at * any position on the line.   - A hyphen in column 1 begins a control statement. - Unrecognized control statements are ignored and - may also mark comment lines. Not recommended.    ;* The semicolon statement separator output = 'FOO' ;* begins a new statement. This idiom output = 'BAR' ;* simulates an asterisk in the first  ;* column, allowing end of line comments.   END   Any text after the required END label is ignored.
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.)
#SNUSP
SNUSP
'This is single-line comment   ''This is multiline comment''
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
#Perl
Perl
#!/usr/bin/perl -w use strict ; use GD ;   my %colors = ( 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 ] ) ; my $barwidth = 160 / 8 ; my $image = new GD::Image( 160 , 100 ) ; my $start = 0 ; foreach my $rgb ( values %colors ) { my $paintcolor = $image->colorAllocate( @$rgb ) ; $image->filledRectangle( $start * $barwidth , 0 , $start * $barwidth + $barwidth - 1 , 99 , $paintcolor ) ; $start++ ; } open ( DISPLAY , ">" , "testprogram.png" ) || die ; binmode DISPLAY ; print DISPLAY $image->png ; close DISPLAY ;#to be watched with <image viewer> testprogram.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)
#360_Assembly
360 Assembly
* Closest Pair Problem 10/03/2017 CLOSEST CSECT USING CLOSEST,R13 base register B 72(R15) skip savearea DC 17F'0' savearea STM R14,R12,12(R13) save previous context ST R13,4(R15) link backward ST R15,8(R13) link forward LR R13,R15 set addressability LA R6,1 i=1 LA R7,2 j=2 BAL R14,DDCALC dd=(px(i)-px(j))^2+(py(i)-py(j))^2 BAL R14,DDSTORE ddmin=dd; ii=i; jj=j LA R6,1 i=1 DO WHILE=(C,R6,LE,N) do i=1 to n LA R7,1 j=1 DO WHILE=(C,R7,LE,N) do j=1 to n BAL R14,DDCALC dd=(px(i)-px(j))^2+(py(i)-py(j))^2 IF CP,DD,GT,=P'0' THEN if dd>0 then IF CP,DD,LT,DDMIN THEN if dd<ddmin then BAL R14,DDSTORE ddmin=dd; ii=i; jj=j ENDIF , endif ENDIF , endif LA R7,1(R7) j++ ENDDO , enddo j LA R6,1(R6) i++ ENDDO , enddo i ZAP WPD,DDMIN ddmin DP WPD,=PL8'2' ddmin/2 ZAP SQRT2,WPD(8) sqrt2=ddmin/2 ZAP SQRT1,DDMIN sqrt1=ddmin DO WHILE=(CP,SQRT1,NE,SQRT2) do while sqrt1<>sqrt2 ZAP SQRT1,SQRT2 sqrt1=sqrt2 ZAP WPD,DDMIN ddmin DP WPD,SQRT1 /sqrt1 ZAP WP1,WPD(8) ddmin/sqrt1 AP WP1,SQRT1 +sqrt1 ZAP WPD,WP1 ~ DP WPD,=PL8'2' /2 ZAP SQRT2,WPD(8) sqrt2=(sqrt1+(ddmin/sqrt1))/2 ENDDO , enddo while MVC PG,=CL80'the minimum distance ' ZAP WP1,SQRT2 sqrt2 BAL R14,EDITPK edit MVC PG+21(L'WC),WC output XPRNT PG,L'PG print buffer XPRNT =CL22'is between the points:',22 MVC PG,PGP init buffer L R1,II ii SLA R1,4 *16 LA R4,PXY-16(R1) @px(ii) MVC WP1,0(R4) px(ii) BAL R14,EDITPK edit MVC PG+3(L'WC),WC output MVC WP1,8(R4) py(ii) BAL R14,EDITPK edit MVC PG+21(L'WC),WC output XPRNT PG,L'PG print buffer MVC PG,PGP init buffer L R1,JJ jj SLA R1,4 *16 LA R4,PXY-16(R1) @px(jj) MVC WP1,0(R4) px(jj) BAL R14,EDITPK edit MVC PG+3(L'WC),WC output MVC WP1,8(R4) py(jj) BAL R14,EDITPK edit MVC PG+21(L'WC),WC output XPRNT PG,L'PG print buffer L R13,4(0,R13) restore previous savearea pointer LM R14,R12,12(R13) restore previous context XR R15,R15 rc=0 BR R14 exit DDCALC EQU * ---- dd=(px(i)-px(j))^2+(py(i)-py(j))^2 LR R1,R6 i SLA R1,4 *16 LA R4,PXY-16(R1) @px(i) LR R1,R7 j SLA R1,4 *16 LA R5,PXY-16(R1) @px(j) ZAP WP1,0(8,R4) px(i) ZAP WP2,0(8,R5) px(j) SP WP1,WP2 px(i)-px(j) ZAP WPS,WP1 = MP WP1,WPS (px(i)-px(j))*(px(i)-px(j)) ZAP WP2,8(8,R4) py(i) ZAP WP3,8(8,R5) py(j) SP WP2,WP3 py(i)-py(j) ZAP WPS,WP2 = MP WP2,WPS (py(i)-py(j))*(py(i)-py(j)) AP WP1,WP2 (px(i)-px(j))^2+(py(i)-py(j))^2 ZAP DD,WP1 dd=(px(i)-px(j))^2+(py(i)-py(j))^2 BR R14 ---- return DDSTORE EQU * ---- ddmin=dd; ii=i; jj=j ZAP DDMIN,DD ddmin=dd ST R6,II ii=i ST R7,JJ jj=j BR R14 ---- return EDITPK EQU * ---- MVC WM,MASK set mask EDMK WM,WP1 edit and mark BCTR R1,0 -1 MVC 0(1,R1),WM+17 set sign MVC WC,WM len17<-len18 BR R14 ---- return N DC A((PGP-PXY)/16) PXY DC PL8'0.654682',PL8'0.925557',PL8'0.409382',PL8'0.619391' DC PL8'0.891663',PL8'0.888594',PL8'0.716629',PL8'0.996200' DC PL8'0.477721',PL8'0.946355',PL8'0.925092',PL8'0.818220' DC PL8'0.624291',PL8'0.142924',PL8'0.211332',PL8'0.221507' DC PL8'0.293786',PL8'0.691701',PL8'0.839186',PL8'0.728260' PGP DC CL80' [+xxxxxxxxx.xxxxxx,+xxxxxxxxx.xxxxxx]' MASK DC C' ',7X'20',X'21',X'20',C'.',6X'20',C'-' CL18 15num II DS F JJ DS F DD DS PL8 DDMIN DS PL8 SQRT1 DS PL8 SQRT2 DS PL8 WP1 DS PL8 WP2 DS PL8 WP3 DS PL8 WPS DS PL8 WPD DS PL16 WM DS CL18 WC DS CL17 PG DS CL80 YREGS END CLOSEST
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
#D
D
import std.stdio;   void main() { int delegate()[] funcs;   foreach (i; 0 .. 10) funcs ~= (i => () => i ^^ 2)(i);   writeln(funcs[3]()); }
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
#Delphi
Delphi
program Project1;   type TFuncIntResult = reference to function: Integer;   // use function that returns anonymous method to avoid capturing the loop variable function CreateFunc(i: Integer): TFuncIntResult; begin Result := function: Integer begin Result := i * i; end; end;   var Funcs: array[0..9] of TFuncIntResult; i: integer; begin // create 10 anonymous functions for i := Low(Funcs) to High(Funcs) do Funcs[i] := CreateFunc(i);   // call all 10 functions for i := Low(Funcs) to High(Funcs) do Writeln(Funcs[i]()); 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.
#F.23
F#
  // Circular primes - Nigel Galloway: September 13th., 2021 let fG n g=let rec fG y=if y=g then true else if y>g && isPrime y then fG(10*(y%n)+y/n) else false in fG(10*(g%n)+g/n) let rec fN g l=seq{let g=[for n in g do for g in [1;3;7;9] do let g=n*10+g in yield g] in yield! g|>List.filter(fun n->isPrime n && fG l n); yield! fN g (l*10)} let circP()=seq{yield! [2;3;5;7]; yield! fN [1;3;7;9] 10} circP()|> Seq.take 19 |>Seq.iter(printf "%d "); printfn "" printf "The first 5 repunit primes are "; rUnitP(10)|>Seq.take 5|>Seq.iter(fun n->printf $"R(%d{n}) "); printfn ""  
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
#ALGOL_68
ALGOL 68
# create a constant array of integers and set its values # []INT constant array = ( 1, 2, 3, 4 ); # create an array of integers that can be changed, note the size mst be specified # # this array has the default lower bound of 1 # [ 5 ]INT mutable array := ( 9, 8, 7, 6, 5 ); # modify the second element of the mutable array # mutable array[ 2 ] := -1; # array sizes are normally fixed when the array is created, however arrays can be # # declared to be FLEXible, allowing their sizes to change by assigning a new array to them # # The standard built-in STRING is notionally defined as FLEX[ 1 : 0 ]CHAR in the standard prelude # # Create a string variable: # STRING str := "abc"; # assign a longer value to it # str := "bbc/itv"; # add a few characters to str, +=: adds the text to the beginning, +:= adds it to the end # "[" +=: str; str +:= "]"; # str now contains "[bbc/itv]" # # Arrays of any type can be FLEXible: # # create an array of two integers # FLEX[ 1 : 2 ]INT fa := ( 0, 0 ); # replace it with a new array of 5 elements # fa := LOC[ -2 : 2 ]INT;  
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
#F.23
F#
let choose m n = let rec fC prefix m from = seq { let rec loopFor f = seq { match f with | [] -> () | x::xs -> yield (x, fC [] (m-1) xs) yield! loopFor xs } if m = 0 then yield prefix else for (i, s) in loopFor from do for x in s do yield prefix@[i]@x } fC [] m [0..(n-1)]   [<EntryPoint>] let main argv = choose 3 5 |> Seq.iter (printfn "%A") 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.
#Oforth
Oforth
aBoolean ifTrue: [ ...] aBoolean ifFalse: [ ... ] aObject ifNull: [ ... ] aObject ifNotNull: [ ... ] aObject ifZero: [ ... ]
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.)
#SPL
SPL
'This is single-line comment   ''This is multiline 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.)
#SQL
SQL
SELECT * FROM mytable -- Selects all columns and rows
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.)
#SQL_PL
SQL PL
  --This is a single line 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.
#11l
11l
T MyType Int public_variable // member variable = instance variable . Int private_variable   F () // constructor .private_variable = 0   F someMethod() // member function = method .private_variable = 1 .public_variable = 10
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
#Action.21
Action!
BYTE FUNC AtasciiToInternal(CHAR c) BYTE c2   c2=c&$7F IF c2<32 THEN RETURN (c+64) ELSEIF c2<96 THEN RETURN (c-32) FI RETURN (c)   PROC CharOut(CARD x BYTE y CHAR c) BYTE i,j,v CARD addr   addr=$E000+AtasciiToInternal(c)*8 FOR j=0 TO 7 DO v=Peek(addr) i=8 WHILE i>0 DO IF (v&1)=0 THEN Color=0 ELSE Color=1 FI Plot(x+i,y+j) v=v RSH 1 i==-1 OD addr==+1 OD RETURN   PROC TextOut(CARD x BYTE y CHAR ARRAY text) BYTE i   FOR i=1 TO text(0) DO CharOut(x,y,text(i)) x==+8 OD RETURN   PROC DrawDigit(BYTE d INT x BYTE y INT dx,dy) IF d=1 THEN Plot(x,y) DrawTo(x+dx,y) ELSEIF d=2 THEN Plot(x,y+dy) DrawTo(x+dx,y+dy) ELSEIF d=3 THEN Plot(x,y) DrawTo(x+dx,y+dy) ELSEIF d=4 THEN Plot(x,y+dy) DrawTo(x+dx,y) ELSEIF d=5 THEN Plot(x,y) DrawTo(x+dx,y) DrawTo(x,y+dy) ELSEIF d=6 THEN Plot(x+dx,y) DrawTo(x+dx,y+dy) ELSEIF d=7 THEN Plot(x,y) DrawTo(x+dx,y) DrawTo(x+dx,y+dy) ELSEIF d=8 THEN Plot(x,y+dy) DrawTo(x+dx,y+dy) DrawTo(x+dx,y) ELSEIF d=9 THEN Plot(x,y) DrawTo(x+dx,y) DrawTo(x+dx,y+dy) DrawTo(x,y+dy) FI RETURN   PROC Cystersian(CARD n INT x BYTE y,s) INT ms   ms=-s Color=1 Plot(x+s,y) DrawTo(x+s,y+3*s)   DrawDigit(n MOD 10,x+s,y,s,s) n==/10 DrawDigit(n MOD 10,x+s,y,ms,s) n==/10 DrawDigit(n MOD 10,x+s,y+3*s,s,ms) n==/10 DrawDigit(n MOD 10,x+s,y+3*s,ms,ms) RETURN   PROC Test(CARD n INT x BYTE y,s) CHAR ARRAY text(5)   StrC(n,text) TextOut(x+(2*s-text(0)*8)/2,y-10,text) Cystersian(n,x,y,s) RETURN   PROC Main() CARD ARRAY numbers=[0 1 20 300 4000 5555 6789 6502 1977 2021] BYTE CH=$02FC,COLOR1=$02C5,COLOR2=$02C6 BYTE s=[16],i INT x,y   Graphics(8+16) COLOR1=$0C COLOR2=$02   x=s y=2*s FOR i=0 TO 9 DO Test(numbers(i),x,y,s) x==+4*s IF x>=320-s THEN x=s y==+5*s FI OD   DO UNTIL CH#$FF OD CH=$FF RETURN
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
#Phix
Phix
-- demo\rosetta\Colour_bars.exw with javascript_semantics include pGUI.e constant colours = {CD_BLACK, CD_RED, CD_GREEN, CD_BLUE, CD_MAGENTA, CD_CYAN, CD_YELLOW, CD_WHITE} Ihandle dlg, canvas cdCanvas cdcanvas function redraw_cb(Ihandle /*ih*/, integer /*posx*/, /*posy*/) integer {width, height} = IupGetIntInt(canvas, "DRAWSIZE"), x = 0, lc = length(colours) cdCanvasActivate(cdcanvas) for i=1 to lc do integer w = floor((width-x)/(lc-i+1)) cdCanvasSetForeground(cdcanvas, colours[i]) cdCanvasBox(cdcanvas, x, x+w, 0, height) x += w end for cdCanvasFlush(cdcanvas) return IUP_DEFAULT end function IupOpen() canvas = IupCanvas(Icallback("redraw_cb"),"RASTERSIZE=600x400") -- initial size dlg = IupDialog(canvas,`TITLE="Colour bars"`) IupMap(dlg) cdcanvas = cdCreateCanvas(CD_IUP, canvas) IupShow(dlg) IupSetAttribute(canvas, "RASTERSIZE", NULL) -- release the minimum limitation if platform()!=JS then IupMainLoop() IupClose() end if
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)
#Ada
Ada
with Ada.Numerics.Generic_Elementary_Functions; with Ada.Text_IO;   procedure Closest is package Math is new Ada.Numerics.Generic_Elementary_Functions (Float);   Dimension : constant := 2; type Vector is array (1 .. Dimension) of Float; type Matrix is array (Positive range <>) of Vector;   -- calculate the distance of two points function Distance (Left, Right : Vector) return Float is Result : Float := 0.0; Offset : Natural := 0; begin loop Result := Result + (Left(Left'First + Offset) - Right(Right'First + Offset))**2; Offset := Offset + 1; exit when Offset >= Left'Length; end loop; return Math.Sqrt (Result); end Distance;   -- determine the two closest points inside a cloud of vectors function Get_Closest_Points (Cloud : Matrix) return Matrix is Result : Matrix (1..2); Min_Distance : Float; begin if Cloud'Length(1) < 2 then raise Constraint_Error; end if; Result := (Cloud (Cloud'First), Cloud (Cloud'First + 1)); Min_Distance := Distance (Cloud (Cloud'First), Cloud (Cloud'First + 1)); for I in Cloud'First (1) .. Cloud'Last(1) - 1 loop for J in I + 1 .. Cloud'Last(1) loop if Distance (Cloud (I), Cloud (J)) < Min_Distance then Min_Distance := Distance (Cloud (I), Cloud (J)); Result := (Cloud (I), Cloud (J)); end if; end loop; end loop; return Result; end Get_Closest_Points;   Test_Cloud : constant Matrix (1 .. 10) := ( (5.0, 9.0), (9.0, 3.0), (2.0, 0.0), (8.0, 4.0), (7.0, 4.0), (9.0, 10.0), (1.0, 9.0), (8.0, 2.0), (0.0, 10.0), (9.0, 6.0)); Closest_Points : Matrix := Get_Closest_Points (Test_Cloud);   Second_Test : constant Matrix (1 .. 10) := ( (0.654682, 0.925557), (0.409382, 0.619391), (0.891663, 0.888594), (0.716629, 0.9962), (0.477721, 0.946355), (0.925092, 0.81822), (0.624291, 0.142924), (0.211332, 0.221507), (0.293786, 0.691701), (0.839186, 0.72826)); Second_Points : Matrix := Get_Closest_Points (Second_Test); begin Ada.Text_IO.Put_Line ("Closest Points:"); Ada.Text_IO.Put_Line ("P1: " & Float'Image (Closest_Points (1) (1)) & " " & Float'Image (Closest_Points (1) (2))); Ada.Text_IO.Put_Line ("P2: " & Float'Image (Closest_Points (2) (1)) & " " & Float'Image (Closest_Points (2) (2))); Ada.Text_IO.Put_Line ("Distance: " & Float'Image (Distance (Closest_Points (1), Closest_Points (2)))); Ada.Text_IO.Put_Line ("Closest Points 2:"); Ada.Text_IO.Put_Line ("P1: " & Float'Image (Second_Points (1) (1)) & " " & Float'Image (Second_Points (1) (2))); Ada.Text_IO.Put_Line ("P2: " & Float'Image (Second_Points (2) (1)) & " " & Float'Image (Second_Points (2) (2))); Ada.Text_IO.Put_Line ("Distance: " & Float'Image (Distance (Second_Points (1), Second_Points (2)))); end Closest;
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
#Dyalect
Dyalect
var xs = [] let num = 10   for n in 0..<num { xs.Add((n => () => n * n)(n)) }   for x in xs { print(x()) }
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
#EchoLisp
EchoLisp
  (define (fgen i) (lambda () (* i i))) (define fs (for/vector ((i 10)) (fgen i))) ;; vector of 10 anonymous functions ((vector-ref fs 5)) ;; calls fs[5] → 25  
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.
#Factor
Factor
USING: combinators.short-circuit formatting io kernel lists lists.lazy math math.combinatorics math.functions math.parser math.primes sequences sequences.extras ;   ! Create an ordered infinite lazy list of circular prime ! "candidates" -- the numbers 2, 3, 5 followed by numbers ! composed of only the digits 1, 3, 7, and 9.   : candidates ( -- list ) L{ "2" "3" "5" "7" } 2 lfrom [ "1379" swap selections >list ] lmap-lazy lconcat lappend ;   : circular-prime? ( str -- ? ) all-rotations { [ [ infimum ] [ first = ] bi ] [ [ string>number prime? ] all? ] } 1&& ;   : circular-primes ( -- list ) candidates [ circular-prime? ] lfilter ;   : prime-repunits ( -- list ) 7 lfrom [ 10^ 1 - 9 / prime? ] lfilter ;   "The first 19 circular primes are:" print 19 circular-primes ltake [ write bl ] leach nl nl   "The next 4 circular primes, in repunit format, are:" print 4 prime-repunits ltake [ "R(%d) " printf ] leach nl
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
#Apex
Apex
  // Create an empty list of String List<String> my_list = new List<String>(); // Create a nested list List<List<Set<Integer>>> my_list_2 = new List<List<Set<Integer>>>();  
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
#Factor
Factor
USING: math.combinatorics prettyprint ;   5 iota 3 all-combinations .
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.
#Ol
Ol
  (if (= (* 2 2) 4) (print "if-then: equal")) (if (= (* 2 2) 6) (print "if-then: non equal")) ; ==> if-then: equal  
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.)
#Squirrel
Squirrel
//this is a single line comment   #this is also a single line comment   /* this is a multi-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.)
#SSEM
SSEM
00101010010001000100100100001100
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.)
#Standard_ML
Standard ML
(* This a comment (* containing nested 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.
#ActionScript
ActionScript
package { public class MyClass {   private var myVariable:int; // Note: instance variables are usually "private"   /** * The constructor */ public function MyClass() { // creates a new instance }   /** * A method */ public function someMethod():void { this.myVariable = 1; // Note: "this." is optional // myVariable = 1; works also } } }
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.
#Ada
Ada
package My_Package is type My_Type is tagged private; procedure Some_Procedure(Item : out My_Type); function Set(Value : in Integer) return My_Type; private type My_Type is tagged record Variable : Integer := -12; end record; end My_Package;
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
#AWK
AWK
  # syntax: GAWK -f CISTERCIAN_NUMERALS.AWK [-v debug={0|1}] [-v xc=anychar] numbers 0-9999 ... # # example: GAWK -f CISTERCIAN_NUMERALS.AWK 0 1 20 300 4000 5555 6789 1995 10000 # # sorting: # PROCINFO["sorted_in"] is used by GAWK # SORTTYPE is used by Thompson Automation's TAWK # BEGIN { cistercian_init() for (i=1; i<=ARGC-1; i++) { cistercian1(ARGV[i]) } exit(0) } function cistercian1(n, i) { printf("\n%6s\n",n) if (!(n ~ /^[0-9]+$/ && length(n) <= 4)) { print("invalid") return } n = sprintf("%04d",n) cistercian2(2,1,substr(n,3,1),substr(n,4,1)) for (i=1; i<=5; i++) { # separator between upper and lower parts printf("%5s%1s%5s\n","",xc,"") } cistercian2(4,3,substr(n,1,1),substr(n,2,1)) } function cistercian2(i1,i2,n1,n2, i,L,R) { for (i=1; i<=5; i++) { L = substr(cn_arr[i1][i],n1*6+2,5) R = substr(cn_arr[i2][i],n2*6+2,5) printf("%5s%1s%5s\n",L,xc,R) } } function cistercian_init( header,i,j,LL,LR,UL,UR) { # 1-9 upper-right cn_arr[1][++UR] = ":xxxxx:  :x  : x:xxxxx: x:xxxxx: x:xxxxx:" cn_arr[1][++UR] = ":  :  : x  : x : x : x: x: x: x:" cn_arr[1][++UR] = ":  :  : x  : x  : x  : x: x: x: x:" cn_arr[1][++UR] = ":  :  : x : x  : x  : x: x: x: x:" cn_arr[1][++UR] = ":  :xxxxx: x:x  :x  : x: x:xxxxx:xxxxx:" # 10-90 upper-left cn_arr[2][++UL] = ":xxxxx:  : x:x  :xxxxx:x  :xxxxx:x  :xxxxx:" cn_arr[2][++UL] = ":  :  : x : x  : x  :x  :x  :x  :x  :" cn_arr[2][++UL] = ":  :  : x  : x  : x  :x  :x  :x  :x  :" cn_arr[2][++UL] = ":  :  : x  : x : x :x  :x  :x  :x  :" cn_arr[2][++UL] = ":  :xxxxx:x  : x: x:x  :x  :xxxxx:xxxxx:" # 100-900 lower-right cn_arr[3][++LR] = ":  :xxxxx: x:x  :x  : x: x:xxxxx:xxxxx:" cn_arr[3][++LR] = ":  :  : x : x  : x  : x: x: x: x:" cn_arr[3][++LR] = ":  :  : x  : x  : x  : x: x: x: x:" cn_arr[3][++LR] = ":  :  : x  : x : x : x: x: x: x:" cn_arr[3][++LR] = ":xxxxx:  :x  : x:xxxxx: x:xxxxx: x:xxxxx:" # 1000-9000 lower-left cn_arr[4][++LL] = ":  :xxxxx:x  : x: x:x  :x  :xxxxx:xxxxx:" cn_arr[4][++LL] = ":  :  : x  : x : x :x  :x  :x  :x  :" cn_arr[4][++LL] = ":  :  : x  : x  : x  :x  :x  :x  :x  :" cn_arr[4][++LL] = ":  :  : x : x  : x  :x  :x  :x  :x  :" cn_arr[4][++LL] = ":xxxxx:  : x:x  :xxxxx:x  :xxxxx:x  :xxxxx:" header = ":00000:11111:22222:33333:44444:55555:66666:77777:88888:99999:" PROCINFO["sorted_in"] = "@ind_str_asc" ; SORTTYPE = 1 sub(/^ +/,"",xc) xc = (xc == "") ? "x" : substr(xc,1,1) # substitution character for (i in cn_arr) { for (j in cn_arr[i]) { gsub(/x/,xc,cn_arr[i][j]) # change "x" to substitution character cn_arr[i][j] = sprintf(":%5s%s","",cn_arr[i][j]) # add zero column to table if (debug == 1) { printf("%s %2s %d.%d\n",cn_arr[i][j],substr("URULLRLL",i*2-1,2),i,j) } } } if (debug == 1) { printf("%s\n",header) } }  
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
#PHP
PHP
<?php $colors = array(array( 0, 0, 0), // black array(255, 0, 0), // red array( 0, 255, 0), // green array( 0, 0, 255), // blue array(255, 0, 255), // magenta array( 0, 255, 255), // cyan array(255, 255, 0), // yellow array(255, 255, 255)); // white   define('BARWIDTH', 640 / count($colors)); define('HEIGHT', 480);   $image = imagecreate(BARWIDTH * count($colors), HEIGHT);   foreach ($colors as $position => $color) { $color = imagecolorallocate($image, $color[0], $color[1], $color[2]); imagefilledrectangle($image, $position * BARWIDTH, 0, $position * BARWIDTH + BARWIDTH - 1, HEIGHT - 1, $color); }   header('Content-type:image/png'); imagepng($image); imagedestroy($image);
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)
#AutoHotkey
AutoHotkey
ClosestPair(points){ if (points.count() <= 3) return bruteForceClosestPair(points) split := xSplit(Points) LP := split.1 ; left points LD := ClosestPair(LP) ; recursion : left closest pair RP := split.2 ; right points RD := ClosestPair(RP) ; recursion : right closest pair minD := min(LD, RD) ; minimum of LD & RD xmin := Split.3 - minD ; strip left boundary xmax := Split.3 + minD ; strip right boundary S := strip(points, xmin, xmax) if (s.count()>=2) { SD := ClosestPair(S) ; recursion : strip closest pair return min(SD, minD) } return minD } ;--------------------------------------------------------------- strip(points, xmin, xmax){ strip:=[] for i, coord in points if (coord.1 >= xmin) && (coord.1 <= xmax) strip.push([coord.1, coord.2]) return strip } ;--------------------------------------------------------------- bruteForceClosestPair(points){ minD := [] loop, % points.count()-1{ p1 := points.RemoveAt(1) loop, % points.count(){ p2 := points[A_Index] d := dist(p1, p2) minD.push(d) } } return min(minD*) } ;--------------------------------------------------------------- dist(p1, p2){ return Sqrt((p2.1-p1.1)**2 + (p2.2-p1.2)**2) } ;--------------------------------------------------------------- xSplit(Points){ xL := [], xR := [] p := xSort(Points) Loop % Ceil(p.count()/2) xL.push(p.RemoveAt(1)) while p.count() xR.push(p.RemoveAt(1)) mid := (xL[xl.count(),1] + xR[1,1])/2 return [xL, xR, mid] } ;--------------------------------------------------------------- xSort(Points){ S := [], Res :=[] for i, coord in points S[coord.1, coord.2] := true for x, coord in S for y, v in coord res.push([x, y]) return res } ;---------------------------------------------------------------
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
#Elena
Elena
import system'routines; import extensions;   public program() { var functions := Array.allocate(10).populate:(int i => {^ i * i} );   functions.forEach:(func) { console.printLine(func()) } }
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
#Elixir
Elixir
funs = for i <- 0..9, do: (fn -> i*i end) Enum.each(funs, &IO.puts &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.
#Forth
Forth
  create 235-wheel 6 c, 4 c, 2 c, 4 c, 2 c, 4 c, 6 c, 2 c, does> swap 7 and + c@ ;   0 1 2constant init-235 \ roll 235 wheel at position 1 : next-235 over 235-wheel + swap 1+ swap ;   \ check that n is prime excepting multiples of 2, 3, 5. : sq dup * ; : wheel-prime? ( n -- f ) >r init-235 begin next-235 dup sq r@ > if rdrop 2drop true exit then r@ over mod 0= if rdrop 2drop false exit then again ;   : prime? ( n -- f ) dup 2 < if drop false exit then dup 2 mod 0= if 2 = exit then dup 3 mod 0= if 3 = exit then dup 5 mod 0= if 5 = exit then wheel-prime? ;   : log10^ ( n -- 10^[log n], log n ) dup 0<= abort" log10^: argument error." 1 0 rot begin dup 9 > while >r swap 10 * swap 1+ r> 10 / repeat drop ;   : log10 ( n -- n ) log10^ nip ;   : rotate ( n -- n ) dup log10^ drop /mod swap 10 * + ;   : prime-rotation? ( p0 p -- f ) tuck <= swap prime? and ;   : circular? ( n -- f ) \ assume n is not a multiple of 2, 3, 5 dup wheel-prime? invert if drop false exit then dup >r true over log10 0 ?do swap rotate j over prime-rotation? rot and loop nip rdrop ;   : .primes 2 . 3 . 5 . 16 init-235 \ -- count, [n1 n2] as 2,3,5 wheel begin next-235 dup circular? if dup . rot 1- -rot then third 0= until 2drop drop ;   ." The first 19 circular primes are:" cr .primes cr bye  
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
#Arturo
Arturo
; initialize array arr: ["one" 2 "three" "four"]   ; add an element to the array arr: arr ++ 5   ; print it print arr
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
#Fortran
Fortran
program Combinations use iso_fortran_env implicit none   type comb_result integer, dimension(:), allocatable :: combs end type comb_result   type(comb_result), dimension(:), pointer :: r integer :: i, j   call comb(5, 3, r) do i = 0, choose(5, 3) - 1 do j = 2, 0, -1 write(*, "(I4, ' ')", advance="no") r(i)%combs(j) end do deallocate(r(i)%combs) write(*,*) "" end do deallocate(r)   contains   function choose(n, k, err) integer :: choose integer, intent(in) :: n, k integer, optional, intent(out) :: err   integer :: imax, i, imin, ie   ie = 0 if ( (n < 0 ) .or. (k < 0 ) ) then write(ERROR_UNIT, *) "negative in choose" choose = 0 ie = 1 else if ( n < k ) then choose = 0 else if ( n == k ) then choose = 1 else imax = max(k, n-k) imin = min(k, n-k) choose = 1 do i = imax+1, n choose = choose * i end do do i = 2, imin choose = choose / i end do end if end if if ( present(err) ) err = ie end function choose   subroutine comb(n, k, co) integer, intent(in) :: n, k type(comb_result), dimension(:), pointer, intent(out) :: co   integer :: i, j, s, ix, kx, hm, t integer :: err   hm = choose(n, k, err) if ( err /= 0 ) then nullify(co) return end if   allocate(co(0:hm-1)) do i = 0, hm-1 allocate(co(i)%combs(0:k-1)) end do do i = 0, hm-1 ix = i; kx = k do s = 0, n-1 if ( kx == 0 ) exit t = choose(n-(s+1), kx-1) if ( ix < t ) then co(i)%combs(kx-1) = s kx = kx - 1 else ix = ix - t end if end do end do   end subroutine comb   end program Combinations
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.
#ooRexx
ooRexx
if arg~isa(.string) & arg~left(1) == "*" then call processArg arg
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.)
#Stata
Stata
* Line comment: must be used at the beginning of a line (does not work in Mata)   // Line comment until the end of the line   /* Multiline 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.)
#Swift
Swift
// this is a single line comment /* This a block comment /* containing nested comment */ */   ///This is a documentation comment   /** This is a documentation block 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.)
#Symsyn
Symsyn
  | This is a 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.
#Aikido
Aikido
class Circle (radius, x, y) extends Shape (x, y) implements Drawable { var myvec = new Vector (x, y)   public function draw() { // draw the circle } }
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.
#ALGOL_68
ALGOL 68
MODE MYDATA = STRUCT( INT name1 ); STRUCT( INT name2, PROC (REF MYDATA)REF MYDATA new, PROC (REF MYDATA)VOID init, PROC (REF MYDATA)VOID some method ) class my data; class my data := ( # name2 := # 2, # Class attribute #   # PROC new := # (REF MYDATA new)REF MYDATA:( (init OF class my data)(new); new ),   # PROC init := # (REF MYDATA self)VOID:( """ Constructor (Technically an initializer rather than a true 'constructor') """; name1 OF self := 0 # Instance attribute # ),   # PROC some method := # (REF MYDATA self)VOID:( """ Method """; name1 OF self := 1; name2 OF class my data := 3 ) );   # class name, invoked as a function is the constructor syntax # REF MYDATA my data = (new OF class my data)(LOC MYDATA);   MODE GENDEROPT = UNION(STRING, VOID); MODE AGEOPT = UNION(INT, VOID);   MODE MYOTHERDATA = STRUCT( STRING name, GENDEROPT gender, AGEOPT age ); STRUCT ( INT count, PROC (REF MYOTHERDATA, STRING, GENDEROPT, AGEOPT)REF MYOTHERDATA new, PROC (REF MYOTHERDATA, STRING, GENDEROPT, AGEOPT)VOID init, PROC (REF MYOTHERDATA)VOID del ) class my other data; class my other data := ( # count := # 0, # Population of "(init OF class my other data)" objects # # PROC new := # (REF MYOTHERDATA new, STRING name, GENDEROPT gender, AGEOPT age)REF MYOTHERDATA:( (init OF class my other data)(new, name, gender, age); new ),   # PROC init := # (REF MYOTHERDATA self, STRING name, GENDEROPT gender, AGEOPT age)VOID:( """ One initializer required, others are optional (with different defaults) """; count OF class my other data +:= 1; name OF self := name; gender OF self := gender; CASE gender OF self IN (VOID):gender OF self := "Male" ESAC; age OF self := age ),   # PROC del := # (REF MYOTHERDATA self)VOID:( count OF class my other data -:= 1 ) );   PROC attribute error := STRING: error char; # mend the error with the "error char" #   # Allocate the instance from HEAP # REF MYOTHERDATA person1 = (new OF class my other data)(HEAP MYOTHERDATA, "John", EMPTY, EMPTY); print (((name OF person1), ": ", (gender OF person1|(STRING gender):gender|attribute error), " ")); # "John Male" # print (((age OF person1|(INT age):age|attribute error), new line)); # Raises AttributeError exception! #   # Allocate the instance from LOC (stack) # REF MYOTHERDATA person2 = (new OF class my other data)(LOC MYOTHERDATA, "Jane", "Female", 23); print (((name OF person2), ": ", (gender OF person2|(STRING gender):gender|attribute error), " ")); print (((age OF person2|(INT age):age|attribute error), new line)) # "Jane Female 23" #
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
#C
C
#include <stdio.h>   #define GRID_SIZE 15 char canvas[GRID_SIZE][GRID_SIZE];   void initN() { int i, j; for (i = 0; i < GRID_SIZE; i++) { for (j = 0; j < GRID_SIZE; j++) { canvas[i][j] = ' '; } canvas[i][5] = 'x'; } }   void horizontal(size_t c1, size_t c2, size_t r) { size_t c; for (c = c1; c <= c2; c++) { canvas[r][c] = 'x'; } }   void vertical(size_t r1, size_t r2, size_t c) { size_t r; for (r = r1; r <= r2; r++) { canvas[r][c] = 'x'; } }   void diagd(size_t c1, size_t c2, size_t r) { size_t c; for (c = c1; c <= c2; c++) { canvas[r + c - c1][c] = 'x'; } }   void diagu(size_t c1, size_t c2, size_t r) { size_t c; for (c = c1; c <= c2; c++) { canvas[r - c + c1][c] = 'x'; } }   void drawOnes(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: drawOnes(1); drawOnes(4); break; case 6: vertical(0, 4, 10); break; case 7: drawOnes(1); drawOnes(6); break; case 8: drawOnes(2); drawOnes(6); break; case 9: drawOnes(1); drawOnes(8); break; default: break; } }   void drawTens(int v) { switch (v) { case 1: horizontal(0, 4, 0); break; case 2: horizontal(0, 4, 4); break; case 3: diagu(0, 4, 4); break; case 4: diagd(0, 4, 0); break; case 5: drawTens(1); drawTens(4); break; case 6: vertical(0, 4, 0); break; case 7: drawTens(1); drawTens(6); break; case 8: drawTens(2); drawTens(6); break; case 9: drawTens(1); drawTens(8); break; default: break; } }   void drawHundreds(int hundreds) { switch (hundreds) { case 1: horizontal(6, 10, 14); break; case 2: horizontal(6, 10, 10); break; case 3: diagu(6, 10, 14); break; case 4: diagd(6, 10, 10); break; case 5: drawHundreds(1); drawHundreds(4); break; case 6: vertical(10, 14, 10); break; case 7: drawHundreds(1); drawHundreds(6); break; case 8: drawHundreds(2); drawHundreds(6); break; case 9: drawHundreds(1); drawHundreds(8); break; default: break; } }   void drawThousands(int thousands) { switch (thousands) { case 1: horizontal(0, 4, 14); break; case 2: horizontal(0, 4, 10); break; case 3: diagd(0, 4, 10); break; case 4: diagu(0, 4, 14); break; case 5: drawThousands(1); drawThousands(4); break; case 6: vertical(10, 14, 0); break; case 7: drawThousands(1); drawThousands(6); break; case 8: drawThousands(2); drawThousands(6); break; case 9: drawThousands(1); drawThousands(8); break; default: break; } }   void draw(int v) { int thousands = v / 1000; v %= 1000;   int hundreds = v / 100; v %= 100;   int tens = v / 10; int ones = v % 10;   if (thousands > 0) { drawThousands(thousands); } if (hundreds > 0) { drawHundreds(hundreds); } if (tens > 0) { drawTens(tens); } if (ones > 0) { drawOnes(ones); } }   void write(FILE *out) { int i; for (i = 0; i < GRID_SIZE; i++) { fprintf(out, "%-.*s", GRID_SIZE, canvas[i]); putc('\n', out); } }   void test(int n) { printf("%d:\n", n); initN(); draw(n); write(stdout); printf("\n\n"); }   int main() { test(0); test(1); test(20); test(300); test(4000); test(5555); test(6789); test(9999);   return 0; }
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
#PicoLisp
PicoLisp
(call 'clear)   (let Width (in '(tput cols) (read)) (do (in '(tput lines) (read)) (for B (range 0 7) (call 'tput 'setab B) (space (/ Width 8)) ) (prinl) ) )   (call '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
#Plain_English
Plain English
To run: Start up. Clear the screen. Divide the screen width by 8 giving a bar width. Make a bar with 0 and 0 and the bar width and the screen's bottom. Draw the color bars using the bar. Refresh the screen. Wait for the escape key. Shut down.   To divide the screen width by a number giving a width: Put the screen's right into the width. Divide the width by the number.   A bar is a box.   To draw a bar using a color and move it over: Draw and fill the bar with the color. Move the bar right the bar's width.   To draw the color bars using a bar: Draw the bar using the black color and move it over. Draw the bar using the red color and move it over. Draw the bar using the green color and move it over. Draw the bar using the blue color and move it over. Draw the bar using the magenta color and move it over. Draw the bar using the cyan color and move it over. Draw the bar using the yellow color and move it over. Draw and fill the bar using the white color.
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
#PowerShell
PowerShell
  [string[]]$colors = "Black" , "DarkBlue" , "DarkGreen" , "DarkCyan", "DarkRed" , "DarkMagenta", "DarkYellow", "Gray", "DarkGray", "Blue" , "Green" , "Cyan", "Red" , "Magenta" , "Yellow" , "White"   for ($i = 0; $i -lt 64; $i++) { for ($j = 0; $j -lt $colors.Count; $j++) { Write-Host (" " * 12) -BackgroundColor $colors[$j] -NoNewline }   Write-Host }  
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)
#AWK
AWK
  # syntax: GAWK -f CLOSEST-PAIR_PROBLEM.AWK BEGIN { x[++n] = 0.654682 ; y[n] = 0.925557 x[++n] = 0.409382 ; y[n] = 0.619391 x[++n] = 0.891663 ; y[n] = 0.888594 x[++n] = 0.716629 ; y[n] = 0.996200 x[++n] = 0.477721 ; y[n] = 0.946355 x[++n] = 0.925092 ; y[n] = 0.818220 x[++n] = 0.624291 ; y[n] = 0.142924 x[++n] = 0.211332 ; y[n] = 0.221507 x[++n] = 0.293786 ; y[n] = 0.691701 x[++n] = 0.839186 ; y[n] = 0.728260 min = 1E20 for (i=1; i<=n-1; i++) { for (j=i+1; j<=n; j++) { dsq = (x[i]-x[j])^2 + (y[i]-y[j])^2 if (dsq < min) { min = dsq mini = i minj = j } } } printf("distance between (%.6f,%.6f) and (%.6f,%.6f) is %g\n",x[mini],y[mini],x[minj],y[minj],sqrt(min)) exit(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
#Emacs_Lisp
Emacs Lisp
;; -*- lexical-binding: t; -*- (mapcar #'funcall (mapcar (lambda (x) (lambda () (* x x))) '(1 2 3 4 5 6 7 8 9 10))) ;; => (1 4 9 16 25 36 49 64 81 100)
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
#Erlang
Erlang
  -module(capture_demo). -export([demo/0]).   demo() -> Funs = lists:map(fun (X) -> fun () -> X * X end end, lists:seq(1,10)), lists:foreach(fun (F) -> io:fwrite("~B~n",[F()]) end, Funs).  
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.
#FreeBASIC
FreeBASIC
#define floor(x) ((x*2.0-0.5)Shr 1)   Function isPrime(Byval p As Integer) As Boolean If p < 2 Then Return False If p Mod 2 = 0 Then Return p = 2 If p Mod 3 = 0 Then Return p = 3 Dim As Integer d = 5 While d * d <= p If p Mod d = 0 Then Return False Else d += 2 If p Mod d = 0 Then Return False Else d += 4 Wend Return True End Function   Function isCircularPrime(Byval p As Integer) As Boolean Dim As Integer n = floor(Log(p)/Log(10)) Dim As Integer m = 10^n, q = p For i As Integer = 0 To n If (q < p Or Not isPrime(q)) Then Return false q = (q Mod m) * 10 + floor(q / m) Next i Return true End Function   Dim As Integer p = 2, dp = 1, cont = 0 Print("Primeros 19 primos circulares:") While cont < 19 If isCircularPrime(p) Then Print p;" "; : cont += 1 p += dp: dp = 2 Wend Sleep
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
#AutoHotkey
AutoHotkey
myCol := Object() mycol.mykey := "my value!" mycol["mykey"] := "new val!" MsgBox % mycol.mykey ; new val
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
#FreeBASIC
FreeBASIC
sub iterate( byval curr as string, byval start as uinteger,_ byval stp as uinteger, byval depth as uinteger ) dim as uinteger i for i = start to stp if depth = 0 then print curr + " " + str(i) end if iterate( curr+" "+str(i), i+1, stp, depth-1 ) next i return end sub   dim as uinteger m, n input "Enter n comb m. ", n, m dim as string outstr = "" iterate outstr, 0, m-1, n-1
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.
#OxygenBasic
OxygenBasic
  if a then b=c else b=d   if a=0 b=c elseif a<0 b=d else b=e end if   select case a case 'A' v=21 case 'B' v=22 case 1 to 64 v=a+300 case else v=0 end select    
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.)
#Tcl
Tcl
# comment on a line by itself. The next is a command by itself: set var1 $value1 set var2 $value2 ; # comment that follows a line of code
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.)
#Tern
Tern
:"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.)
#TI-83_BASIC
TI-83 BASIC
:"THIS IS A 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.
#AmigaE
AmigaE
OBJECT a_class varA, varP ENDOBJECT   -> this could be used like a constructor PROC init() OF a_class self.varP := 10 self.varA := 2 ENDPROC   -> the special proc end() is for destructor PROC end() OF a_class -> nothing to do here... ENDPROC   -> a not so useful getter PROC getP() OF a_class IS self.varP   PROC main() DEF obj : PTR TO a_class NEW obj.init() WriteF('\d\n', obj.varA) -> this can be done, while -> varP can't be accessed directly WriteF('\d\n', obj.varP) -> or WriteF('\d\n', obj.getP()) END obj ENDPROC
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.
#AutoHotkey
AutoHotkey
obj := new MyClass obj.WhenCreated()   class MyClass { ; Instance Variable #1 time := A_Hour ":" A_Min ":" A_Sec   ; Constructor __New() { MsgBox, % "Constructing new object of type: " this.__Class FormatTime, date, , MM/dd/yyyy ; Instance Variable #2 this.date := date } ; Method WhenCreated() { MsgBox, % "Object created at " this.time " on " this.date } }
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
#C.2B.2B
C++
#include <array> #include <iostream>   template<typename T, size_t S> using FixedSquareGrid = std::array<std::array<T, S>, S>;   struct Cistercian { public: Cistercian() { initN(); }   Cistercian(int v) { initN(); draw(v); }   Cistercian &operator=(int v) { initN(); draw(v); }   friend std::ostream &operator<<(std::ostream &, const Cistercian &);   private: FixedSquareGrid<char, 15> canvas;   void initN() { for (auto &row : canvas) { row.fill(' '); row[5] = 'x'; } }   void horizontal(size_t c1, size_t c2, size_t r) { for (size_t c = c1; c <= c2; c++) { canvas[r][c] = 'x'; } }   void vertical(size_t r1, size_t r2, size_t c) { for (size_t r = r1; r <= r2; r++) { canvas[r][c] = 'x'; } }   void diagd(size_t c1, size_t c2, size_t r) { for (size_t c = c1; c <= c2; c++) { canvas[r + c - c1][c] = 'x'; } }   void diagu(size_t c1, size_t c2, size_t r) { for (size_t c = c1; c <= c2; c++) { canvas[r - c + c1][c] = 'x'; } }   void drawOnes(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: drawOnes(1); drawOnes(4); break; case 6: vertical(0, 4, 10); break; case 7: drawOnes(1); drawOnes(6); break; case 8: drawOnes(2); drawOnes(6); break; case 9: drawOnes(1); drawOnes(8); break; default: break; } }   void drawTens(int v) { switch (v) { case 1: horizontal(0, 4, 0); break; case 2: horizontal(0, 4, 4); break; case 3: diagu(0, 4, 4); break; case 4: diagd(0, 4, 0); break; case 5: drawTens(1); drawTens(4); break; case 6: vertical(0, 4, 0); break; case 7: drawTens(1); drawTens(6); break; case 8: drawTens(2); drawTens(6); break; case 9: drawTens(1); drawTens(8); break; default: break; } }   void drawHundreds(int hundreds) { switch (hundreds) { case 1: horizontal(6, 10, 14); break; case 2: horizontal(6, 10, 10); break; case 3: diagu(6, 10, 14); break; case 4: diagd(6, 10, 10); break; case 5: drawHundreds(1); drawHundreds(4); break; case 6: vertical(10, 14, 10); break; case 7: drawHundreds(1); drawHundreds(6); break; case 8: drawHundreds(2); drawHundreds(6); break; case 9: drawHundreds(1); drawHundreds(8); break; default: break; } }   void drawThousands(int thousands) { switch (thousands) { case 1: horizontal(0, 4, 14); break; case 2: horizontal(0, 4, 10); break; case 3: diagd(0, 4, 10); break; case 4: diagu(0, 4, 14); break; case 5: drawThousands(1); drawThousands(4); break; case 6: vertical(10, 14, 0); break; case 7: drawThousands(1); drawThousands(6); break; case 8: drawThousands(2); drawThousands(6); break; case 9: drawThousands(1); drawThousands(8); break; default: break; } }   void draw(int v) { int thousands = v / 1000; v %= 1000;   int hundreds = v / 100; v %= 100;   int tens = v / 10; int ones = v % 10;   if (thousands > 0) { drawThousands(thousands); } if (hundreds > 0) { drawHundreds(hundreds); } if (tens > 0) { drawTens(tens); } if (ones > 0) { drawOnes(ones); } } };   std::ostream &operator<<(std::ostream &os, const Cistercian &c) { for (auto &row : c.canvas) { for (auto cell : row) { os << cell; } os << '\n'; } return os; }   int main() { for (auto number : { 0, 1, 20, 300, 4000, 5555, 6789, 9999 }) { std::cout << number << ":\n";   Cistercian c(number); std::cout << c << '\n'; }   return 0; }
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
#Processing
Processing
fullScreen(); noStroke(); color[] cs = { color(0), // black color(255,0,0), // red color(0,255,0), // green color(255,0,255), // magenta color(0,255,255), // cyan color(255,255,0), // yellow color(255) // white }; for(int i=0; i<7; i++) { fill(cs[i]); rect(i*width/8,0,width/8,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
#Python
Python
  #!/usr/bin/env python #vertical coloured stripes in window in Python 2.7.1   from livewires import *   horiz=640; vert=480 begin_graphics(width=horiz,height=vert,title="v_stripes",background=Colour.black) NameColors=["black","red","green","dark_blue","purple","blue","yellow","white"] stepik=horiz/len(NameColors)   for index,each in enumerate(NameColors): ExcStrng="set_colour(Colour."+each+")" exec ExcStrng box(index*stepik,0,(index+1)*stepik,vert,filled=1)   while keys_pressed() != ['x']: # press x key to terminate program pass   end_graphics()  
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)
#BASIC256
BASIC256
  Dim x(9) x = {0.654682, 0.409382, 0.891663, 0.716629, 0.477721, 0.925092, 0.624291, 0.211332, 0.293786, 0.839186} Dim y(9) y = {0.925557, 0.619391, 0.888594, 0.996200, 0.946355, 0.818220, 0.142924, 0.221507, 0.691701, 0.728260}   minDist = 1^30 For i = 0 To 8 For j = i+1 To 9 dist = (x[i] - x[j])^2 + (y[i] - y[j])^2 If dist < minDist Then minDist = dist : minDisti = i : minDistj = j Next j Next i Print "El par más cercano es "; minDisti; " y "; minDistj; " a una distancia de "; Sqr(minDist) End  
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
#F.23
F#
[<EntryPoint>] let main argv = let fs = List.init 10 (fun i -> fun () -> i*i) do List.iter (fun f -> printfn "%d" <| f()) fs 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
#Factor
Factor
USING: io kernel locals math prettyprint sequences ;   [let  ! Create a sequence of 10 quotations 10 iota [  :> i  ! Bind lexical variable i [ i i * ]  ! Push a quotation to calculate i squared ] map :> seq   { 3 8 } [ dup pprint " squared is " write seq nth call . ] each ]
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.
#Go
Go
package main   import ( "fmt" big "github.com/ncw/gmp" "strings" )   // OK for 'small' numbers. func isPrime(n int) bool { switch { case n < 2: return false case n%2 == 0: return n == 2 case n%3 == 0: return n == 3 default: d := 5 for d*d <= n { if n%d == 0 { return false } d += 2 if n%d == 0 { return false } d += 4 } return true } }   func repunit(n int) *big.Int { ones := strings.Repeat("1", n) b, _ := new(big.Int).SetString(ones, 10) return b }   var circs = []int{}   // binary search is overkill for a small number of elements func alreadyFound(n int) bool { for _, i := range circs { if i == n { return true } } return false }   func isCircular(n int) bool { nn := n pow := 1 // will eventually contain 10 ^ d where d is number of digits in n for nn > 0 { pow *= 10 nn /= 10 } nn = n for { nn *= 10 f := nn / pow // first digit nn += f * (1 - pow) if alreadyFound(nn) { return false } if nn == n { break } if !isPrime(nn) { return false } } return true }   func main() { fmt.Println("The first 19 circular primes are:") digits := [4]int{1, 3, 7, 9} q := []int{1, 2, 3, 5, 7, 9} // queue the numbers to be examined fq := []int{1, 2, 3, 5, 7, 9} // also queue the corresponding first digits count := 0 for { f := q[0] // peek first element fd := fq[0] // peek first digit if isPrime(f) && isCircular(f) { circs = append(circs, f) count++ if count == 19 { break } } copy(q, q[1:]) // pop first element q = q[:len(q)-1] // reduce length by 1 copy(fq, fq[1:]) // ditto for first digit queue fq = fq[:len(fq)-1] if f == 2 || f == 5 { // if digits > 1 can't contain a 2 or 5 continue } // add numbers with one more digit to queue // only numbers whose last digit >= first digit need be added for _, d := range digits { if d >= fd { q = append(q, f*10+d) fq = append(fq, fd) } } } fmt.Println(circs) fmt.Println("\nThe next 4 circular primes, in repunit format, are:") count = 0 var rus []string for i := 7; count < 4; i++ { if repunit(i).ProbablyPrime(10) { count++ rus = append(rus, fmt.Sprintf("R(%d)", i)) } } fmt.Println(rus) fmt.Println("\nThe following repunits are probably circular primes:") for _, i := range []int{5003, 9887, 15073, 25031, 35317, 49081} { fmt.Printf("R(%-5d) : %t\n", i, repunit(i).ProbablyPrime(10)) } }
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
#AWK
AWK
a[0]="hello"
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
#GAP
GAP
# Built-in Combinations([1 .. n], m);   Combinations([1 .. 5], 3); # [ [ 1, 2, 3 ], [ 1, 2, 4 ], [ 1, 2, 5 ], [ 1, 3, 4 ], [ 1, 3, 5 ], # [ 1, 4, 5 ], [ 2, 3, 4 ], [ 2, 3, 5 ], [ 2, 4, 5 ], [ 3, 4, 5 ] ]
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.
#Oz
Oz
proc {PrintParity X} if {IsEven X} then {Show even} elseif {IsOdd X} then {Show odd} else {Show 'should not happen'} end 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.)
#TI-89_BASIC
TI-89 BASIC
© This is a comment. Everything from © to the end of the line is ignored.
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.)
#Tiny_BASIC
Tiny BASIC
  10 REM this is a comment 20   40 REM from above you can see that line numbers with no statement 50 REM and blank lines also are ignored  
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.)
#Toka
Toka
#! Everything on this line (after the shebang to the left) will be ignored.