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/Cholesky_decomposition
Cholesky decomposition
Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interpreted as a generalized square root of A {\displaystyle A} , as described in Cholesky decomposition. In a 3x3 example, we have to solve the following system of equations: A = ( a 11 a 21 a 31 a 21 a 22 a 32 a 31 a 32 a 33 ) = ( l 11 0 0 l 21 l 22 0 l 31 l 32 l 33 ) ( l 11 l 21 l 31 0 l 22 l 32 0 0 l 33 ) ≡ L L T = ( l 11 2 l 21 l 11 l 31 l 11 l 21 l 11 l 21 2 + l 22 2 l 31 l 21 + l 32 l 22 l 31 l 11 l 31 l 21 + l 32 l 22 l 31 2 + l 32 2 + l 33 2 ) {\displaystyle {\begin{aligned}A&={\begin{pmatrix}a_{11}&a_{21}&a_{31}\\a_{21}&a_{22}&a_{32}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}\\&={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}l_{11}&l_{21}&l_{31}\\0&l_{22}&l_{32}\\0&0&l_{33}\end{pmatrix}}\equiv LL^{T}\\&={\begin{pmatrix}l_{11}^{2}&l_{21}l_{11}&l_{31}l_{11}\\l_{21}l_{11}&l_{21}^{2}+l_{22}^{2}&l_{31}l_{21}+l_{32}l_{22}\\l_{31}l_{11}&l_{31}l_{21}+l_{32}l_{22}&l_{31}^{2}+l_{32}^{2}+l_{33}^{2}\end{pmatrix}}\end{aligned}}} We can see that for the diagonal elements ( l k k {\displaystyle l_{kk}} ) of L {\displaystyle L} there is a calculation pattern: l 11 = a 11 {\displaystyle l_{11}={\sqrt {a_{11}}}} l 22 = a 22 − l 21 2 {\displaystyle l_{22}={\sqrt {a_{22}-l_{21}^{2}}}} l 33 = a 33 − ( l 31 2 + l 32 2 ) {\displaystyle l_{33}={\sqrt {a_{33}-(l_{31}^{2}+l_{32}^{2})}}} or in general: l k k = a k k − ∑ j = 1 k − 1 l k j 2 {\displaystyle l_{kk}={\sqrt {a_{kk}-\sum _{j=1}^{k-1}l_{kj}^{2}}}} For the elements below the diagonal ( l i k {\displaystyle l_{ik}} , where i > k {\displaystyle i>k} ) there is also a calculation pattern: l 21 = 1 l 11 a 21 {\displaystyle l_{21}={\frac {1}{l_{11}}}a_{21}} l 31 = 1 l 11 a 31 {\displaystyle l_{31}={\frac {1}{l_{11}}}a_{31}} l 32 = 1 l 22 ( a 32 − l 31 l 21 ) {\displaystyle l_{32}={\frac {1}{l_{22}}}(a_{32}-l_{31}l_{21})} which can also be expressed in a general formula: l i k = 1 l k k ( a i k − ∑ j = 1 k − 1 l i j l k j ) {\displaystyle l_{ik}={\frac {1}{l_{kk}}}\left(a_{ik}-\sum _{j=1}^{k-1}l_{ij}l_{kj}\right)} Task description The task is to implement a routine which will return a lower Cholesky factor L {\displaystyle L} for every given symmetric, positive definite nxn matrix A {\displaystyle A} . You should then test it on the following two examples and include your output. Example 1: 25 15 -5 5 0 0 15 18 0 --> 3 3 0 -5 0 11 -1 1 3 Example 2: 18 22 54 42 4.24264 0.00000 0.00000 0.00000 22 70 86 62 --> 5.18545 6.56591 0.00000 0.00000 54 86 174 134 12.72792 3.04604 1.64974 0.00000 42 62 134 106 9.89949 1.62455 1.84971 1.39262 Note The Cholesky decomposition of a Pascal upper-triangle matrix is the Identity matrix of the same size. The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
CholeskyDecomposition[{{25, 15, -5}, {15, 18, 0}, {-5, 0, 11}}]
http://rosettacode.org/wiki/Cheryl%27s_birthday
Cheryl's birthday
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the   month   of birth,   and Bernard the   day   (of the month)   of birth. 1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too. 2) Bernard: At first I don't know when Cheryl's birthday is, but I know now. 3) Albert: Then I also know when Cheryl's birthday is. Task Write a computer program to deduce, by successive elimination, Cheryl's birthday. Related task Sum and Product Puzzle References Wikipedia article of the same name. Tuple Relational Calculus
#Perl
Perl
sub filter { my($test,@dates) = @_; my(%M,%D,@filtered);   # analysis of potential birthdays, keyed by month and by day for my $date (@dates) { my($mon,$day) = split '-', $date; $M{$mon}{cnt}++; $D{$day}{cnt}++; push @{$M{$mon}{day}}, $day; push @{$D{$day}{mon}}, $mon; push @{$M{$mon}{bday}}, "$mon-$day"; push @{$D{$day}{bday}}, "$mon-$day"; }   # eliminates May/Jun dates based on 18th and 19th being singletons if ($test eq 'singleton') { my %skip; for my $day (grep { $D{$_}{cnt} == 1 } keys %D) { $skip{ @{$D{$day}{mon}}[0] }++ } for my $mon (grep { ! $skip{$_} } keys %M) { push @filtered, @{$M{$mon}{bday}} }   # eliminates Jul/Aug 14th because day count > 1 across months } elsif ($test eq 'duplicate') { for my $day (grep { $D{$_}{cnt} == 1 } keys %D) { push @filtered, @{$D{$day}{bday}} }   # eliminates Aug 15th/17th because day count > 1, within month } elsif ($test eq 'multiple') { for my $day (grep { $M{$_}{cnt} == 1 } keys %M) { push @filtered, @{$M{$day}{bday}} } } return @filtered; }   # doesn't matter what order singleton/duplicate tests are run, but 'multiple' must be last; my @dates = qw<5-15 5-16 5-19 6-17 6-18 7-14 7-16 8-14 8-15 8-17>; @dates = filter($_, @dates) for qw<singleton duplicate multiple>;   my @months = qw<_ January February March April May June July August September October November December>;   my ($m, $d) = split '-', $dates[0]; print "Cheryl's birthday is $months[$m] $d.\n";
http://rosettacode.org/wiki/Checkpoint_synchronization
Checkpoint synchronization
The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before starting another one. Putting details together is the checkpoint at which tasks synchronize themselves before going their paths apart. The task Implement checkpoint synchronization in your language. Make sure that the solution is race condition-free. Note that a straightforward solution based on events is exposed to race condition. Let two tasks A and B need to be synchronized at a checkpoint. Each signals its event (EA and EB correspondingly), then waits for the AND-combination of the events (EA&EB) and resets its event. Consider the following scenario: A signals EA first and gets blocked waiting for EA&EB. Then B signals EB and loses the processor. Then A is released (both events are signaled) and resets EA. Now if B returns and enters waiting for EA&EB, it gets lost. When a worker is ready it shall not continue before others finish. A typical implementation bug is when a worker is counted twice within one working cycle causing its premature completion. This happens when the quickest worker serves its cycle two times while the laziest one is lagging behind. If you can, implement workers joining and leaving.
#zkl
zkl
const NUM_PARTS=5; // number of parts used to make the product var requested=Atomic.Int(-1); // the id of the part the consumer needs var pipe=Thread.Pipe(); // "conveyor belt" of parts to consumer   fcn producer(id,pipe){ while(True){ // make part forever requested.waitFor(id); // wait for consumer to ask for my part requested.set(-1); // I'm making the part pipe.write(id); // ship my part } println(id," stopped"); }   foreach id in (NUM_PARTS){ producer.launch(id,pipe) } // start workers/threads   product:=NUM_PARTS.pump(List(),0); // parts I have on hand do(10){ // make 10 products while(False!=(id:=product.filter1n('==(0)))){ // gather parts to make product requested.set(id); part:=pipe.read(); // get requested part product[part]+=1; // assemble part into product } println("product made: ",product); foreach n in (NUM_PARTS){ product[n]-=1 } // remove parts from bin } println("Done"); // but workers are still waiting
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
#Lua
Lua
collection = {0, '1'} print(collection[1]) -- prints 0   collection = {["foo"] = 0, ["bar"] = '1'} -- a collection of key/value pairs print(collection["foo"]) -- prints 0 print(collection.foo) -- syntactic sugar, also prints 0   collection = {0, '1', ["foo"] = 0, ["bar"] = '1'}
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
#PHP
PHP
  <?php   $a=array(1,2,3,4,5); $k=3; $n=5; $c=array_splice($a, $k); $b=array_splice($a, 0, $k); $j=$k-1; print_r($b);   while (1) {   $m=array_search($b[$j]+1,$c); if ($m!==false) { $c[$m]-=1; $b[$j]=$b[$j]+1; print_r($b); } if ($b[$k-1]==$n) { $i=$k-1; while ($i >= 0) {   if ($i == 0 && $b[$i] == $n-$k+1) break 2;   $m=array_search($b[$i]+1,$c); if ($m!==false) { $c[$m]=$c[$m]-1; $b[$i]=$b[$i]+1;   $g=$i; while ($g != $k-1) { array_unshift ($c, $b[$g+1]); $b[$g+1]=$b[$g]+1; $g++; } $c=array_diff($c,$b); print_r($b); break; } $i--;   }   }     }   ?>  
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.
#Seed7
Seed7
if condition then statement end if;   if condition then statement1 else statement2; end if;   if condition1 then statement1 elsif condition2 then statement2; end if;   if condition1 then statement1 elsif condition2 then statement2; else statement3; end if;
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 {\displaystyle a_{2}} ,   … {\displaystyle \dots } ,   a k {\displaystyle a_{k}} ,   there exists an integer   x {\displaystyle x}   solving the following system of simultaneous congruences: x ≡ a 1 ( mod n 1 ) x ≡ a 2 ( mod n 2 )     ⋮ x ≡ a k ( mod n k ) {\displaystyle {\begin{aligned}x&\equiv a_{1}{\pmod {n_{1}}}\\x&\equiv a_{2}{\pmod {n_{2}}}\\&{}\ \ \vdots \\x&\equiv a_{k}{\pmod {n_{k}}}\end{aligned}}} Furthermore, all solutions   x {\displaystyle x}   of this system are congruent modulo the product,   N = n 1 n 2 … n k {\displaystyle N=n_{1}n_{2}\ldots n_{k}} . Task Write a program to solve a system of linear congruences by applying the   Chinese Remainder Theorem. If the system of equations cannot be solved, your program must somehow indicate this. (It may throw an exception or return a special false value.) Since there are infinitely many solutions, the program should return the unique solution   s {\displaystyle s}   where   0 ≤ s ≤ n 1 n 2 … n k {\displaystyle 0\leq s\leq n_{1}n_{2}\ldots n_{k}} . Show the functionality of this program by printing the result such that the   n {\displaystyle n} 's   are   [ 3 , 5 , 7 ] {\displaystyle [3,5,7]}   and the   a {\displaystyle a} 's   are   [ 2 , 3 , 2 ] {\displaystyle [2,3,2]} . Algorithm:   The following algorithm only applies if the   n i {\displaystyle n_{i}} 's   are pairwise co-prime. Suppose, as above, that a solution is required for the system of congruences: x ≡ a i ( mod n i ) f o r i = 1 , … , k {\displaystyle x\equiv a_{i}{\pmod {n_{i}}}\quad \mathrm {for} \;i=1,\ldots ,k} Again, to begin, the product   N = n 1 n 2 … n k {\displaystyle N=n_{1}n_{2}\ldots n_{k}}   is defined. Then a solution   x {\displaystyle x}   can be found as follows: For each   i {\displaystyle i} ,   the integers   n i {\displaystyle n_{i}}   and   N / n i {\displaystyle N/n_{i}}   are co-prime. Using the   Extended Euclidean algorithm,   we can find integers   r i {\displaystyle r_{i}}   and   s i {\displaystyle s_{i}}   such that   r i n i + s i N / n i = 1 {\displaystyle r_{i}n_{i}+s_{i}N/n_{i}=1} . Then, one solution to the system of simultaneous congruences is: x = ∑ i = 1 k a i s i N / n i {\displaystyle x=\sum _{i=1}^{k}a_{i}s_{i}N/n_{i}} and the minimal solution, x ( mod N ) {\displaystyle x{\pmod {N}}} .
#JavaScript
JavaScript
  function crt(num, rem) { let sum = 0; const prod = num.reduce((a, c) => a * c, 1);   for (let i = 0; i < num.length; i++) { const [ni, ri] = [num[i], rem[i]]; const p = Math.floor(prod / ni); sum += ri * p * mulInv(p, ni); } return sum % prod; }   function mulInv(a, b) { const b0 = b; let [x0, x1] = [0, 1];   if (b === 1) { return 1; } while (a > 1) { const q = Math.floor(a / b); [a, b] = [b, a % b]; [x0, x1] = [x1 - q * x0, x0]; } if (x1 < 0) { x1 += b0; } return x1; }   console.log(crt([3,5,7], [2,3,2]))
http://rosettacode.org/wiki/Chowla_numbers
Chowla numbers
Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n   is a positive integer The sequence is named after   Sarvadaman D. S. Chowla,   (22 October 1907 ──► 10 December 1995), a London born Indian American mathematician specializing in number theory. German mathematician Carl Friedrich Gauss (1777─1855) said: "Mathematics is the queen of the sciences ─ and number theory is the queen of mathematics". Definitions Chowla numbers can also be expressed as: chowla(n) = sum of divisors of n excluding unity and n chowla(n) = sum( divisors(n)) - 1 - n chowla(n) = sum( properDivisors(n)) - 1 chowla(n) = sum(aliquotDivisors(n)) - 1 chowla(n) = aliquot(n) - 1 chowla(n) = sigma(n) - 1 - n chowla(n) = sigmaProperDivisiors(n) - 1   chowla(a*b) = a + b,   if a and b are distinct primes if chowla(n) = 0,  and n > 1, then n is prime if chowla(n) = n - 1, and n > 1, then n is a perfect number Task   create a   chowla   function that returns the   chowla number   for a positive integer   n   Find and display   (1 per line)   for the 1st   37   integers:   the integer   (the index)   the chowla number for that integer   For finding primes, use the   chowla   function to find values of zero   Find and display the   count   of the primes up to              100   Find and display the   count   of the primes up to           1,000   Find and display the   count   of the primes up to         10,000   Find and display the   count   of the primes up to       100,000   Find and display the   count   of the primes up to    1,000,000   Find and display the   count   of the primes up to  10,000,000   For finding perfect numbers, use the   chowla   function to find values of   n - 1   Find and display all   perfect numbers   up to   35,000,000   use commas within appropriate numbers   show all output here Related tasks   totient function   perfect numbers   Proper divisors   Sieve of Eratosthenes See also   the OEIS entry for   A48050 Chowla's function.
#REXX
REXX
/*REXX program computes/displays chowla numbers (and may count primes & perfect numbers.*/ parse arg LO HI . /*obtain optional arguments from the CL*/ if LO=='' | LO=="," then LO= 1 /*Not specified? Then use the default.*/ perf= LO<0; LO= abs(LO) /*Negative? Then determine if perfect.*/ if HI=='' | HI=="," then HI= LO /*Not specified? Then use the default.*/ prim= HI<0; HI= abs(HI) /*Negative? Then determine if a prime.*/ numeric digits max(9, length(HI) + 1 ) /*use enough decimal digits for // */ w= length( commas(HI) ) /*W: used in aligning output numbers.*/ tell= \(prim | perf) /*set boolean value for showing chowlas*/ p= 0 /*the number of primes found (so far).*/ do j=LO to HI; #= chowla(j) /*compute the cholwa number for J. */ if tell then say right('chowla('commas(j)")", w+9) ' = ' right( commas(#), w) else if #==0 then if j>1 then p= p+1 if perf then if j-1==# & j>1 then say right(commas(j), w) ' is a perfect number.' end /*j*/   if prim & \perf then say 'number of primes found for the range ' commas(LO) " to " , commas(HI) " (inclusive) is: " commas(p) exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ chowla: procedure; parse arg x; if x<2 then return 0; odd= x // 2 s=0 /* [↓] use EVEN or ODD integers. ___*/ do k=2+odd by 1+odd while k*k<x /*divide by all the integers up to √ X */ if x//k==0 then s=s + k + x%k /*add the two divisors to the sum. */ end /*k*/ /* [↓] adkust for square. ___*/ if k*k==x then s=s + k /*Was X a square? If so, add √ X */ return s /*return " " " " " */ /*──────────────────────────────────────────────────────────────────────────────────────*/ commas: parse arg _; do k=length(_)-3 to 1 by -3; _= insert(',', _, k); end; return _
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.
#MiniScript
MiniScript
// MiniScript is prototype based Weapon = { "name": "Sword", "damage": 3 } Weapon.slice = function() print "Did " + self.damage + " damage with " + self.name end function   wep = new Weapon // Same as: wep = { "__isa": Weapon }   wep.name = "Lance"   wep.slice
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)
#Pascal
Pascal
program closestPoints; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} const PointCnt = 10000;//31623; type TdblPoint = Record ptX, ptY : double; end; tPtLst = array of TdblPoint;   tMinDIstIdx = record md1, md2 : NativeInt; end;   function ClosPointBruteForce(var ptl :tPtLst):tMinDIstIdx; Var i,j,k : NativeInt; mindst2,dst2: double; //square of distance, no need to sqrt p0,p1 : ^TdblPoint; //using pointer, since calc of ptl[?] takes much time Begin i := Low(ptl); j := High(ptl); result.md1 := i;result.md2 := j; mindst2 := sqr(ptl[i].ptX-ptl[j].ptX)+sqr(ptl[i].ptY-ptl[j].ptY); repeat p0 := @ptl[i]; p1 := p0; inc(p1); For k := i+1 to j do Begin dst2:= sqr(p0^.ptX-p1^.ptX)+sqr(p0^.ptY-p1^.ptY); IF mindst2 > dst2 then Begin mindst2 := dst2; result.md1 := i; result.md2 := k; end; inc(p1); end; inc(i); until i = j; end;   var PointLst :tPtLst; cloPt : tMinDIstIdx; i : NativeInt; Begin randomize; setlength(PointLst,PointCnt); For i := 0 to PointCnt-1 do with PointLst[i] do Begin ptX := random; ptY := random; end; cloPt:= ClosPointBruteForce(PointLst) ; i := cloPt.md1; Writeln('P[',i:4,']= x: ',PointLst[i].ptX:0:8, ' y: ',PointLst[i].ptY:0:8); i := cloPt.md2; Writeln('P[',i:4,']= x: ',PointLst[i].ptX:0:8, ' y: ',PointLst[i].ptY:0:8); end.
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points
Circles of given radius through two points
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. Exceptions r==0.0 should be treated as never describing circles (except in the case where the points are coincident). If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point. If the points form a diameter then return two identical circles or return a single circle, according to which is the most natural mechanism for the implementation language. If the points are too far apart then no circles can be drawn. Task detail Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, or some indication of special cases where two, possibly equal, circles cannot be returned. Show here the output for the following inputs: p1 p2 r 0.1234, 0.9876 0.8765, 0.2345 2.0 0.0000, 2.0000 0.0000, 0.0000 1.0 0.1234, 0.9876 0.1234, 0.9876 2.0 0.1234, 0.9876 0.8765, 0.2345 0.5 0.1234, 0.9876 0.1234, 0.9876 0.0 Related task   Total circles area. See also   Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
#Kotlin
Kotlin
// version 1.1.51   typealias IAE = IllegalArgumentException   class Point(val x: Double, val y: Double) { fun distanceFrom(other: Point): Double { val dx = x - other.x val dy = y - other.y return Math.sqrt(dx * dx + dy * dy ) }   override fun equals(other: Any?): Boolean { if (other == null || other !is Point) return false return (x == other.x && y == other.y) }   override fun toString() = "(%.4f, %.4f)".format(x, y) }   fun findCircles(p1: Point, p2: Point, r: Double): Pair<Point, Point> { if (r < 0.0) throw IAE("the radius can't be negative") if (r == 0.0 && p1 != p2) throw IAE("no circles can ever be drawn") if (r == 0.0) return p1 to p1 if (p1 == p2) throw IAE("an infinite number of circles can be drawn") val distance = p1.distanceFrom(p2) val diameter = 2.0 * r if (distance > diameter) throw IAE("the points are too far apart to draw a circle") val center = Point((p1.x + p2.x) / 2.0, (p1.y + p2.y) / 2.0) if (distance == diameter) return center to center val mirrorDistance = Math.sqrt(r * r - distance * distance / 4.0) val dx = (p2.x - p1.x) * mirrorDistance / distance val dy = (p2.y - p1.y) * mirrorDistance / distance return Point(center.x - dy, center.y + dx) to Point(center.x + dy, center.y - dx) }   fun main(args: Array<String>) { val p = arrayOf( Point(0.1234, 0.9876), Point(0.8765, 0.2345), Point(0.0000, 2.0000), Point(0.0000, 0.0000) ) val points = arrayOf( p[0] to p[1], p[2] to p[3], p[0] to p[0], p[0] to p[1], p[0] to p[0] ) val radii = doubleArrayOf(2.0, 1.0, 2.0, 0.5, 0.0) for (i in 0..4) { try { val (p1, p2) = points[i] val r = radii[i] println("For points $p1 and $p2 with radius $r") val (c1, c2) = findCircles(p1, p2, r) if (c1 == c2) println("there is just one circle with center at $c1") else println("there are two circles with centers at $c1 and $c2") } catch(ex: IllegalArgumentException) { println(ex.message) } println() } }
http://rosettacode.org/wiki/Chinese_zodiac
Chinese zodiac
Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Tuesday, February 1, 2022 CE (in the common Gregorian calendar) will begin the lunisolar Year of the Tiger. The celestial stems have no one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems each belong to one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element's governance is associated with yin, the other with yang. Thus, 2022 is also the yang year of Water. Note that since 12 is an even number, the association between animals and yin/yang doesn't change. Consecutive Years of the Rooster will cycle through the five elements, but will always be yin, despite the apparent conceptual mismatch between the specifically-male English animal name and the female aspect denoted by yin. Task Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year. You may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration). Requisite information The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig. The element cycle runs in this order: Wood, Fire, Earth, Metal, Water. The yang year precedes the yin year within each element. The current 60-year cycle began in 1984 CE; the first cycle of the Common Era began in 4 CE. Thus, 1984 was the year of the Wood Rat (yang), 1985 was the year of the Wood Ox (yin), and 1986 the year of the Fire Tiger (yang); 2022 - which, as already noted, is the year of the Water Tiger (yang) - is the 39th year of the current cycle. Information for optional task The ten celestial stems are 甲 jiă, 乙 yĭ, 丙 bĭng, 丁 dīng, 戊 wù, 己 jĭ, 庚 gēng, 辛 xīn, 壬 rén, and 癸 gŭi. With the ASCII version of Pinyin tones, the names are written "jia3", "yi3", "bing3", "ding1", "wu4", "ji3", "geng1", "xin1", "ren2", and "gui3". The twelve terrestrial branches are 子 zĭ, 丑 chŏu, 寅 yín, 卯 măo, 辰 chén, 巳 sì, 午 wŭ, 未 wèi, 申 shēn, 酉 yŏu, 戌 xū, 亥 hài. In ASCII Pinyin, those are "zi3", "chou3", "yin2", "mao3", "chen2", "si4", "wu3", "wei4", "shen1", "you3", "xu1", and "hai4". Therefore 1984 was 甲子 (jiă-zĭ, or jia3-zi3). 2022 is 壬寅 (rén-yín or ren2-yin2).
#Kotlin
Kotlin
// version 1.1.2   class ChineseZodiac(val year: Int) { val stem : Char val branch : Char val sName : String val bName : String val element: String val animal : String val aspect : String val cycle : Int   private companion object { val animals = listOf("Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig") val aspects = listOf("Yang","Yin") val elements = listOf("Wood", "Fire", "Earth", "Metal", "Water") val stems = listOf('甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸') val branches = listOf('子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥') val sNames = listOf("jiă", "yĭ", "bĭng", "dīng", "wù", "jĭ", "gēng", "xīn", "rén", "gŭi") val bNames = listOf("zĭ", "chŏu", "yín", "măo", "chén", "sì", "wŭ", "wèi", "shēn", "yŏu", "xū", "hài") val fmt = "%d  %c%c  %-9s  %-7s  %-7s  %-6s %02d/60" }   init { val y = year - 4 val s = y % 10 val b = y % 12 stem = stems[s] branch = branches[b] sName = sNames[s] bName = bNames[b] element = elements[s / 2] animal = animals[b] aspect = aspects[s % 2] cycle = y % 60 + 1 }   override fun toString() = fmt.format(year, stem, branch, sName + "-" + bName, element, animal, aspect, cycle) }   fun main(args: Array<String>) { val years = intArrayOf(1935, 1938, 1968, 1972, 1976, 1984, 2017) println("Year Chinese Pinyin Element Animal Aspect Cycle") println("---- ------- --------- ------- ------- ------ -----") for (year in years) println(ChineseZodiac(year)) }
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an unusual filename:   `Abdu'l-Bahá.txt
#E
E
for file in [<file:input.txt>, <file:///input.txt>] { require(file.exists(), fn { `$file is missing!` }) require(!file.isDirectory(), fn { `$file is a directory!` }) }   for file in [<file:docs>, <file:///docs>] { require(file.exists(), fn { `$file is missing!` }) require(file.isDirectory(), fn { `$file is not a directory!` }) }
http://rosettacode.org/wiki/Chaos_game
Chaos game
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a starting point at random (preferably inside the triangle).   Then add the next point halfway between the starting point and one of the reference points.   This reference point is chosen at random. After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge. See also The Game of Chaos
#Gnuplot
Gnuplot
  ## Chaos Game (Sierpinski triangle) 2/16/17 aev reset fn="ChGS3Gnu1"; clr='"red"'; ttl="Chaos Game (Sierpinski triangle)" sz=600; sz1=sz/2; sz2=sz1*sqrt(3); x=y=xf=yf=v=0; dfn=fn.".dat"; ofn=fn.".png"; set terminal png font arial 12 size 640,640 set print dfn append set output ofn unset border; unset xtics; unset ytics; unset key; set size square set title ttl font "Arial:Bold,12" lim=30000; max=100; x=y=xw=yw=p=0; randgp(top) = floor(rand(0)*top) x=randgp(sz); y=randgp(sz2); do for [i=1:lim] { v=randgp(3); if (v==0) {x=x/2; y=y/2} if (v==1) {x=sz1+(sz1-x)/2; y=sz2-(sz2-y)/2} if (v==2) {x=sz-(sz-x)/2; y=y/2} xf=floor(x); yf=floor(y); if(!(xf<1||xf>sz||yf<1||yf>sz)) {print xf," ",yf}; } plot dfn using 1:2 with points pt 7 ps 0.5 lc @clr set output unset print  
http://rosettacode.org/wiki/Chat_server
Chat server
Task Write a server for a minimal text based chat. People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.
#Kotlin
Kotlin
import java.io.BufferedReader import java.io.IOException import java.io.InputStreamReader import java.io.OutputStreamWriter import java.io.Writer import java.net.ServerSocket import java.net.Socket import java.util.ArrayList import java.util.Collections   class ChatServer private constructor(private val port: Int) : Runnable { private val clients = ArrayList<Client>()   private val onlineListCSV: String @Synchronized get() { val sb = StringBuilder() sb.append(clients.size).append(" user(s) online: ") for (i in clients.indices) { sb.append(if (i > 0) ", " else "").append(clients[i].clientName) } return sb.toString() }   override fun run() { try { val ss = ServerSocket(port) while (true) { val s = ss.accept() Thread(Client(s)).start() } } catch (e: Exception) { e.printStackTrace() } }   @Synchronized private fun registerClient(client: Client): Boolean { for (otherClient in clients) { if (otherClient.clientName!!.equals(client.clientName!!, ignoreCase = true)) { return false } } clients.add(client) return true }   private fun deRegisterClient(client: Client) { var wasRegistered = false synchronized(this) { wasRegistered = clients.remove(client) } if (wasRegistered) { broadcast(client, "--- " + client.clientName + " left ---") } }   private fun broadcast(fromClient: Client, msg: String) { // Copy client list (don't want to hold lock while doing IO) var clients: List<Client> = Collections.emptyList() synchronized(this) { clients = ArrayList(this.clients) } for (client in clients) { if (client.equals(fromClient)) { continue } try { client.write(msg + "\r\n") } catch (e: Exception) { e.printStackTrace() }   } }   inner class Client internal constructor(private var socket: Socket?) : Runnable { private var output: Writer? = null var clientName: String? = null   override fun run() { try { socket!!.sendBufferSize = 16384 socket!!.tcpNoDelay = true val input = BufferedReader(InputStreamReader(socket!!.getInputStream())) output = OutputStreamWriter(socket!!.getOutputStream()) write("Please enter your name: ") var line: String while (true) { line = input.readLine() if (null == line) { break } if (clientName == null) { line = line.trim { it <= ' ' } if (line.isEmpty()) { write("A name is required. Please enter your name: ") continue } clientName = line if (!registerClient(this)) { clientName = null write("Name already registered. Please enter your name: ") continue } write(onlineListCSV + "\r\n") broadcast(this, "+++ $clientName arrived +++") continue } if (line.equals("/quit", ignoreCase = true)) { return } broadcast(this, "$clientName> $line") } } catch (e: Exception) { e.printStackTrace() } finally { deRegisterClient(this) output = null try { socket!!.close() } catch (e: Exception) { e.printStackTrace() }   socket = null } }   @Throws(IOException::class) internal fun write(msg: String) { output!!.write(msg) output!!.flush() }   internal fun equals(client: Client?): Boolean { return (client != null && clientName != null && client.clientName != null && clientName == client.clientName) } }   companion object { @JvmStatic fun main(args: Array<String>) { var port = 4004 if (args.isNotEmpty()) { port = Integer.parseInt(args[0]) } ChatServer(port).run() } } }
http://rosettacode.org/wiki/Check_Machin-like_formulas
Check Machin-like formulas
Machin-like formulas   are useful for efficiently computing numerical approximations for π {\displaystyle \pi } Task Verify the following Machin-like formulas are correct by calculating the value of tan   (right hand side) for each equation using exact arithmetic and showing they equal 1: π 4 = arctan ⁡ 1 2 + arctan ⁡ 1 3 {\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 3}} π 4 = 2 arctan ⁡ 1 3 + arctan ⁡ 1 7 {\displaystyle {\pi \over 4}=2\arctan {1 \over 3}+\arctan {1 \over 7}} π 4 = 4 arctan ⁡ 1 5 − arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 239}} π 4 = 5 arctan ⁡ 1 7 + 2 arctan ⁡ 3 79 {\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+2\arctan {3 \over 79}} π 4 = 5 arctan ⁡ 29 278 + 7 arctan ⁡ 3 79 {\displaystyle {\pi \over 4}=5\arctan {29 \over 278}+7\arctan {3 \over 79}} π 4 = arctan ⁡ 1 2 + arctan ⁡ 1 5 + arctan ⁡ 1 8 {\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 5}+\arctan {1 \over 8}} π 4 = 4 arctan ⁡ 1 5 − arctan ⁡ 1 70 + arctan ⁡ 1 99 {\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 70}+\arctan {1 \over 99}} π 4 = 5 arctan ⁡ 1 7 + 4 arctan ⁡ 1 53 + 2 arctan ⁡ 1 4443 {\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+4\arctan {1 \over 53}+2\arctan {1 \over 4443}} π 4 = 6 arctan ⁡ 1 8 + 2 arctan ⁡ 1 57 + arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=6\arctan {1 \over 8}+2\arctan {1 \over 57}+\arctan {1 \over 239}} π 4 = 8 arctan ⁡ 1 10 − arctan ⁡ 1 239 − 4 arctan ⁡ 1 515 {\displaystyle {\pi \over 4}=8\arctan {1 \over 10}-\arctan {1 \over 239}-4\arctan {1 \over 515}} π 4 = 12 arctan ⁡ 1 18 + 8 arctan ⁡ 1 57 − 5 arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=12\arctan {1 \over 18}+8\arctan {1 \over 57}-5\arctan {1 \over 239}} π 4 = 16 arctan ⁡ 1 21 + 3 arctan ⁡ 1 239 + 4 arctan ⁡ 3 1042 {\displaystyle {\pi \over 4}=16\arctan {1 \over 21}+3\arctan {1 \over 239}+4\arctan {3 \over 1042}} π 4 = 22 arctan ⁡ 1 28 + 2 arctan ⁡ 1 443 − 5 arctan ⁡ 1 1393 − 10 arctan ⁡ 1 11018 {\displaystyle {\pi \over 4}=22\arctan {1 \over 28}+2\arctan {1 \over 443}-5\arctan {1 \over 1393}-10\arctan {1 \over 11018}} π 4 = 22 arctan ⁡ 1 38 + 17 arctan ⁡ 7 601 + 10 arctan ⁡ 7 8149 {\displaystyle {\pi \over 4}=22\arctan {1 \over 38}+17\arctan {7 \over 601}+10\arctan {7 \over 8149}} π 4 = 44 arctan ⁡ 1 57 + 7 arctan ⁡ 1 239 − 12 arctan ⁡ 1 682 + 24 arctan ⁡ 1 12943 {\displaystyle {\pi \over 4}=44\arctan {1 \over 57}+7\arctan {1 \over 239}-12\arctan {1 \over 682}+24\arctan {1 \over 12943}} π 4 = 88 arctan ⁡ 1 172 + 51 arctan ⁡ 1 239 + 32 arctan ⁡ 1 682 + 44 arctan ⁡ 1 5357 + 68 arctan ⁡ 1 12943 {\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12943}} and confirm that the following formula is incorrect by showing   tan   (right hand side)   is not   1: π 4 = 88 arctan ⁡ 1 172 + 51 arctan ⁡ 1 239 + 32 arctan ⁡ 1 682 + 44 arctan ⁡ 1 5357 + 68 arctan ⁡ 1 12944 {\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12944}} These identities are useful in calculating the values: tan ⁡ ( a + b ) = tan ⁡ ( a ) + tan ⁡ ( b ) 1 − tan ⁡ ( a ) tan ⁡ ( b ) {\displaystyle \tan(a+b)={\tan(a)+\tan(b) \over 1-\tan(a)\tan(b)}} tan ⁡ ( arctan ⁡ a b ) = a b {\displaystyle \tan \left(\arctan {a \over b}\right)={a \over b}} tan ⁡ ( − a ) = − tan ⁡ ( a ) {\displaystyle \tan(-a)=-\tan(a)} You can store the equations in any convenient data structure, but for extra credit parse them from human-readable text input. Note: to formally prove the formula correct, it would have to be shown that − 3 p i 4 {\displaystyle {-3pi \over 4}} < right hand side < 5 p i 4 {\displaystyle {5pi \over 4}} due to tan ⁡ ( ) {\displaystyle \tan()} periodicity.
#R
R
  #lang R library(Rmpfr) prec <- 1000 # precision in bits `%:%` <- function(e1, e2) '/'(mpfr(e1, prec), mpfr(e2, prec)) # operator %:% for high precision division # function for checking identity of tan of expression and 1, making use of high precision division operator %:% tanident_1 <- function(x) identical(round(tan(eval(parse(text = gsub("/", "%:%", deparse(substitute(x)))))), (prec/10)), mpfr(1, prec))  
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out the corresponding character.
#Clojure
Clojure
(print (int \a)) ; prints "97" (print (char 97)) ; prints \a   ; Unicode is also available, as Clojure uses the underlying java Strings & chars (print (int \π)) ; prints 960 (print (char 960)) ; prints \π   ; use String because char in Java can't represent characters outside Basic Multilingual Plane (print (.codePointAt "𝅘𝅥𝅮" 0)) ; prints 119136 (print (String. (int-array 1 119136) 0 1)) ; prints 𝅘𝅥𝅮
http://rosettacode.org/wiki/Cholesky_decomposition
Cholesky decomposition
Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interpreted as a generalized square root of A {\displaystyle A} , as described in Cholesky decomposition. In a 3x3 example, we have to solve the following system of equations: A = ( a 11 a 21 a 31 a 21 a 22 a 32 a 31 a 32 a 33 ) = ( l 11 0 0 l 21 l 22 0 l 31 l 32 l 33 ) ( l 11 l 21 l 31 0 l 22 l 32 0 0 l 33 ) ≡ L L T = ( l 11 2 l 21 l 11 l 31 l 11 l 21 l 11 l 21 2 + l 22 2 l 31 l 21 + l 32 l 22 l 31 l 11 l 31 l 21 + l 32 l 22 l 31 2 + l 32 2 + l 33 2 ) {\displaystyle {\begin{aligned}A&={\begin{pmatrix}a_{11}&a_{21}&a_{31}\\a_{21}&a_{22}&a_{32}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}\\&={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}l_{11}&l_{21}&l_{31}\\0&l_{22}&l_{32}\\0&0&l_{33}\end{pmatrix}}\equiv LL^{T}\\&={\begin{pmatrix}l_{11}^{2}&l_{21}l_{11}&l_{31}l_{11}\\l_{21}l_{11}&l_{21}^{2}+l_{22}^{2}&l_{31}l_{21}+l_{32}l_{22}\\l_{31}l_{11}&l_{31}l_{21}+l_{32}l_{22}&l_{31}^{2}+l_{32}^{2}+l_{33}^{2}\end{pmatrix}}\end{aligned}}} We can see that for the diagonal elements ( l k k {\displaystyle l_{kk}} ) of L {\displaystyle L} there is a calculation pattern: l 11 = a 11 {\displaystyle l_{11}={\sqrt {a_{11}}}} l 22 = a 22 − l 21 2 {\displaystyle l_{22}={\sqrt {a_{22}-l_{21}^{2}}}} l 33 = a 33 − ( l 31 2 + l 32 2 ) {\displaystyle l_{33}={\sqrt {a_{33}-(l_{31}^{2}+l_{32}^{2})}}} or in general: l k k = a k k − ∑ j = 1 k − 1 l k j 2 {\displaystyle l_{kk}={\sqrt {a_{kk}-\sum _{j=1}^{k-1}l_{kj}^{2}}}} For the elements below the diagonal ( l i k {\displaystyle l_{ik}} , where i > k {\displaystyle i>k} ) there is also a calculation pattern: l 21 = 1 l 11 a 21 {\displaystyle l_{21}={\frac {1}{l_{11}}}a_{21}} l 31 = 1 l 11 a 31 {\displaystyle l_{31}={\frac {1}{l_{11}}}a_{31}} l 32 = 1 l 22 ( a 32 − l 31 l 21 ) {\displaystyle l_{32}={\frac {1}{l_{22}}}(a_{32}-l_{31}l_{21})} which can also be expressed in a general formula: l i k = 1 l k k ( a i k − ∑ j = 1 k − 1 l i j l k j ) {\displaystyle l_{ik}={\frac {1}{l_{kk}}}\left(a_{ik}-\sum _{j=1}^{k-1}l_{ij}l_{kj}\right)} Task description The task is to implement a routine which will return a lower Cholesky factor L {\displaystyle L} for every given symmetric, positive definite nxn matrix A {\displaystyle A} . You should then test it on the following two examples and include your output. Example 1: 25 15 -5 5 0 0 15 18 0 --> 3 3 0 -5 0 11 -1 1 3 Example 2: 18 22 54 42 4.24264 0.00000 0.00000 0.00000 22 70 86 62 --> 5.18545 6.56591 0.00000 0.00000 54 86 174 134 12.72792 3.04604 1.64974 0.00000 42 62 134 106 9.89949 1.62455 1.84971 1.39262 Note The Cholesky decomposition of a Pascal upper-triangle matrix is the Identity matrix of the same size. The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
#MATLAB_.2F_Octave
MATLAB / Octave
A = [ 25 15 -5 15 18 0 -5 0 11 ];   B = [ 18 22 54 42 22 70 86 62 54 86 174 134 42 62 134 106 ];   [L] = chol(A,'lower') [L] = chol(B,'lower')  
http://rosettacode.org/wiki/Cheryl%27s_birthday
Cheryl's birthday
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the   month   of birth,   and Bernard the   day   (of the month)   of birth. 1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too. 2) Bernard: At first I don't know when Cheryl's birthday is, but I know now. 3) Albert: Then I also know when Cheryl's birthday is. Task Write a computer program to deduce, by successive elimination, Cheryl's birthday. Related task Sum and Product Puzzle References Wikipedia article of the same name. Tuple Relational Calculus
#Phix
Phix
-- demo\rosetta\Cheryls_Birthday.exw with javascript_semantics sequence choices = {{5, 15}, {5, 16}, {5, 19}, {6, 17}, {6, 18}, {7, 14}, {7, 16}, {8, 14}, {8, 15}, {8, 17}} sequence mwud = repeat(false,12) -- months with unique days for step=1 to 4 do sequence {months,days} = columnize(choices) bool impossible = false for i=length(choices) to 1 by -1 do integer {m,d} = choices[i] switch step do case 1: mwud[m] += (sum(sq_eq(days,d))=1) case 2: impossible = mwud[m] case 3: impossible = (sum(sq_eq(days,d))!=1) case 4: impossible = (sum(sq_eq(months,m))!=1) end switch if impossible then choices[i..i] = {} end if end for end for ?choices
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
#M2000_Interpreter
M2000 Interpreter
  Module Arr { \\ array as tuple A=(1,2,3,4,5) Print Array(A,0)=1 Print A \\ add two arrays A=Cons(A, (6,)) Print Len(A)=6 Print A \\ arrays may have arrays, inventories, stacks as items A=((1,2,3),(4,5,6)) Print Array(Array(A, 0),2)=3 } 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
#Picat
Picat
go =>  % Integers 1..K N = 3, K = 5, printf("comb1(3,5): %w\n", comb1(N,K)), nl.   % Recursive (numbers) comb1(M,N) = comb1_(M, 1..N). comb1_(0, _X) = [[]]. comb1_(_M, []) = []. comb1_(M, [X|Xs]) = [ [X] ++ Xs2 : Xs2 in comb1_(M-1, Xs) ] ++ comb1_(M, Xs).
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include if-then-else and switch. Less common are arithmetic if, ternary operator and Hash-based conditionals. Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
#SIMPOL
SIMPOL
if x == 1 foo() else if x == 2 bar() else foobar() end if
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 {\displaystyle a_{2}} ,   … {\displaystyle \dots } ,   a k {\displaystyle a_{k}} ,   there exists an integer   x {\displaystyle x}   solving the following system of simultaneous congruences: x ≡ a 1 ( mod n 1 ) x ≡ a 2 ( mod n 2 )     ⋮ x ≡ a k ( mod n k ) {\displaystyle {\begin{aligned}x&\equiv a_{1}{\pmod {n_{1}}}\\x&\equiv a_{2}{\pmod {n_{2}}}\\&{}\ \ \vdots \\x&\equiv a_{k}{\pmod {n_{k}}}\end{aligned}}} Furthermore, all solutions   x {\displaystyle x}   of this system are congruent modulo the product,   N = n 1 n 2 … n k {\displaystyle N=n_{1}n_{2}\ldots n_{k}} . Task Write a program to solve a system of linear congruences by applying the   Chinese Remainder Theorem. If the system of equations cannot be solved, your program must somehow indicate this. (It may throw an exception or return a special false value.) Since there are infinitely many solutions, the program should return the unique solution   s {\displaystyle s}   where   0 ≤ s ≤ n 1 n 2 … n k {\displaystyle 0\leq s\leq n_{1}n_{2}\ldots n_{k}} . Show the functionality of this program by printing the result such that the   n {\displaystyle n} 's   are   [ 3 , 5 , 7 ] {\displaystyle [3,5,7]}   and the   a {\displaystyle a} 's   are   [ 2 , 3 , 2 ] {\displaystyle [2,3,2]} . Algorithm:   The following algorithm only applies if the   n i {\displaystyle n_{i}} 's   are pairwise co-prime. Suppose, as above, that a solution is required for the system of congruences: x ≡ a i ( mod n i ) f o r i = 1 , … , k {\displaystyle x\equiv a_{i}{\pmod {n_{i}}}\quad \mathrm {for} \;i=1,\ldots ,k} Again, to begin, the product   N = n 1 n 2 … n k {\displaystyle N=n_{1}n_{2}\ldots n_{k}}   is defined. Then a solution   x {\displaystyle x}   can be found as follows: For each   i {\displaystyle i} ,   the integers   n i {\displaystyle n_{i}}   and   N / n i {\displaystyle N/n_{i}}   are co-prime. Using the   Extended Euclidean algorithm,   we can find integers   r i {\displaystyle r_{i}}   and   s i {\displaystyle s_{i}}   such that   r i n i + s i N / n i = 1 {\displaystyle r_{i}n_{i}+s_{i}N/n_{i}=1} . Then, one solution to the system of simultaneous congruences is: x = ∑ i = 1 k a i s i N / n i {\displaystyle x=\sum _{i=1}^{k}a_{i}s_{i}N/n_{i}} and the minimal solution, x ( mod N ) {\displaystyle x{\pmod {N}}} .
#jq
jq
# mul_inv(a;b) returns x where (a * x) % b == 1, or else null def mul_inv(a; b):   # state: [a, b, x0, x1] def iterate: .[0] as $a | .[1] as $b | if $a > 1 then if $b == 0 then null else ($a / $b | floor) as $q | [$b, ($a % $b), (.[3] - ($q * .[2])), .[2]] | iterate end else . end ;   if (b == 1) then 1 else [a,b,0,1] | iterate | if . == null then . else .[3] | if . < 0 then . + b else . end end end;   def chinese_remainder(mods; remainders): (reduce mods[] as $i (1; . * $i)) as $prod | reduce range(0; mods|length) as $i (0; ($prod/mods[$i]) as $p | mul_inv($p; mods[$i]) as $mi | if $mi == null then error("nogo: p=\($p) mods[\($i)]=\(mods[$i])") else . + (remainders[$i] * $mi * $p) end ) | . % $prod ;
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 {\displaystyle a_{2}} ,   … {\displaystyle \dots } ,   a k {\displaystyle a_{k}} ,   there exists an integer   x {\displaystyle x}   solving the following system of simultaneous congruences: x ≡ a 1 ( mod n 1 ) x ≡ a 2 ( mod n 2 )     ⋮ x ≡ a k ( mod n k ) {\displaystyle {\begin{aligned}x&\equiv a_{1}{\pmod {n_{1}}}\\x&\equiv a_{2}{\pmod {n_{2}}}\\&{}\ \ \vdots \\x&\equiv a_{k}{\pmod {n_{k}}}\end{aligned}}} Furthermore, all solutions   x {\displaystyle x}   of this system are congruent modulo the product,   N = n 1 n 2 … n k {\displaystyle N=n_{1}n_{2}\ldots n_{k}} . Task Write a program to solve a system of linear congruences by applying the   Chinese Remainder Theorem. If the system of equations cannot be solved, your program must somehow indicate this. (It may throw an exception or return a special false value.) Since there are infinitely many solutions, the program should return the unique solution   s {\displaystyle s}   where   0 ≤ s ≤ n 1 n 2 … n k {\displaystyle 0\leq s\leq n_{1}n_{2}\ldots n_{k}} . Show the functionality of this program by printing the result such that the   n {\displaystyle n} 's   are   [ 3 , 5 , 7 ] {\displaystyle [3,5,7]}   and the   a {\displaystyle a} 's   are   [ 2 , 3 , 2 ] {\displaystyle [2,3,2]} . Algorithm:   The following algorithm only applies if the   n i {\displaystyle n_{i}} 's   are pairwise co-prime. Suppose, as above, that a solution is required for the system of congruences: x ≡ a i ( mod n i ) f o r i = 1 , … , k {\displaystyle x\equiv a_{i}{\pmod {n_{i}}}\quad \mathrm {for} \;i=1,\ldots ,k} Again, to begin, the product   N = n 1 n 2 … n k {\displaystyle N=n_{1}n_{2}\ldots n_{k}}   is defined. Then a solution   x {\displaystyle x}   can be found as follows: For each   i {\displaystyle i} ,   the integers   n i {\displaystyle n_{i}}   and   N / n i {\displaystyle N/n_{i}}   are co-prime. Using the   Extended Euclidean algorithm,   we can find integers   r i {\displaystyle r_{i}}   and   s i {\displaystyle s_{i}}   such that   r i n i + s i N / n i = 1 {\displaystyle r_{i}n_{i}+s_{i}N/n_{i}=1} . Then, one solution to the system of simultaneous congruences is: x = ∑ i = 1 k a i s i N / n i {\displaystyle x=\sum _{i=1}^{k}a_{i}s_{i}N/n_{i}} and the minimal solution, x ( mod N ) {\displaystyle x{\pmod {N}}} .
#Julia
Julia
function chineseremainder(n::Array, a::Array) Π = prod(n) mod(sum(ai * invmod(Π ÷ ni, ni) * (Π ÷ ni) for (ni, ai) in zip(n, a)), Π) end   @show chineseremainder([3, 5, 7], [2, 3, 2])
http://rosettacode.org/wiki/Chowla_numbers
Chowla numbers
Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n   is a positive integer The sequence is named after   Sarvadaman D. S. Chowla,   (22 October 1907 ──► 10 December 1995), a London born Indian American mathematician specializing in number theory. German mathematician Carl Friedrich Gauss (1777─1855) said: "Mathematics is the queen of the sciences ─ and number theory is the queen of mathematics". Definitions Chowla numbers can also be expressed as: chowla(n) = sum of divisors of n excluding unity and n chowla(n) = sum( divisors(n)) - 1 - n chowla(n) = sum( properDivisors(n)) - 1 chowla(n) = sum(aliquotDivisors(n)) - 1 chowla(n) = aliquot(n) - 1 chowla(n) = sigma(n) - 1 - n chowla(n) = sigmaProperDivisiors(n) - 1   chowla(a*b) = a + b,   if a and b are distinct primes if chowla(n) = 0,  and n > 1, then n is prime if chowla(n) = n - 1, and n > 1, then n is a perfect number Task   create a   chowla   function that returns the   chowla number   for a positive integer   n   Find and display   (1 per line)   for the 1st   37   integers:   the integer   (the index)   the chowla number for that integer   For finding primes, use the   chowla   function to find values of zero   Find and display the   count   of the primes up to              100   Find and display the   count   of the primes up to           1,000   Find and display the   count   of the primes up to         10,000   Find and display the   count   of the primes up to       100,000   Find and display the   count   of the primes up to    1,000,000   Find and display the   count   of the primes up to  10,000,000   For finding perfect numbers, use the   chowla   function to find values of   n - 1   Find and display all   perfect numbers   up to   35,000,000   use commas within appropriate numbers   show all output here Related tasks   totient function   perfect numbers   Proper divisors   Sieve of Eratosthenes See also   the OEIS entry for   A48050 Chowla's function.
#Ruby
Ruby
def chowla(n) sum = 0 i = 2 while i * i <= n do if n % i == 0 then sum = sum + i j = n / i if i != j then sum = sum + j end end i = i + 1 end return sum end   def main for n in 1 .. 37 do puts "chowla(%d) = %d" % [n, chowla(n)] end   count = 0 power = 100 for n in 2 .. 10000000 do if chowla(n) == 0 then count = count + 1 end if n % power == 0 then puts "There are %d primes < %d" % [count, power] power = power * 10 end end   count = 0 limit = 350000000 k = 2 kk = 3 loop do p = k * kk if p > limit then break end if chowla(p) == p - 1 then puts "%d is a perfect number" % [p] count = count + 1 end k = kk + 1 kk = kk + k end puts "There are %d perfect numbers < %d" % [count, limit] end   main()
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.
#MiniZinc
MiniZinc
% define a Rectangle "class" var int: Rectangle(var int: width, var int: height) = let { var int: this; constraint Type(this) = Rectangle; %define the "type" of the instance  %define some "instance methods" constraint area(this) = width*height; constraint width(this) = width; constraint height(this) = height; } in this;   %this enum should contain the list of class names enum Type = {Rectangle}; function var Type: Type(var int:a);   %declare the "instance methods" function var int: area(var int:this) = let {var int:result;} in result; function var int: height(var int:a) = let {var int:result;} in result; function var int: width(var int:a) = let {var int:result;} in result;   %create an instance of the "class" var int: rect = Rectangle(3,4); var int: area1 = area(rect);   solve satisfy;   % print the area of the rectangle output [show(area1),"\n"];
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, as a type, has the values and operations of its own. The operations of are usually called methods of the root type. Both operations and values are called polymorphic. A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument. The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual. Operations with multiple arguments and/or the results of the class are called multi-methods. A further generalization of is the operation with arguments and/or results from different classes. single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x). multiple-dispatch languages allow many arguments and/or results to control the dispatch. A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type. This type is sometimes called the most specific type of a [polymorphic] value. The type tag of the value is used in order to resolve the dispatch. The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class. In many OO languages the type of the class of T and T itself are considered equivalent. In some languages they are distinct (like in Ada). When class T and T are equivalent, there is no way to distinguish polymorphic and specific values. Task Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
#Nanoquery
Nanoquery
class MyClass declare name   // constructors are methods with the same name as the class def MyClass(name) this.name = name end   def getName() return name end end   // instantiate a new MyClass object inst = new(MyClass, "name string goes here")   // display the name value println inst.getName()
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)
#Perl
Perl
use strict; use warnings; use POSIX qw(ceil);   sub dist { my ($a, $b) = @_; return sqrt(($a->[0] - $b->[0])**2 + ($a->[1] - $b->[1])**2) }   sub closest_pair_simple { my @points = @{ shift @_ }; my ($a, $b, $d) = ( $points[0], $points[1], dist($points[0], $points[1]) ); while( @points ) { my $p = pop @points; for my $l (@points) { my $t = dist($p, $l); ($a, $b, $d) = ($p, $l, $t) if $t < $d; } } $a, $b, $d }   sub closest_pair { my @r = @{ shift @_ }; closest_pair_real( [sort { $a->[0] <=> $b->[0] } @r], [sort { $a->[1] <=> $b->[1] } @r] ) }   sub closest_pair_real { my ($rx, $ry) = @_; return closest_pair_simple($rx) if scalar(@$rx) <= 3;   my(@yR, @yL, @yS); my $N = @$rx; my $midx = ceil($N/2)-1; my @PL = @$rx[ 0 .. $midx]; my @PR = @$rx[$midx+1 .. $N-1]; my $xm = $$rx[$midx]->[0]; $_->[0] <= $xm ? push @yR, $_ : push @yL, $_ for @$ry; my ($al, $bl, $dL) = closest_pair_real(\@PL, \@yR); my ($ar, $br, $dR) = closest_pair_real(\@PR, \@yL); my ($w1, $w2, $closest) = $dR > $dL ? ($al, $bl, $dL) : ($ar, $br, $dR); abs($xm - $_->[0]) < $closest and push @yS, $_ for @$ry;   for my $i (0 .. @yS-1) { my $k = $i + 1; while ( $k <= $#yS and ($yS[$k]->[1] - $yS[$i]->[1]) < $closest ) { my $d = dist($yS[$k], $yS[$i]); ($w1, $w2, $closest) = ($yS[$k], $yS[$i], $d) if $d < $closest; $k++; } } $w1, $w2, $closest }   my @points; push @points, [rand(20)-10, rand(20)-10] for 1..5000; printf "%.8f between (%.5f, %.5f), (%.5f, %.5f)\n", $_->[2], @{$$_[0]}, @{$$_[1]} for [closest_pair_simple(\@points)], [closest_pair(\@points)];
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points
Circles of given radius through two points
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. Exceptions r==0.0 should be treated as never describing circles (except in the case where the points are coincident). If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point. If the points form a diameter then return two identical circles or return a single circle, according to which is the most natural mechanism for the implementation language. If the points are too far apart then no circles can be drawn. Task detail Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, or some indication of special cases where two, possibly equal, circles cannot be returned. Show here the output for the following inputs: p1 p2 r 0.1234, 0.9876 0.8765, 0.2345 2.0 0.0000, 2.0000 0.0000, 0.0000 1.0 0.1234, 0.9876 0.1234, 0.9876 2.0 0.1234, 0.9876 0.8765, 0.2345 0.5 0.1234, 0.9876 0.1234, 0.9876 0.0 Related task   Total circles area. See also   Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
#Lambdatalk
Lambdatalk
  input: OP1=(x1,y1), OP2=(x2,y2), r output: OC = OH + HC where OH = (OP1+OP2)/2 and HC = j*|HC| where j is the unit vector rotated -90° from P1P2 and |HC| = √(r^2 - (|P1P2|/2)^2) if exists   {def circleby2points {lambda {:x1 :y1 :x2 :y2 :r} {if {= :r 0} then radius is zero else {if {and {= :x1 :x2} {= :y1 :y2}} then same points else {let { {:r :r} {:vx {- :x2 :x1}} {:vy {- :y2 :y1}} // v = P1P2 {:hx {/ {+ :x1 :x2} 2}} {:hy {/ {+ :y1 :y2} 2}} } // h = OH {let { {:r :r} {:vx :vx} {:vy :vy} {:hx :hx} {:hy :hy} // closure {:d {sqrt {+ {* :px :px} {* :py :py}}} } } // d = |P1P2| {if {> :d {* 2 :r}} // d > diam then no circle, points are too far apart else {if {= :d {* 2 :r}} // d = diam then one circle: opposite ends of diameter with centre (:hx,:hy) else {let { {:r :r} {:hx :hx} {:hy :hy} // closure {:jx {- {/ :vy :d}}} {:jy {/ :vx :d}} // j unit -90° to P1P2 {:d {sqrt {- {* :r :r} {/ {* :d :d} 4}}}} } // |HC| two circles: {br}({+ :hx {* :d :jx}},{+ :hy {* :d :jy}}) // OH + j*|HC| {br}({- :hx {* :d :jx}},{- :hy {* :d :jy}}) // OH - j*|HC| }}}}}}}}}   {circleby2points -1 0 1 0 0.5} -> no circle: points are too far apart   {circleby2points -1 0 1 0 1} -> one circle: opposite ends of diameter with centre (0,0)   {circleby2points -1 0 1 0 {sqrt 2}} -> two circles: (0,1.0000000000000002) (0,-1.0000000000000002)   rosetta's task:   {circleby2points 0.1234 0.9876 0.8765 0.2345 2.0} -> two circles: (1.8631118016581893,1.974211801658189) (-0.8632118016581896,-0.7521118016581892)   {circleby2points 0.0000 2.0000 0.0000 0.0000 1.0} -> one circle: opposite ends of diameter with centre (0,1)   {circleby2points 0.1234 0.9876 0.1234 0.9876 2.0} -> same points   {circleby2points 0.1234 0.9876 0.8765 0.2345 0.5} -> no circle, points are too far apart   {circleby2points 0.1234 0.9876 0.1234 0.9876 0.0} -> radius is zero  
http://rosettacode.org/wiki/Chinese_zodiac
Chinese zodiac
Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Tuesday, February 1, 2022 CE (in the common Gregorian calendar) will begin the lunisolar Year of the Tiger. The celestial stems have no one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems each belong to one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element's governance is associated with yin, the other with yang. Thus, 2022 is also the yang year of Water. Note that since 12 is an even number, the association between animals and yin/yang doesn't change. Consecutive Years of the Rooster will cycle through the five elements, but will always be yin, despite the apparent conceptual mismatch between the specifically-male English animal name and the female aspect denoted by yin. Task Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year. You may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration). Requisite information The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig. The element cycle runs in this order: Wood, Fire, Earth, Metal, Water. The yang year precedes the yin year within each element. The current 60-year cycle began in 1984 CE; the first cycle of the Common Era began in 4 CE. Thus, 1984 was the year of the Wood Rat (yang), 1985 was the year of the Wood Ox (yin), and 1986 the year of the Fire Tiger (yang); 2022 - which, as already noted, is the year of the Water Tiger (yang) - is the 39th year of the current cycle. Information for optional task The ten celestial stems are 甲 jiă, 乙 yĭ, 丙 bĭng, 丁 dīng, 戊 wù, 己 jĭ, 庚 gēng, 辛 xīn, 壬 rén, and 癸 gŭi. With the ASCII version of Pinyin tones, the names are written "jia3", "yi3", "bing3", "ding1", "wu4", "ji3", "geng1", "xin1", "ren2", and "gui3". The twelve terrestrial branches are 子 zĭ, 丑 chŏu, 寅 yín, 卯 măo, 辰 chén, 巳 sì, 午 wŭ, 未 wèi, 申 shēn, 酉 yŏu, 戌 xū, 亥 hài. In ASCII Pinyin, those are "zi3", "chou3", "yin2", "mao3", "chen2", "si4", "wu3", "wei4", "shen1", "you3", "xu1", and "hai4". Therefore 1984 was 甲子 (jiă-zĭ, or jia3-zi3). 2022 is 壬寅 (rén-yín or ren2-yin2).
#Lua
Lua
local ANIMALS = {"Rat","Ox","Tiger","Rabbit","Dragon","Snake","Horse","Goat","Monkey","Rooster","Dog","Pig"} local ELEMENTS = {"Wood","Fire","Earth","Metal","Water"}   function element(year) local idx = math.floor(((year - 4) % 10) / 2) return ELEMENTS[idx + 1] end   function animal(year) local idx = (year - 4) % 12 return ANIMALS[idx + 1] end   function yy(year) if year % 2 == 0 then return "yang" else return "yin" end end   function zodiac(year) local e = element(year) local a = animal(year) local y = yy(year) print(year.." is the year of the "..e.." "..a.." ("..y..")") end   zodiac(1935) zodiac(1938) zodiac(1968) zodiac(1972) zodiac(1976) zodiac(2017)
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an unusual filename:   `Abdu'l-Bahá.txt
#Elena
Elena
import system'io; import extensions;   extension op { validatePath() = self.Available.iif("exists","not found"); }   public program() { console.printLine("input.txt file ",File.assign("input.txt").validatePath());   console.printLine("\input.txt file ",File.assign("\input.txt").validatePath());   console.printLine("docs directory ",Directory.assign("docs").validatePath());   console.printLine("\docs directory ",Directory.assign("\docs").validatePath()) }
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an unusual filename:   `Abdu'l-Bahá.txt
#Elixir
Elixir
File.regular?("input.txt") File.dir?("docs") File.regular?("/input.txt") File.dir?("/docs")
http://rosettacode.org/wiki/Chaos_game
Chaos game
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a starting point at random (preferably inside the triangle).   Then add the next point halfway between the starting point and one of the reference points.   This reference point is chosen at random. After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge. See also The Game of Chaos
#Go
Go
package main   import ( "fmt" "image" "image/color" "image/draw" "image/gif" "log" "math" "math/rand" "os" "time" )   var bwPalette = color.Palette{ color.Transparent, color.White, color.RGBA{R: 0xff, A: 0xff}, color.RGBA{G: 0xff, A: 0xff}, color.RGBA{B: 0xff, A: 0xff}, }   func main() { const ( width = 160 frames = 100 pointsPerFrame = 50 delay = 100 * time.Millisecond filename = "chaos_anim.gif" )   var tan60 = math.Sin(math.Pi / 3) height := int(math.Round(float64(width) * tan60)) b := image.Rect(0, 0, width, height) vertices := [...]image.Point{ {0, height}, {width, height}, {width / 2, 0}, }   // Make a filled triangle. m := image.NewPaletted(b, bwPalette) for y := b.Min.Y; y < b.Max.Y; y++ { bg := int(math.Round(float64(b.Max.Y-y) / 2 / tan60)) for x := b.Min.X + bg; x < b.Max.X-bg; x++ { m.SetColorIndex(x, y, 1) } }   // Pick starting point var p image.Point rand.Seed(time.Now().UnixNano()) p.Y = rand.Intn(height) + b.Min.Y p.X = rand.Intn(width) + b.Min.X // TODO: make within triangle   anim := newAnim(frames, delay) addFrame(anim, m) for i := 1; i < frames; i++ { for j := 0; j < pointsPerFrame; j++ { // Pick a random vertex vi := rand.Intn(len(vertices)) v := vertices[vi] // Move p halfway there p.X = (p.X + v.X) / 2 p.Y = (p.Y + v.Y) / 2 m.SetColorIndex(p.X, p.Y, uint8(2+vi)) } addFrame(anim, m) } if err := writeAnim(anim, filename); err != nil { log.Fatal(err) } fmt.Printf("wrote to %q\n", filename) }   // Stuff for making a simple GIF animation.   func newAnim(frames int, delay time.Duration) *gif.GIF { const gifDelayScale = 10 * time.Millisecond g := &gif.GIF{ Image: make([]*image.Paletted, 0, frames), Delay: make([]int, 1, frames), } g.Delay[0] = int(delay / gifDelayScale) return g } func addFrame(anim *gif.GIF, m *image.Paletted) { b := m.Bounds() dst := image.NewPaletted(b, m.Palette) draw.Draw(dst, b, m, image.ZP, draw.Src) anim.Image = append(anim.Image, dst) if len(anim.Delay) < len(anim.Image) { anim.Delay = append(anim.Delay, anim.Delay[0]) } } func writeAnim(anim *gif.GIF, filename string) error { f, err := os.Create(filename) if err != nil { return err } err = gif.EncodeAll(f, anim) if cerr := f.Close(); err == nil { err = cerr } return err }
http://rosettacode.org/wiki/Chat_server
Chat server
Task Write a server for a minimal text based chat. People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.
#Nim
Nim
import asyncnet, asyncdispatch   type Client = tuple socket: AsyncSocket name: string connected: bool   var clients {.threadvar.}: seq[Client]   proc sendOthers(client: Client, line: string) {.async.} = for c in clients: if c != client and c.connected: await c.socket.send(line & "\c\L")   proc processClient(socket: AsyncSocket) {.async.} = await socket.send("Please enter your name: ") var client: Client = (socket, await socket.recvLine(), true)   clients.add(client) asyncCheck client.sendOthers("+++ " & client.name & " arrived +++")   while true: let line = await client.socket.recvLine() if line == "": asyncCheck client.sendOthers("--- " & client.name & " leaves ---") client.connected = false return asyncCheck client.sendOthers(client.name & "> " & line)   proc serve() {.async.} = clients = @[] var server = newAsyncSocket() server.bindAddr(Port(4004)) server.listen()   while true: let socket = await server.accept() asyncCheck processClient(socket)   asyncCheck serve() runForever()
http://rosettacode.org/wiki/Check_Machin-like_formulas
Check Machin-like formulas
Machin-like formulas   are useful for efficiently computing numerical approximations for π {\displaystyle \pi } Task Verify the following Machin-like formulas are correct by calculating the value of tan   (right hand side) for each equation using exact arithmetic and showing they equal 1: π 4 = arctan ⁡ 1 2 + arctan ⁡ 1 3 {\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 3}} π 4 = 2 arctan ⁡ 1 3 + arctan ⁡ 1 7 {\displaystyle {\pi \over 4}=2\arctan {1 \over 3}+\arctan {1 \over 7}} π 4 = 4 arctan ⁡ 1 5 − arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 239}} π 4 = 5 arctan ⁡ 1 7 + 2 arctan ⁡ 3 79 {\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+2\arctan {3 \over 79}} π 4 = 5 arctan ⁡ 29 278 + 7 arctan ⁡ 3 79 {\displaystyle {\pi \over 4}=5\arctan {29 \over 278}+7\arctan {3 \over 79}} π 4 = arctan ⁡ 1 2 + arctan ⁡ 1 5 + arctan ⁡ 1 8 {\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 5}+\arctan {1 \over 8}} π 4 = 4 arctan ⁡ 1 5 − arctan ⁡ 1 70 + arctan ⁡ 1 99 {\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 70}+\arctan {1 \over 99}} π 4 = 5 arctan ⁡ 1 7 + 4 arctan ⁡ 1 53 + 2 arctan ⁡ 1 4443 {\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+4\arctan {1 \over 53}+2\arctan {1 \over 4443}} π 4 = 6 arctan ⁡ 1 8 + 2 arctan ⁡ 1 57 + arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=6\arctan {1 \over 8}+2\arctan {1 \over 57}+\arctan {1 \over 239}} π 4 = 8 arctan ⁡ 1 10 − arctan ⁡ 1 239 − 4 arctan ⁡ 1 515 {\displaystyle {\pi \over 4}=8\arctan {1 \over 10}-\arctan {1 \over 239}-4\arctan {1 \over 515}} π 4 = 12 arctan ⁡ 1 18 + 8 arctan ⁡ 1 57 − 5 arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=12\arctan {1 \over 18}+8\arctan {1 \over 57}-5\arctan {1 \over 239}} π 4 = 16 arctan ⁡ 1 21 + 3 arctan ⁡ 1 239 + 4 arctan ⁡ 3 1042 {\displaystyle {\pi \over 4}=16\arctan {1 \over 21}+3\arctan {1 \over 239}+4\arctan {3 \over 1042}} π 4 = 22 arctan ⁡ 1 28 + 2 arctan ⁡ 1 443 − 5 arctan ⁡ 1 1393 − 10 arctan ⁡ 1 11018 {\displaystyle {\pi \over 4}=22\arctan {1 \over 28}+2\arctan {1 \over 443}-5\arctan {1 \over 1393}-10\arctan {1 \over 11018}} π 4 = 22 arctan ⁡ 1 38 + 17 arctan ⁡ 7 601 + 10 arctan ⁡ 7 8149 {\displaystyle {\pi \over 4}=22\arctan {1 \over 38}+17\arctan {7 \over 601}+10\arctan {7 \over 8149}} π 4 = 44 arctan ⁡ 1 57 + 7 arctan ⁡ 1 239 − 12 arctan ⁡ 1 682 + 24 arctan ⁡ 1 12943 {\displaystyle {\pi \over 4}=44\arctan {1 \over 57}+7\arctan {1 \over 239}-12\arctan {1 \over 682}+24\arctan {1 \over 12943}} π 4 = 88 arctan ⁡ 1 172 + 51 arctan ⁡ 1 239 + 32 arctan ⁡ 1 682 + 44 arctan ⁡ 1 5357 + 68 arctan ⁡ 1 12943 {\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12943}} and confirm that the following formula is incorrect by showing   tan   (right hand side)   is not   1: π 4 = 88 arctan ⁡ 1 172 + 51 arctan ⁡ 1 239 + 32 arctan ⁡ 1 682 + 44 arctan ⁡ 1 5357 + 68 arctan ⁡ 1 12944 {\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12944}} These identities are useful in calculating the values: tan ⁡ ( a + b ) = tan ⁡ ( a ) + tan ⁡ ( b ) 1 − tan ⁡ ( a ) tan ⁡ ( b ) {\displaystyle \tan(a+b)={\tan(a)+\tan(b) \over 1-\tan(a)\tan(b)}} tan ⁡ ( arctan ⁡ a b ) = a b {\displaystyle \tan \left(\arctan {a \over b}\right)={a \over b}} tan ⁡ ( − a ) = − tan ⁡ ( a ) {\displaystyle \tan(-a)=-\tan(a)} You can store the equations in any convenient data structure, but for extra credit parse them from human-readable text input. Note: to formally prove the formula correct, it would have to be shown that − 3 p i 4 {\displaystyle {-3pi \over 4}} < right hand side < 5 p i 4 {\displaystyle {5pi \over 4}} due to tan ⁡ ( ) {\displaystyle \tan()} periodicity.
#Racket
Racket
  #lang racket (define (reduce e) (match e [(? number? a) a] [(list '+ (? number? a) (? number? b)) (+ a b)] [(list '- (? number? a) (? number? b)) (- a b)] [(list '- (? number? a)) (- a)] [(list '* (? number? a) (? number? b)) (* a b)] [(list '/ (? number? a) (? number? b)) (/ a b)] [(list '+ a b) (reduce `(+ ,(reduce a) ,(reduce b)))] [(list '- a b) (reduce `(- ,(reduce a) ,(reduce b)))] [(list '- a) (reduce `(- ,(reduce a)))] [(list '* a b) (reduce `(* ,(reduce a) ,(reduce b)))] [(list '/ a b) (reduce `(/ ,(reduce a) ,(reduce b)))] [(list 'tan (list 'arctan a)) (reduce a)] [(list 'tan (list '- a)) (reduce `(- ,(reduce `(tan ,a))))] [(list 'tan (list '+ a b)) (reduce `(/ (+ (tan ,a) (tan ,b)) (- 1 (* (tan ,a) (tan ,b)))))] [(list 'tan (list '+ a b c ...)) (reduce `(tan (+ ,a (+ ,b ,@c))))] [(list 'tan (list '- a b)) (reduce `(/ (+ (tan ,a) (tan (- ,b))) (- 1 (* (tan ,a) (tan (- ,b))))))] [(list 'tan (list '* 1 a)) (reduce `(tan ,a))] [(list 'tan (list '* (? number? n) a)) (cond [(< n 0) (reduce `(- (tan (* ,(- n) ,a))))] [(= n 0) 0] [(even? n) (reduce `(tan (+ (* ,(/ n 2) ,a) (* ,(/ n 2) ,a))))] [else (reduce `(tan (+ ,a (* ,(- n 1) ,a))))])]))   (define correct-formulas '((tan (+ (arctan 1/2) (arctan 1/3))) (tan (+ (* 2 (arctan 1/3)) (arctan 1/7))) (tan (- (* 4 (arctan 1/5)) (arctan 1/239))) (tan (+ (* 5 (arctan 1/7)) (* 2 (arctan 3/79)))) (tan (+ (* 5 (arctan 29/278)) (* 7 (arctan 3/79)))) (tan (+ (arctan 1/2) (arctan 1/5) (arctan 1/8))) (tan (+ (* 4 (arctan 1/5)) (* -1 (arctan 1/70)) (arctan 1/99))) (tan (+ (* 5 (arctan 1/7)) (* 4 (arctan 1/53)) (* 2 (arctan 1/4443)))) (tan (+ (* 6 (arctan 1/8)) (* 2 (arctan 1/57)) (arctan 1/239))) (tan (+ (* 8 (arctan 1/10)) (* -1 (arctan 1/239)) (* -4 (arctan 1/515)))) (tan (+ (* 12 (arctan 1/18)) (* 8 (arctan 1/57)) (* -5 (arctan 1/239)))) (tan (+ (* 16 (arctan 1/21)) (* 3 (arctan 1/239)) (* 4 (arctan 3/1042)))) (tan (+ (* 22 (arctan 1/28)) (* 2 (arctan 1/443)) (* -5 (arctan 1/1393)) (* -10 (arctan 1/11018)))) (tan (+ (* 22 (arctan 1/38)) (* 17 (arctan 7/601)) (* 10 (arctan 7/8149)))) (tan (+ (* 44 (arctan 1/57)) (* 7 (arctan 1/239)) (* -12 (arctan 1/682)) (* 24 (arctan 1/12943)))) (tan (+ (* 88 (arctan 1/172)) (* 51 (arctan 1/239)) (* 32 (arctan 1/682)) (* 44 (arctan 1/5357)) (* 68 (arctan 1/12943))))))   (define wrong-formula '(tan (+ (* 88 (arctan 1/172)) (* 51 (arctan 1/239)) (* 32 (arctan 1/682)) (* 44 (arctan 1/5357)) (* 68 (arctan 1/12944)))))   (displayln "Do all correct formulas reduce to 1?") (for/and ([f correct-formulas]) (= 1 (reduce f)))   (displayln "The incorrect formula reduces to:") (reduce wrong-formula)  
http://rosettacode.org/wiki/Check_Machin-like_formulas
Check Machin-like formulas
Machin-like formulas   are useful for efficiently computing numerical approximations for π {\displaystyle \pi } Task Verify the following Machin-like formulas are correct by calculating the value of tan   (right hand side) for each equation using exact arithmetic and showing they equal 1: π 4 = arctan ⁡ 1 2 + arctan ⁡ 1 3 {\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 3}} π 4 = 2 arctan ⁡ 1 3 + arctan ⁡ 1 7 {\displaystyle {\pi \over 4}=2\arctan {1 \over 3}+\arctan {1 \over 7}} π 4 = 4 arctan ⁡ 1 5 − arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 239}} π 4 = 5 arctan ⁡ 1 7 + 2 arctan ⁡ 3 79 {\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+2\arctan {3 \over 79}} π 4 = 5 arctan ⁡ 29 278 + 7 arctan ⁡ 3 79 {\displaystyle {\pi \over 4}=5\arctan {29 \over 278}+7\arctan {3 \over 79}} π 4 = arctan ⁡ 1 2 + arctan ⁡ 1 5 + arctan ⁡ 1 8 {\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 5}+\arctan {1 \over 8}} π 4 = 4 arctan ⁡ 1 5 − arctan ⁡ 1 70 + arctan ⁡ 1 99 {\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 70}+\arctan {1 \over 99}} π 4 = 5 arctan ⁡ 1 7 + 4 arctan ⁡ 1 53 + 2 arctan ⁡ 1 4443 {\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+4\arctan {1 \over 53}+2\arctan {1 \over 4443}} π 4 = 6 arctan ⁡ 1 8 + 2 arctan ⁡ 1 57 + arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=6\arctan {1 \over 8}+2\arctan {1 \over 57}+\arctan {1 \over 239}} π 4 = 8 arctan ⁡ 1 10 − arctan ⁡ 1 239 − 4 arctan ⁡ 1 515 {\displaystyle {\pi \over 4}=8\arctan {1 \over 10}-\arctan {1 \over 239}-4\arctan {1 \over 515}} π 4 = 12 arctan ⁡ 1 18 + 8 arctan ⁡ 1 57 − 5 arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=12\arctan {1 \over 18}+8\arctan {1 \over 57}-5\arctan {1 \over 239}} π 4 = 16 arctan ⁡ 1 21 + 3 arctan ⁡ 1 239 + 4 arctan ⁡ 3 1042 {\displaystyle {\pi \over 4}=16\arctan {1 \over 21}+3\arctan {1 \over 239}+4\arctan {3 \over 1042}} π 4 = 22 arctan ⁡ 1 28 + 2 arctan ⁡ 1 443 − 5 arctan ⁡ 1 1393 − 10 arctan ⁡ 1 11018 {\displaystyle {\pi \over 4}=22\arctan {1 \over 28}+2\arctan {1 \over 443}-5\arctan {1 \over 1393}-10\arctan {1 \over 11018}} π 4 = 22 arctan ⁡ 1 38 + 17 arctan ⁡ 7 601 + 10 arctan ⁡ 7 8149 {\displaystyle {\pi \over 4}=22\arctan {1 \over 38}+17\arctan {7 \over 601}+10\arctan {7 \over 8149}} π 4 = 44 arctan ⁡ 1 57 + 7 arctan ⁡ 1 239 − 12 arctan ⁡ 1 682 + 24 arctan ⁡ 1 12943 {\displaystyle {\pi \over 4}=44\arctan {1 \over 57}+7\arctan {1 \over 239}-12\arctan {1 \over 682}+24\arctan {1 \over 12943}} π 4 = 88 arctan ⁡ 1 172 + 51 arctan ⁡ 1 239 + 32 arctan ⁡ 1 682 + 44 arctan ⁡ 1 5357 + 68 arctan ⁡ 1 12943 {\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12943}} and confirm that the following formula is incorrect by showing   tan   (right hand side)   is not   1: π 4 = 88 arctan ⁡ 1 172 + 51 arctan ⁡ 1 239 + 32 arctan ⁡ 1 682 + 44 arctan ⁡ 1 5357 + 68 arctan ⁡ 1 12944 {\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12944}} These identities are useful in calculating the values: tan ⁡ ( a + b ) = tan ⁡ ( a ) + tan ⁡ ( b ) 1 − tan ⁡ ( a ) tan ⁡ ( b ) {\displaystyle \tan(a+b)={\tan(a)+\tan(b) \over 1-\tan(a)\tan(b)}} tan ⁡ ( arctan ⁡ a b ) = a b {\displaystyle \tan \left(\arctan {a \over b}\right)={a \over b}} tan ⁡ ( − a ) = − tan ⁡ ( a ) {\displaystyle \tan(-a)=-\tan(a)} You can store the equations in any convenient data structure, but for extra credit parse them from human-readable text input. Note: to formally prove the formula correct, it would have to be shown that − 3 p i 4 {\displaystyle {-3pi \over 4}} < right hand side < 5 p i 4 {\displaystyle {5pi \over 4}} due to tan ⁡ ( ) {\displaystyle \tan()} periodicity.
#Raku
Raku
sub taneval ($coef, $f) { return 0 if $coef == 0; return $f if $coef == 1; return -taneval(-$coef, $f) if $coef < 0;   my $a = taneval($coef+>1, $f); my $b = taneval($coef - $coef+>1, $f); ($a+$b)/(1-$a*$b); }   sub tans (@xs) { return taneval(@xs[0;0], @xs[0;1].FatRat) if @xs == 1;   my $a = tans(@xs[0 .. (-1+@xs+>1)]); my $b = tans(@xs[(-1+@xs+>1)+1 .. -1+@xs]); ($a+$b)/(1-$a*$b); }   sub verify (@eqn) { printf "%5s (%s)\n", (tans(@eqn) == 1) ?? "OK" !! "Error", (map { "[{.[0]} {.[1].nude.join('/')}]" }, @eqn).join(' '); }   verify($_) for ([[1,1/2], [1,1/3]], [[2,1/3], [1,1/7]], [[4,1/5], [-1,1/239]], [[5,1/7], [2,3/79]], [[5,29/278], [7,3/79]], [[1,1/2], [1,1/5], [1,1/8]], [[4,1/5], [-1,1/70], [1,1/99]], [[5,1/7], [4,1/53], [2,1/4443]], [[6,1/8], [2,1/57], [1,1/239]], [[8,1/10], [-1,1/239], [-4,1/515]], [[12,1/18], [8,1/57], [-5,1/239]], [[16,1/21], [3,1/239], [4,3/1042]], [[22,1/28], [2,1/443], [-5,1/1393], [-10,1/11018]], [[22,1/38], [17,7/601], [10,7/8149]], [[44,1/57], [7,1/239], [-12,1/682], [24,1/12943]], [[88,1/172], [51,1/239], [32,1/682], [44,1/5357], [68,1/12943]], [[88,1/172], [51,1/239], [32,1/682], [44,1/5357], [68,1/21944]] );
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out the corresponding character.
#CLU
CLU
start_up = proc () po: stream := stream$primary_output()    % To turn a character code into an integer, use char$c2i  % (but then to print it, it needs to be turned into a string first  % with int$unparse) stream$putl(po, int$unparse( char$c2i( 'a' ) ) ) % prints '97'    % To turn an integer into a character code, use char$i2c stream$putc(po, char$i2c( 97 ) );  % prints 'a' end start_up
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out the corresponding character.
#COBOL
COBOL
identification division. program-id. character-codes. remarks. COBOL is an ordinal language, first is 1. remarks. 42nd ASCII code is ")" not, "*". procedure division. display function char(42) display function ord('*') goback. end program character-codes.
http://rosettacode.org/wiki/Cholesky_decomposition
Cholesky decomposition
Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interpreted as a generalized square root of A {\displaystyle A} , as described in Cholesky decomposition. In a 3x3 example, we have to solve the following system of equations: A = ( a 11 a 21 a 31 a 21 a 22 a 32 a 31 a 32 a 33 ) = ( l 11 0 0 l 21 l 22 0 l 31 l 32 l 33 ) ( l 11 l 21 l 31 0 l 22 l 32 0 0 l 33 ) ≡ L L T = ( l 11 2 l 21 l 11 l 31 l 11 l 21 l 11 l 21 2 + l 22 2 l 31 l 21 + l 32 l 22 l 31 l 11 l 31 l 21 + l 32 l 22 l 31 2 + l 32 2 + l 33 2 ) {\displaystyle {\begin{aligned}A&={\begin{pmatrix}a_{11}&a_{21}&a_{31}\\a_{21}&a_{22}&a_{32}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}\\&={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}l_{11}&l_{21}&l_{31}\\0&l_{22}&l_{32}\\0&0&l_{33}\end{pmatrix}}\equiv LL^{T}\\&={\begin{pmatrix}l_{11}^{2}&l_{21}l_{11}&l_{31}l_{11}\\l_{21}l_{11}&l_{21}^{2}+l_{22}^{2}&l_{31}l_{21}+l_{32}l_{22}\\l_{31}l_{11}&l_{31}l_{21}+l_{32}l_{22}&l_{31}^{2}+l_{32}^{2}+l_{33}^{2}\end{pmatrix}}\end{aligned}}} We can see that for the diagonal elements ( l k k {\displaystyle l_{kk}} ) of L {\displaystyle L} there is a calculation pattern: l 11 = a 11 {\displaystyle l_{11}={\sqrt {a_{11}}}} l 22 = a 22 − l 21 2 {\displaystyle l_{22}={\sqrt {a_{22}-l_{21}^{2}}}} l 33 = a 33 − ( l 31 2 + l 32 2 ) {\displaystyle l_{33}={\sqrt {a_{33}-(l_{31}^{2}+l_{32}^{2})}}} or in general: l k k = a k k − ∑ j = 1 k − 1 l k j 2 {\displaystyle l_{kk}={\sqrt {a_{kk}-\sum _{j=1}^{k-1}l_{kj}^{2}}}} For the elements below the diagonal ( l i k {\displaystyle l_{ik}} , where i > k {\displaystyle i>k} ) there is also a calculation pattern: l 21 = 1 l 11 a 21 {\displaystyle l_{21}={\frac {1}{l_{11}}}a_{21}} l 31 = 1 l 11 a 31 {\displaystyle l_{31}={\frac {1}{l_{11}}}a_{31}} l 32 = 1 l 22 ( a 32 − l 31 l 21 ) {\displaystyle l_{32}={\frac {1}{l_{22}}}(a_{32}-l_{31}l_{21})} which can also be expressed in a general formula: l i k = 1 l k k ( a i k − ∑ j = 1 k − 1 l i j l k j ) {\displaystyle l_{ik}={\frac {1}{l_{kk}}}\left(a_{ik}-\sum _{j=1}^{k-1}l_{ij}l_{kj}\right)} Task description The task is to implement a routine which will return a lower Cholesky factor L {\displaystyle L} for every given symmetric, positive definite nxn matrix A {\displaystyle A} . You should then test it on the following two examples and include your output. Example 1: 25 15 -5 5 0 0 15 18 0 --> 3 3 0 -5 0 11 -1 1 3 Example 2: 18 22 54 42 4.24264 0.00000 0.00000 0.00000 22 70 86 62 --> 5.18545 6.56591 0.00000 0.00000 54 86 174 134 12.72792 3.04604 1.64974 0.00000 42 62 134 106 9.89949 1.62455 1.84971 1.39262 Note The Cholesky decomposition of a Pascal upper-triangle matrix is the Identity matrix of the same size. The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
#Maxima
Maxima
/* Cholesky decomposition is built-in */   a: hilbert_matrix(4)$   b: cholesky(a); /* matrix([1, 0, 0, 0 ], [1/2, 1/(2*sqrt(3)), 0, 0 ], [1/3, 1/(2*sqrt(3)), 1/(6*sqrt(5)), 0 ], [1/4, 3^(3/2)/20, 1/(4*sqrt(5)), 1/(20*sqrt(7))]) */   b . transpose(b) - a; matrix([0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0])
http://rosettacode.org/wiki/Cholesky_decomposition
Cholesky decomposition
Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interpreted as a generalized square root of A {\displaystyle A} , as described in Cholesky decomposition. In a 3x3 example, we have to solve the following system of equations: A = ( a 11 a 21 a 31 a 21 a 22 a 32 a 31 a 32 a 33 ) = ( l 11 0 0 l 21 l 22 0 l 31 l 32 l 33 ) ( l 11 l 21 l 31 0 l 22 l 32 0 0 l 33 ) ≡ L L T = ( l 11 2 l 21 l 11 l 31 l 11 l 21 l 11 l 21 2 + l 22 2 l 31 l 21 + l 32 l 22 l 31 l 11 l 31 l 21 + l 32 l 22 l 31 2 + l 32 2 + l 33 2 ) {\displaystyle {\begin{aligned}A&={\begin{pmatrix}a_{11}&a_{21}&a_{31}\\a_{21}&a_{22}&a_{32}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}\\&={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}l_{11}&l_{21}&l_{31}\\0&l_{22}&l_{32}\\0&0&l_{33}\end{pmatrix}}\equiv LL^{T}\\&={\begin{pmatrix}l_{11}^{2}&l_{21}l_{11}&l_{31}l_{11}\\l_{21}l_{11}&l_{21}^{2}+l_{22}^{2}&l_{31}l_{21}+l_{32}l_{22}\\l_{31}l_{11}&l_{31}l_{21}+l_{32}l_{22}&l_{31}^{2}+l_{32}^{2}+l_{33}^{2}\end{pmatrix}}\end{aligned}}} We can see that for the diagonal elements ( l k k {\displaystyle l_{kk}} ) of L {\displaystyle L} there is a calculation pattern: l 11 = a 11 {\displaystyle l_{11}={\sqrt {a_{11}}}} l 22 = a 22 − l 21 2 {\displaystyle l_{22}={\sqrt {a_{22}-l_{21}^{2}}}} l 33 = a 33 − ( l 31 2 + l 32 2 ) {\displaystyle l_{33}={\sqrt {a_{33}-(l_{31}^{2}+l_{32}^{2})}}} or in general: l k k = a k k − ∑ j = 1 k − 1 l k j 2 {\displaystyle l_{kk}={\sqrt {a_{kk}-\sum _{j=1}^{k-1}l_{kj}^{2}}}} For the elements below the diagonal ( l i k {\displaystyle l_{ik}} , where i > k {\displaystyle i>k} ) there is also a calculation pattern: l 21 = 1 l 11 a 21 {\displaystyle l_{21}={\frac {1}{l_{11}}}a_{21}} l 31 = 1 l 11 a 31 {\displaystyle l_{31}={\frac {1}{l_{11}}}a_{31}} l 32 = 1 l 22 ( a 32 − l 31 l 21 ) {\displaystyle l_{32}={\frac {1}{l_{22}}}(a_{32}-l_{31}l_{21})} which can also be expressed in a general formula: l i k = 1 l k k ( a i k − ∑ j = 1 k − 1 l i j l k j ) {\displaystyle l_{ik}={\frac {1}{l_{kk}}}\left(a_{ik}-\sum _{j=1}^{k-1}l_{ij}l_{kj}\right)} Task description The task is to implement a routine which will return a lower Cholesky factor L {\displaystyle L} for every given symmetric, positive definite nxn matrix A {\displaystyle A} . You should then test it on the following two examples and include your output. Example 1: 25 15 -5 5 0 0 15 18 0 --> 3 3 0 -5 0 11 -1 1 3 Example 2: 18 22 54 42 4.24264 0.00000 0.00000 0.00000 22 70 86 62 --> 5.18545 6.56591 0.00000 0.00000 54 86 174 134 12.72792 3.04604 1.64974 0.00000 42 62 134 106 9.89949 1.62455 1.84971 1.39262 Note The Cholesky decomposition of a Pascal upper-triangle matrix is the Identity matrix of the same size. The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
#Nim
Nim
import math, strutils, strformat   type Matrix[N: static int, T: SomeFloat] = array[N, array[N, T]]   proc cholesky[Matrix](a: Matrix): Matrix = for i in 0 ..< a[0].len: for j in 0 .. i: var s = 0.0 for k in 0 ..< j: s += result[i][k] * result[j][k] result[i][j] = if i == j: sqrt(a[i][i]-s) else: 1.0 / result[j][j] * (a[i][j] - s)   proc `$`(a: Matrix): string = result = "" for b in a: var line = "" for c in b: line.addSep(" ", 0) line.add fmt"{c:8.5f}" result.add line & '\n'   let m1 = [[25.0, 15.0, -5.0], [15.0, 18.0, 0.0], [-5.0, 0.0, 11.0]] echo cholesky(m1)   let m2 = [[18.0, 22.0, 54.0, 42.0], [22.0, 70.0, 86.0, 62.0], [54.0, 86.0, 174.0, 134.0], [42.0, 62.0, 134.0, 106.0]] echo cholesky(m2)
http://rosettacode.org/wiki/Cheryl%27s_birthday
Cheryl's birthday
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the   month   of birth,   and Bernard the   day   (of the month)   of birth. 1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too. 2) Bernard: At first I don't know when Cheryl's birthday is, but I know now. 3) Albert: Then I also know when Cheryl's birthday is. Task Write a computer program to deduce, by successive elimination, Cheryl's birthday. Related task Sum and Product Puzzle References Wikipedia article of the same name. Tuple Relational Calculus
#Python
Python
'''Cheryl's Birthday'''   from itertools import groupby from re import split     # main :: IO () def main(): '''Derivation of the date.'''   month, day = 0, 1 print( # (3 :: A "Then I also know") # (A's month contains only one remaining day) uniquePairing(month)( # (2 :: B "I know now") # (B's day is paired with only one remaining month) uniquePairing(day)( # (1 :: A "I know that Bernard does not know") # (A's month is not among those with unique days) monthsWithUniqueDays(False)([ # 0 :: Cheryl's list: tuple(x.split()) for x in split( ', ', 'May 15, May 16, May 19, ' + 'June 17, June 18, ' + 'July 14, July 16, ' + 'Aug 14, Aug 15, Aug 17' ) ]) ) ) )     # ------------------- QUERY FUNCTIONS --------------------   # monthsWithUniqueDays :: Bool -> [(Month, Day)] -> [(Month, Day)] def monthsWithUniqueDays(blnInclude): '''The subset of months with (or without) unique days. ''' def go(xs): month, day = 0, 1 months = [fst(x) for x in uniquePairing(day)(xs)] return [ md for md in xs if blnInclude or not (md[month] in months) ] return go     # uniquePairing :: DatePart -> [(Month, Day)] -> [(Month, Day)] def uniquePairing(i): '''Subset of months (or days) with a unique intersection. ''' def go(xs): def inner(md): dct = md[i] uniques = [ k for k in dct.keys() if 1 == len(dct[k]) ] return [tpl for tpl in xs if tpl[i] in uniques] return inner return ap(bindPairs)(go)     # bindPairs :: [(Month, Day)] -> # ((Dict String [String], Dict String [String]) # -> [(Month, Day)]) -> [(Month, Day)] def bindPairs(xs): '''List monad injection operator for lists of (Month, Day) pairs. ''' return lambda f: f( ( dictFromPairs(xs), dictFromPairs( [(b, a) for (a, b) in xs] ) ) )     # dictFromPairs :: [(Month, Day)] -> Dict Text [Text] def dictFromPairs(xs): '''A dictionary derived from a list of month day pairs. ''' return { k: [snd(x) for x in m] for k, m in groupby( sorted(xs, key=fst), key=fst ) }     # ----------------------- GENERIC ------------------------   # ap :: (a -> b -> c) -> (a -> b) -> a -> c def ap(f): '''Applicative instance for functions. ''' def go(g): def fxgx(x): return f(x)( g(x) ) return fxgx return go     # fst :: (a, b) -> a def fst(tpl): '''First component of a pair. ''' return tpl[0]     # snd :: (a, b) -> b def snd(tpl): '''Second component of a pair. ''' return tpl[1]     if __name__ == '__main__': main()
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
#Maple
Maple
  L1 := [3, 4, 5, 6]; L1 := [3, 4, 5, 6]   L2 := [7, 8, 9]; L2 := [7, 8, 9]  
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
#PicoLisp
PicoLisp
(de comb (M Lst) (cond ((=0 M) '(NIL)) ((not Lst)) (T (conc (mapcar '((Y) (cons (car Lst) Y)) (comb (dec M) (cdr Lst)) ) (comb M (cdr Lst)) ) ) ) )   (comb 3 (1 2 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.
#Simula
Simula
statement::= if conditional_expression then statement else statement if X=Y then K:=I else K:=J statement::= if conditional_expression then statement if X=Y then K:=I
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 {\displaystyle a_{2}} ,   … {\displaystyle \dots } ,   a k {\displaystyle a_{k}} ,   there exists an integer   x {\displaystyle x}   solving the following system of simultaneous congruences: x ≡ a 1 ( mod n 1 ) x ≡ a 2 ( mod n 2 )     ⋮ x ≡ a k ( mod n k ) {\displaystyle {\begin{aligned}x&\equiv a_{1}{\pmod {n_{1}}}\\x&\equiv a_{2}{\pmod {n_{2}}}\\&{}\ \ \vdots \\x&\equiv a_{k}{\pmod {n_{k}}}\end{aligned}}} Furthermore, all solutions   x {\displaystyle x}   of this system are congruent modulo the product,   N = n 1 n 2 … n k {\displaystyle N=n_{1}n_{2}\ldots n_{k}} . Task Write a program to solve a system of linear congruences by applying the   Chinese Remainder Theorem. If the system of equations cannot be solved, your program must somehow indicate this. (It may throw an exception or return a special false value.) Since there are infinitely many solutions, the program should return the unique solution   s {\displaystyle s}   where   0 ≤ s ≤ n 1 n 2 … n k {\displaystyle 0\leq s\leq n_{1}n_{2}\ldots n_{k}} . Show the functionality of this program by printing the result such that the   n {\displaystyle n} 's   are   [ 3 , 5 , 7 ] {\displaystyle [3,5,7]}   and the   a {\displaystyle a} 's   are   [ 2 , 3 , 2 ] {\displaystyle [2,3,2]} . Algorithm:   The following algorithm only applies if the   n i {\displaystyle n_{i}} 's   are pairwise co-prime. Suppose, as above, that a solution is required for the system of congruences: x ≡ a i ( mod n i ) f o r i = 1 , … , k {\displaystyle x\equiv a_{i}{\pmod {n_{i}}}\quad \mathrm {for} \;i=1,\ldots ,k} Again, to begin, the product   N = n 1 n 2 … n k {\displaystyle N=n_{1}n_{2}\ldots n_{k}}   is defined. Then a solution   x {\displaystyle x}   can be found as follows: For each   i {\displaystyle i} ,   the integers   n i {\displaystyle n_{i}}   and   N / n i {\displaystyle N/n_{i}}   are co-prime. Using the   Extended Euclidean algorithm,   we can find integers   r i {\displaystyle r_{i}}   and   s i {\displaystyle s_{i}}   such that   r i n i + s i N / n i = 1 {\displaystyle r_{i}n_{i}+s_{i}N/n_{i}=1} . Then, one solution to the system of simultaneous congruences is: x = ∑ i = 1 k a i s i N / n i {\displaystyle x=\sum _{i=1}^{k}a_{i}s_{i}N/n_{i}} and the minimal solution, x ( mod N ) {\displaystyle x{\pmod {N}}} .
#Kotlin
Kotlin
// version 1.1.2   /* returns x where (a * x) % b == 1 */ fun multInv(a: Int, b: Int): Int { if (b == 1) return 1 var aa = a var bb = b var x0 = 0 var x1 = 1 while (aa > 1) { val q = aa / bb var t = bb bb = aa % bb aa = t t = x0 x0 = x1 - q * x0 x1 = t } if (x1 < 0) x1 += b return x1 }   fun chineseRemainder(n: IntArray, a: IntArray): Int { val prod = n.fold(1) { acc, i -> acc * i } var sum = 0 for (i in 0 until n.size) { val p = prod / n[i] sum += a[i] * multInv(p, n[i]) * p } return sum % prod }   fun main(args: Array<String>) { val n = intArrayOf(3, 5, 7) val a = intArrayOf(2, 3, 2) println(chineseRemainder(n, a)) }
http://rosettacode.org/wiki/Chowla_numbers
Chowla numbers
Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n   is a positive integer The sequence is named after   Sarvadaman D. S. Chowla,   (22 October 1907 ──► 10 December 1995), a London born Indian American mathematician specializing in number theory. German mathematician Carl Friedrich Gauss (1777─1855) said: "Mathematics is the queen of the sciences ─ and number theory is the queen of mathematics". Definitions Chowla numbers can also be expressed as: chowla(n) = sum of divisors of n excluding unity and n chowla(n) = sum( divisors(n)) - 1 - n chowla(n) = sum( properDivisors(n)) - 1 chowla(n) = sum(aliquotDivisors(n)) - 1 chowla(n) = aliquot(n) - 1 chowla(n) = sigma(n) - 1 - n chowla(n) = sigmaProperDivisiors(n) - 1   chowla(a*b) = a + b,   if a and b are distinct primes if chowla(n) = 0,  and n > 1, then n is prime if chowla(n) = n - 1, and n > 1, then n is a perfect number Task   create a   chowla   function that returns the   chowla number   for a positive integer   n   Find and display   (1 per line)   for the 1st   37   integers:   the integer   (the index)   the chowla number for that integer   For finding primes, use the   chowla   function to find values of zero   Find and display the   count   of the primes up to              100   Find and display the   count   of the primes up to           1,000   Find and display the   count   of the primes up to         10,000   Find and display the   count   of the primes up to       100,000   Find and display the   count   of the primes up to    1,000,000   Find and display the   count   of the primes up to  10,000,000   For finding perfect numbers, use the   chowla   function to find values of   n - 1   Find and display all   perfect numbers   up to   35,000,000   use commas within appropriate numbers   show all output here Related tasks   totient function   perfect numbers   Proper divisors   Sieve of Eratosthenes See also   the OEIS entry for   A48050 Chowla's function.
#Scala
Scala
object ChowlaNumbers { def main(args: Array[String]): Unit = { println("Chowla Numbers...") for(n <- 1 to 37){println(s"$n: ${chowlaNum(n)}")} println("\nPrime Counts...") for(i <- (2 to 7).map(math.pow(10, _).toInt)){println(f"$i%,d: ${primesPar(i).size}%,d")} println("\nPerfect Numbers...") print(perfectsPar(35000000).toVector.sorted.zipWithIndex.map{case (n, i) => f"${i + 1}%,d: $n%,d"}.mkString("\n")) }   def primesPar(num: Int): ParVector[Int] = ParVector.range(2, num + 1).filter(n => chowlaNum(n) == 0) def perfectsPar(num: Int): ParVector[Int] = ParVector.range(6, num + 1).filter(n => chowlaNum(n) + 1 == n)   def chowlaNum(num: Int): Int = Iterator.range(2, math.sqrt(num).toInt + 1).filter(n => num%n == 0).foldLeft(0){case (s, n) => if(n*n == num) s + n else s + n + (num/n)} }
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, as a type, has the values and operations of its own. The operations of are usually called methods of the root type. Both operations and values are called polymorphic. A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument. The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual. Operations with multiple arguments and/or the results of the class are called multi-methods. A further generalization of is the operation with arguments and/or results from different classes. single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x). multiple-dispatch languages allow many arguments and/or results to control the dispatch. A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type. This type is sometimes called the most specific type of a [polymorphic] value. The type tag of the value is used in order to resolve the dispatch. The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class. In many OO languages the type of the class of T and T itself are considered equivalent. In some languages they are distinct (like in Ada). When class T and T are equivalent, there is no way to distinguish polymorphic and specific values. Task Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
#Nemerle
Nemerle
public class MyClass { public this() { } // the constructor in Nemerle is always named 'this'   public MyVariable : int { get; set; }   public MyMethod() : void { }   }   def myInstance = MyClass(); // no 'new' keyword needed myInstance.MyVariable = 42; // set MyVariable System.Console.WriteLine($"My variable is $(myInstance.MyVariable)") // get MyVariable
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.
#NetRexx
NetRexx
class ClassExample   properties private -- class scope foo = int   properties public -- publicly visible bar = boolean   properties indirect -- generates bean patterns baz = String()   method main(args=String[]) static -- main method clsex = ClassExample() -- instantiate clsex.foo = 42 clsex.baz = 'forty-two' clsex.bar = 0 -- boolean false clsex.test(clsex.foo) clsex.test(clsex.bar) clsex.test(clsex.baz)   method test(s=int) aap = 1 -- local (stack) variable say s aap   method test(s=String) noot = 2 say s noot   method test(s=boolean) mies = 3 say s mies
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)
#Phix
Phix
with javascript_semantics function bruteForceClosestPair(sequence s) atom {x1,y1} = s[1], {x2,y2} = s[2], dx = x1-x2, dy = y1-y2, mind = dx*dx+dy*dy sequence minp = s[1..2] for i=1 to length(s)-1 do {x1,y1} = s[i] for j=i+1 to length(s) do {x2,y2} = s[j] dx = x1-x2 dx = dx*dx if dx<mind then dy = y1-y2 dx += dy*dy if dx<mind then mind = dx minp = {s[i],s[j]} end if end if end for end for return {sqrt(mind),minp} end function sequence testset = sq_rnd(repeat({1,1},10000)) atom t0 = time() {atom d, sequence points} = bruteForceClosestPair(testset) -- (Sorting the final point pair makes brute/dc more likely to tally. Note however -- when >1 equidistant pairs exist, brute and dc may well return different pairs; -- it is only a problem if they decide to return different minimum distances.) atom {{x1,y1},{x2,y2}} = sort(deep_copy(points)) printf(1,"Closest pair: {%f,%f} {%f,%f}, distance=%f (%3.2fs)\n",{x1,y2,x2,y2,d,time()-t0}) t0 = time() constant X = 1, Y = 2 sequence xP = sort(deep_copy(testset)) function byY(sequence p1, p2) return compare(p1[Y],p2[Y]) end function sequence yP = custom_sort(routine_id("byY"),deep_copy(testset)) function distsq(sequence p1,p2) atom {x1,y1} = p1, {x2,y2} = p2 x1 -= x2 y1 -= y2 return x1*x1 + y1*y1 end function function closestPair(sequence 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) integer N = length(xP), midN = floor(N/2) assert(length(yP)=N) if N<=3 then return bruteForceClosestPair(xP) end if sequence xL = xP[1..midN], xR = xP[midN+1..N], yL = {}, yR = {} atom xm = xP[midN][X] for i=1 to N do if yP[i][X]<=xm then yL = append(yL,yP[i]) else yR = append(yR,yP[i]) end if end for {atom dL, sequence pairL} = closestPair(xL, yL) {atom dR, sequence pairR} = closestPair(xR, yR) {atom dmin, sequence pairMin} = min({dL, pairL},{dR, pairR}) sequence yS = {} for i=1 to length(yP) do if abs(xm-yP[i][X])<dmin then yS = append(yS,yP[i]) end if end for integer nS = length(yS) {atom closest, sequence cPair} = {dmin*dmin, pairMin} for i=1 to nS-1 do integer k = i + 1 while k<=nS and (yS[k][Y]-yS[i][Y])<dmin do d = distsq(yS[k],yS[i]) if d<closest then {closest, cPair} = {d, {yS[k], yS[i]}} end if k += 1 end while end for return {sqrt(closest), cPair} end function {d,points} = closestPair(xP,yP) {{x1,y1},{x2,y2}} = sort(deep_copy(points)) -- (see note above) printf(1,"Closest pair: {%f,%f} {%f,%f}, distance=%f (%3.2fs)\n",{x1,y2,x2,y2,d,time()-t0})
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points
Circles of given radius through two points
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. Exceptions r==0.0 should be treated as never describing circles (except in the case where the points are coincident). If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point. If the points form a diameter then return two identical circles or return a single circle, according to which is the most natural mechanism for the implementation language. If the points are too far apart then no circles can be drawn. Task detail Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, or some indication of special cases where two, possibly equal, circles cannot be returned. Show here the output for the following inputs: p1 p2 r 0.1234, 0.9876 0.8765, 0.2345 2.0 0.0000, 2.0000 0.0000, 0.0000 1.0 0.1234, 0.9876 0.1234, 0.9876 2.0 0.1234, 0.9876 0.8765, 0.2345 0.5 0.1234, 0.9876 0.1234, 0.9876 0.0 Related task   Total circles area. See also   Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
#Liberty_BASIC
Liberty BASIC
  '[RC] Circles of given radius through two points for i = 1 to 5 read x1, y1, x2, y2,r print i;") ";x1, y1, x2, y2,r call twoCircles x1, y1, x2, y2,r next end   'p1 p2 r data 0.1234, 0.9876, 0.8765, 0.2345, 2.0 data 0.0000, 2.0000, 0.0000, 0.0000, 1.0 data 0.1234, 0.9876, 0.1234, 0.9876, 2.0 data 0.1234, 0.9876, 0.8765, 0.2345, 0.5 data 0.1234, 0.9876, 0.1234, 0.9876, 0.0   sub twoCircles x1, y1, x2, y2,r   if x1=x2 and y1=y2 then '2.If the points are coincident if r=0 then ' unless r==0.0 print "It will be a single point (";x1;",";y1;") of radius 0" exit sub else print "There are any number of circles via single point (";x1;",";y1;") of radius ";r exit sub end if end if r2 = sqr((x1-x2)^2+(y1-y2)^2)/2 'half distance between points if r<r2 then print "Points are too far apart (";2*r2;") - there are no circles of radius ";r exit sub end if   'else, calculate two centers cx=(x1+x2)/2 'middle point cy=(y1+y2)/2 'should move from middle point along perpendicular by dd2 dd2=sqr(r^2-r2^2) 'perpendicular distance dx1=x2-cx 'vector to middle point dy1=y2-cy dx = 0-dy1/r2*dd2 'perpendicular: dy = dx1/r2*dd2 'rotate and scale print "(";cx+dy;",";cy+dx;")" 'two points, with (+) print "(";cx-dy;",";cy-dx;")" 'and (-)   end sub  
http://rosettacode.org/wiki/Chinese_zodiac
Chinese zodiac
Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Tuesday, February 1, 2022 CE (in the common Gregorian calendar) will begin the lunisolar Year of the Tiger. The celestial stems have no one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems each belong to one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element's governance is associated with yin, the other with yang. Thus, 2022 is also the yang year of Water. Note that since 12 is an even number, the association between animals and yin/yang doesn't change. Consecutive Years of the Rooster will cycle through the five elements, but will always be yin, despite the apparent conceptual mismatch between the specifically-male English animal name and the female aspect denoted by yin. Task Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year. You may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration). Requisite information The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig. The element cycle runs in this order: Wood, Fire, Earth, Metal, Water. The yang year precedes the yin year within each element. The current 60-year cycle began in 1984 CE; the first cycle of the Common Era began in 4 CE. Thus, 1984 was the year of the Wood Rat (yang), 1985 was the year of the Wood Ox (yin), and 1986 the year of the Fire Tiger (yang); 2022 - which, as already noted, is the year of the Water Tiger (yang) - is the 39th year of the current cycle. Information for optional task The ten celestial stems are 甲 jiă, 乙 yĭ, 丙 bĭng, 丁 dīng, 戊 wù, 己 jĭ, 庚 gēng, 辛 xīn, 壬 rén, and 癸 gŭi. With the ASCII version of Pinyin tones, the names are written "jia3", "yi3", "bing3", "ding1", "wu4", "ji3", "geng1", "xin1", "ren2", and "gui3". The twelve terrestrial branches are 子 zĭ, 丑 chŏu, 寅 yín, 卯 măo, 辰 chén, 巳 sì, 午 wŭ, 未 wèi, 申 shēn, 酉 yŏu, 戌 xū, 亥 hài. In ASCII Pinyin, those are "zi3", "chou3", "yin2", "mao3", "chen2", "si4", "wu3", "wei4", "shen1", "you3", "xu1", and "hai4". Therefore 1984 was 甲子 (jiă-zĭ, or jia3-zi3). 2022 is 壬寅 (rén-yín or ren2-yin2).
#Maple
Maple
  zodiac:=proc(year::integer) local year60,yinyang,animal,element; year60:= (year-3) mod 60; yinyang:=["Yin","Yang"]; animal:=["Pig","Rat","Ox","Tiger","Rabbit","Dragon","Snake","Horse","Goat","Monkey","Rooster","Dog"]; element:=["Water","Wood","Wood","Fire","Fire","Earth","Earth","Metal","Metal","Water"]; return sprintf("%a",cat(year," is the year of the ",element[(year60 mod 10)+1]," ",animal[(year60 mod 12)+1]," (",yinyang[(year60 mod 2)+1],")")); end proc:  
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an unusual filename:   `Abdu'l-Bahá.txt
#Emacs_Lisp
Emacs Lisp
(file-exists-p "input.txt") (file-directory-p "docs") (file-exists-p "/input.txt") (file-directory-p "/docs")
http://rosettacode.org/wiki/Chaos_game
Chaos game
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a starting point at random (preferably inside the triangle).   Then add the next point halfway between the starting point and one of the reference points.   This reference point is chosen at random. After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge. See also The Game of Chaos
#Groovy
Groovy
import javafx.animation.AnimationTimer import javafx.application.Application import javafx.scene.Scene import javafx.scene.layout.Pane import javafx.scene.paint.Color import javafx.scene.shape.Circle import javafx.stage.Stage   class ChaosGame extends Application {   final randomNumberGenerator = new Random()   @Override void start(Stage primaryStage) { primaryStage.title = 'Chaos Game' primaryStage.scene = getScene() primaryStage.show() }   def getScene() { def colors = [Color.RED, Color.GREEN, Color.BLUE]   final width = 640, height = 640, margin = 60 final size = width - 2 * margin   def points = [ new Circle(width / 2, margin, 1, colors[0]), new Circle(margin, size, 1, colors[1]), new Circle(margin + size, size, 1, colors[2]) ]   def pane = new Pane() pane.style = '-fx-background-color: black;' points.each { pane.children.add it }   def currentPoint = new Circle().with { centerX = randomNumberGenerator.nextInt(size - margin) + margin centerY = randomNumberGenerator.nextInt(size - margin) + margin it }   ({   def newPoint = generatePoint(currentPoint, points, colors) pane.children.add newPoint currentPoint = newPoint   } as AnimationTimer).start()   new Scene(pane, width, height) }   def generatePoint(currentPoint, points, colors) { def selection = randomNumberGenerator.nextInt 3 new Circle().with { centerX = (currentPoint.centerX + points[selection].centerX) / 2 centerY = (currentPoint.centerY + points[selection].centerY) / 2 radius = 1 fill = colors[selection] it } }   static main(args) { launch(ChaosGame) } }
http://rosettacode.org/wiki/Chat_server
Chat server
Task Write a server for a minimal text based chat. People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.
#Objeck
Objeck
  use System.IO.Net; use System.Concurrency; use Collection;   bundle Default { class ChatServer { @clients : StringMap; @clients_mutex : ThreadMutex;   New() { @clients := StringMap->New(); @clients_mutex := ThreadMutex->New("clients_mutex"); }   method : ValidLogin(login_name : String, clients : StringMap) ~ Bool { if(clients->Has(login_name)) { return false; };   return true; }   function : Main(args : String[]) ~ Nil { chat_server := ChatServer->New(); chat_server->Run(); }   method : public : Broadcast(message : String, sender : Client) ~ Nil { client_array : Vector; critical(@clients_mutex) { client_array := @clients->GetValues(); }; each(i : client_array) { client := client_array->Get(i)->As(Client); if(client <> sender) { client->Send(message); }; }; }   method : public : Disconnect(sender : Client) ~ Nil { send_name := sender->GetName(); Broadcast("+++ {$send_name} has left +++", sender); critical(@clients_mutex) { @clients->Remove(sender->GetName()); }; sender->Close(); }   method : public : Run() ~ Nil { server := TCPSocketServer->New(4661); if(server->Listen(5)) { while(true) { client_sock := server->Accept(); critical(@clients_mutex) { client_sock->WriteString("login: "); login_name := client_sock->ReadString(); if(ValidLogin(login_name, @clients)) { client := Client->New(login_name, client_sock, @self); @clients->Insert(client->GetName(), client); client->Execute(Nil); } else { client_sock->WriteString("+++ login in use +++\r\n"); client_sock->Close(); }; }; }; }; server->Close(); } }   class Client from Thread { @client_sock : TCPSocket; @server : ChatServer;   New(login_name : String, client_sock : TCPSocket, server : ChatServer) { Parent(login_name); @client_sock := client_sock; @server := server; }   method : public : Close() ~ Nil { @client_sock->Close(); }   method : public : Send(message : String) ~ Nil { if(@client_sock->IsOpen() & message->Size() > 0) { @client_sock->WriteString("{$message}\r\n"); } else { @server->Disconnect(@self); }; }   method : public : Run(param : Base) ~ Nil { client_name := GetName(); @server->Broadcast("+++ {$client_name} has arrived +++", @self);   message := @client_sock->ReadString(); while(message->Size() > 0 & message->Equals("/quit") = false) { @server->Broadcast("{$client_name}> {$message}", @self); message := @client_sock->ReadString(); }; @server->Disconnect(@self); } } }  
http://rosettacode.org/wiki/Check_Machin-like_formulas
Check Machin-like formulas
Machin-like formulas   are useful for efficiently computing numerical approximations for π {\displaystyle \pi } Task Verify the following Machin-like formulas are correct by calculating the value of tan   (right hand side) for each equation using exact arithmetic and showing they equal 1: π 4 = arctan ⁡ 1 2 + arctan ⁡ 1 3 {\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 3}} π 4 = 2 arctan ⁡ 1 3 + arctan ⁡ 1 7 {\displaystyle {\pi \over 4}=2\arctan {1 \over 3}+\arctan {1 \over 7}} π 4 = 4 arctan ⁡ 1 5 − arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 239}} π 4 = 5 arctan ⁡ 1 7 + 2 arctan ⁡ 3 79 {\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+2\arctan {3 \over 79}} π 4 = 5 arctan ⁡ 29 278 + 7 arctan ⁡ 3 79 {\displaystyle {\pi \over 4}=5\arctan {29 \over 278}+7\arctan {3 \over 79}} π 4 = arctan ⁡ 1 2 + arctan ⁡ 1 5 + arctan ⁡ 1 8 {\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 5}+\arctan {1 \over 8}} π 4 = 4 arctan ⁡ 1 5 − arctan ⁡ 1 70 + arctan ⁡ 1 99 {\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 70}+\arctan {1 \over 99}} π 4 = 5 arctan ⁡ 1 7 + 4 arctan ⁡ 1 53 + 2 arctan ⁡ 1 4443 {\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+4\arctan {1 \over 53}+2\arctan {1 \over 4443}} π 4 = 6 arctan ⁡ 1 8 + 2 arctan ⁡ 1 57 + arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=6\arctan {1 \over 8}+2\arctan {1 \over 57}+\arctan {1 \over 239}} π 4 = 8 arctan ⁡ 1 10 − arctan ⁡ 1 239 − 4 arctan ⁡ 1 515 {\displaystyle {\pi \over 4}=8\arctan {1 \over 10}-\arctan {1 \over 239}-4\arctan {1 \over 515}} π 4 = 12 arctan ⁡ 1 18 + 8 arctan ⁡ 1 57 − 5 arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=12\arctan {1 \over 18}+8\arctan {1 \over 57}-5\arctan {1 \over 239}} π 4 = 16 arctan ⁡ 1 21 + 3 arctan ⁡ 1 239 + 4 arctan ⁡ 3 1042 {\displaystyle {\pi \over 4}=16\arctan {1 \over 21}+3\arctan {1 \over 239}+4\arctan {3 \over 1042}} π 4 = 22 arctan ⁡ 1 28 + 2 arctan ⁡ 1 443 − 5 arctan ⁡ 1 1393 − 10 arctan ⁡ 1 11018 {\displaystyle {\pi \over 4}=22\arctan {1 \over 28}+2\arctan {1 \over 443}-5\arctan {1 \over 1393}-10\arctan {1 \over 11018}} π 4 = 22 arctan ⁡ 1 38 + 17 arctan ⁡ 7 601 + 10 arctan ⁡ 7 8149 {\displaystyle {\pi \over 4}=22\arctan {1 \over 38}+17\arctan {7 \over 601}+10\arctan {7 \over 8149}} π 4 = 44 arctan ⁡ 1 57 + 7 arctan ⁡ 1 239 − 12 arctan ⁡ 1 682 + 24 arctan ⁡ 1 12943 {\displaystyle {\pi \over 4}=44\arctan {1 \over 57}+7\arctan {1 \over 239}-12\arctan {1 \over 682}+24\arctan {1 \over 12943}} π 4 = 88 arctan ⁡ 1 172 + 51 arctan ⁡ 1 239 + 32 arctan ⁡ 1 682 + 44 arctan ⁡ 1 5357 + 68 arctan ⁡ 1 12943 {\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12943}} and confirm that the following formula is incorrect by showing   tan   (right hand side)   is not   1: π 4 = 88 arctan ⁡ 1 172 + 51 arctan ⁡ 1 239 + 32 arctan ⁡ 1 682 + 44 arctan ⁡ 1 5357 + 68 arctan ⁡ 1 12944 {\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12944}} These identities are useful in calculating the values: tan ⁡ ( a + b ) = tan ⁡ ( a ) + tan ⁡ ( b ) 1 − tan ⁡ ( a ) tan ⁡ ( b ) {\displaystyle \tan(a+b)={\tan(a)+\tan(b) \over 1-\tan(a)\tan(b)}} tan ⁡ ( arctan ⁡ a b ) = a b {\displaystyle \tan \left(\arctan {a \over b}\right)={a \over b}} tan ⁡ ( − a ) = − tan ⁡ ( a ) {\displaystyle \tan(-a)=-\tan(a)} You can store the equations in any convenient data structure, but for extra credit parse them from human-readable text input. Note: to formally prove the formula correct, it would have to be shown that − 3 p i 4 {\displaystyle {-3pi \over 4}} < right hand side < 5 p i 4 {\displaystyle {5pi \over 4}} due to tan ⁡ ( ) {\displaystyle \tan()} periodicity.
#REXX
REXX
/*REXX program evaluates some Machin─like formulas and verifies their veracity. */ @.=; pi= pi(); numeric digits( length(pi) ) - length(.); numeric fuzz 3 say center(' computing with ' digits() " decimal digits ", 110, '═') @.1 = 'pi/4 = atan(1/2) + atan(1/3)' @.2 = 'pi/4 = 2*atan(1/3) + atan(1/7)' @.3 = 'pi/4 = 4*atan(1/5) - atan(1/239)' @.4 = 'pi/4 = 5*atan(1/7) + 2*atan(3/79)' @.5 = 'pi/4 = 5*atan(29/278) + 7*atan(3/79)' @.6 = 'pi/4 = atan(1/2) + atan(1/5) + atan(1/8)' @.7 = 'pi/4 = 4*atan(1/5) - atan(1/70) + atan(1/99)' @.8 = 'pi/4 = 5*atan(1/7) + 4*atan(1/53) + 2*atan(1/4443)' @.9 = 'pi/4 = 6*atan(1/8) + 2*atan(1/57) + atan(1/239)' @.10= 'pi/4 = 8*atan(1/10) - atan(1/239) - 4*atan(1/515)' @.11= 'pi/4 = 12*atan(1/18) + 8*atan(1/57) - 5*atan(1/239)' @.12= 'pi/4 = 16*atan(1/21) + 3*atan(1/239) + 4*atan(3/1042)' @.13= 'pi/4 = 22*atan(1/28) + 2*atan(1/443) - 5*atan(1/1393) - 10*atan(1/11018)' @.14= 'pi/4 = 22*atan(1/38) + 17*atan(7/601) + 10*atan(7/8149)' @.15= 'pi/4 = 44*atan(1/57) + 7*atan(1/239) - 12*atan(1/682) + 24*atan(1/12943)' @.16= 'pi/4 = 88*atan(1/172) + 51*atan(1/239) + 32*atan(1/682) + 44*atan(1/5357) + 68 *atan(1/12943)' @.17= 'pi/4 = 88*atan(1/172) + 51*atan(1/239) + 32*atan(1/682) + 44*atan(1/5357) + 68 *atan(1/12944)' @.18= 'pi/4 = 88*atan(1/172) + 51*atan(1/239) + 32*atan(1/682) + 44*atan(1/5357) + 67.9999999994*atan(1/12943)'   do j=1 while @.j\=='' /*evaluate each "Machin─like" formulas.*/ interpret 'answer=' @.j /*where REXX does the heavy lifting. */ say right( word( 'bad OK', answer + 1), 3)": " @.j end /*j*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ pi: return 3.141592653589793238462643383279502884197169399375105820974944592307816406286 Acos: procedure; parse arg x; return pi() * .5 - Asin(x) Atan: procedure; arg x; if abs(x)=1 then return pi()/4*sign(x); return Asin(x/sqrt(1+x*x)) /*──────────────────────────────────────────────────────────────────────────────────────*/ Asin: procedure; parse arg x 1 z 1 o 1 p; a=abs(x); aa=a*a if a>=sqrt(2)*.5 then return sign(x) * Acos( sqrt(1 - aa) ) do j=2 by 2 until p=z; p=z; o=o*aa*(j-1)/j; z=z+o/(j+1); end /*j*/; return z /*──────────────────────────────────────────────────────────────────────────────────────*/ sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); m.=9; h=d+6; numeric form numeric digits; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g *.5'e'_ % 2 do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/; return g
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out the corresponding character.
#CoffeeScript
CoffeeScript
console.log 'a'.charCodeAt 0 # 97 console.log String.fromCharCode 97 # a
http://rosettacode.org/wiki/Cholesky_decomposition
Cholesky decomposition
Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interpreted as a generalized square root of A {\displaystyle A} , as described in Cholesky decomposition. In a 3x3 example, we have to solve the following system of equations: A = ( a 11 a 21 a 31 a 21 a 22 a 32 a 31 a 32 a 33 ) = ( l 11 0 0 l 21 l 22 0 l 31 l 32 l 33 ) ( l 11 l 21 l 31 0 l 22 l 32 0 0 l 33 ) ≡ L L T = ( l 11 2 l 21 l 11 l 31 l 11 l 21 l 11 l 21 2 + l 22 2 l 31 l 21 + l 32 l 22 l 31 l 11 l 31 l 21 + l 32 l 22 l 31 2 + l 32 2 + l 33 2 ) {\displaystyle {\begin{aligned}A&={\begin{pmatrix}a_{11}&a_{21}&a_{31}\\a_{21}&a_{22}&a_{32}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}\\&={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}l_{11}&l_{21}&l_{31}\\0&l_{22}&l_{32}\\0&0&l_{33}\end{pmatrix}}\equiv LL^{T}\\&={\begin{pmatrix}l_{11}^{2}&l_{21}l_{11}&l_{31}l_{11}\\l_{21}l_{11}&l_{21}^{2}+l_{22}^{2}&l_{31}l_{21}+l_{32}l_{22}\\l_{31}l_{11}&l_{31}l_{21}+l_{32}l_{22}&l_{31}^{2}+l_{32}^{2}+l_{33}^{2}\end{pmatrix}}\end{aligned}}} We can see that for the diagonal elements ( l k k {\displaystyle l_{kk}} ) of L {\displaystyle L} there is a calculation pattern: l 11 = a 11 {\displaystyle l_{11}={\sqrt {a_{11}}}} l 22 = a 22 − l 21 2 {\displaystyle l_{22}={\sqrt {a_{22}-l_{21}^{2}}}} l 33 = a 33 − ( l 31 2 + l 32 2 ) {\displaystyle l_{33}={\sqrt {a_{33}-(l_{31}^{2}+l_{32}^{2})}}} or in general: l k k = a k k − ∑ j = 1 k − 1 l k j 2 {\displaystyle l_{kk}={\sqrt {a_{kk}-\sum _{j=1}^{k-1}l_{kj}^{2}}}} For the elements below the diagonal ( l i k {\displaystyle l_{ik}} , where i > k {\displaystyle i>k} ) there is also a calculation pattern: l 21 = 1 l 11 a 21 {\displaystyle l_{21}={\frac {1}{l_{11}}}a_{21}} l 31 = 1 l 11 a 31 {\displaystyle l_{31}={\frac {1}{l_{11}}}a_{31}} l 32 = 1 l 22 ( a 32 − l 31 l 21 ) {\displaystyle l_{32}={\frac {1}{l_{22}}}(a_{32}-l_{31}l_{21})} which can also be expressed in a general formula: l i k = 1 l k k ( a i k − ∑ j = 1 k − 1 l i j l k j ) {\displaystyle l_{ik}={\frac {1}{l_{kk}}}\left(a_{ik}-\sum _{j=1}^{k-1}l_{ij}l_{kj}\right)} Task description The task is to implement a routine which will return a lower Cholesky factor L {\displaystyle L} for every given symmetric, positive definite nxn matrix A {\displaystyle A} . You should then test it on the following two examples and include your output. Example 1: 25 15 -5 5 0 0 15 18 0 --> 3 3 0 -5 0 11 -1 1 3 Example 2: 18 22 54 42 4.24264 0.00000 0.00000 0.00000 22 70 86 62 --> 5.18545 6.56591 0.00000 0.00000 54 86 174 134 12.72792 3.04604 1.64974 0.00000 42 62 134 106 9.89949 1.62455 1.84971 1.39262 Note The Cholesky decomposition of a Pascal upper-triangle matrix is the Identity matrix of the same size. The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
#Objeck
Objeck
  class Cholesky { function : Main(args : String[]) ~ Nil { n := 3; m1 := [25.0, 15.0, -5.0, 15.0, 18.0, 0.0, -5.0, 0.0, 11.0]; c1 := Cholesky(m1, n); ShowMatrix(c1, n);   IO.Console->PrintLine();   n := 4; m2 := [18.0, 22.0, 54.0, 42.0, 22.0, 70.0, 86.0, 62.0, 54.0, 86.0, 174.0, 134.0, 42.0, 62.0, 134.0, 106.0]; c2 := Cholesky(m2, n); ShowMatrix(c2, n); }   function : ShowMatrix(A : Float[], n : Int) ~ Nil { for (i := 0; i < n; i+=1;) { for (j := 0; j < n; j+=1;) { IO.Console->Print(A[i * n + j])->Print('\t'); }; IO.Console->PrintLine(); }; }   function : Cholesky(A : Float[], n : Int) ~ Float[] { L := Float->New[n * n];   for (i := 0; i < n; i+=1;) { for (j := 0; j < (i+1); j+=1;) { s := 0.0; for (k := 0; k < j; k+=1;) { s += L[i * n + k] * L[j * n + k]; }; L[i * n + j] := (i = j) ? (A[i * n + i] - s)->SquareRoot() : (1.0 / L[j * n + j] * (A[i * n + j] - s)); }; };   return L; } }  
http://rosettacode.org/wiki/Cheryl%27s_birthday
Cheryl's birthday
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the   month   of birth,   and Bernard the   day   (of the month)   of birth. 1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too. 2) Bernard: At first I don't know when Cheryl's birthday is, but I know now. 3) Albert: Then I also know when Cheryl's birthday is. Task Write a computer program to deduce, by successive elimination, Cheryl's birthday. Related task Sum and Product Puzzle References Wikipedia article of the same name. Tuple Relational Calculus
#R
R
options <- dplyr::tibble(mon = rep(c("May", "June", "July", "August"),times = c(3,2,2,3)), day = c(15, 16, 19, 17, 18, 14, 16, 14, 15, 17))   okMonths <- c() # Albert's first clue - it is a month with no unique day for (i in unique(options$mon)){ if(all(options$day[options$mon == i] %in% options$day[options$mon != i])) {okMonths <- c(okMonths, i)} }   okDays <- c() # Bernard's clue - it is a day that only occurs once in the remaining dates for (i in unique(options$day)){ if(!all(options$mon[options$day == i] %in% options$mon[(options$mon %in% okMonths)])) {okDays <- c(okDays, i)} }   remaining <- options[(options$mon %in% okMonths) & (options$day %in% okDays), ] # Albert's second clue - must be a month with only one un-eliminated date for(i in unique(remaining$mon)){ if(sum(remaining$mon == i) == 1) {print(remaining[remaining$mon == i,])} }
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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Lst = {3, 4, 5, 6} ->{3, 4, 5, 6}   PrependTo[ Lst, 2] ->{2, 3, 4, 5, 6} PrependTo[ Lst, 1] ->{1, 2, 3, 4, 5, 6}   Lst ->{1, 2, 3, 4, 5, 6}   Insert[ Lst, X, 4] ->{1, 2, 3, X, 4, 5, 6}
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
#Pop11
Pop11
define comb(n, m); lvars ress = []; define do_combs(l, m, el_lst); lvars i; if m = 0 then cons(rev(el_lst), ress) -> ress; else for i from l to n - m do do_combs(i + 1, m - 1, cons(i, el_lst)); endfor; endif; enddefine; do_combs(0, m, []); rev(ress); enddefine;   comb(5, 3) ==>
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.
#Slate
Slate
"Conditionals in Slate are really messages sent to Boolean objects. Like Smalltalk. (But the compiler might optimize some cases)" balance > 0 ifTrue: [inform: 'still sitting pretty!'.] ifFalse: [inform: 'No money till payday!'.].
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 {\displaystyle a_{2}} ,   … {\displaystyle \dots } ,   a k {\displaystyle a_{k}} ,   there exists an integer   x {\displaystyle x}   solving the following system of simultaneous congruences: x ≡ a 1 ( mod n 1 ) x ≡ a 2 ( mod n 2 )     ⋮ x ≡ a k ( mod n k ) {\displaystyle {\begin{aligned}x&\equiv a_{1}{\pmod {n_{1}}}\\x&\equiv a_{2}{\pmod {n_{2}}}\\&{}\ \ \vdots \\x&\equiv a_{k}{\pmod {n_{k}}}\end{aligned}}} Furthermore, all solutions   x {\displaystyle x}   of this system are congruent modulo the product,   N = n 1 n 2 … n k {\displaystyle N=n_{1}n_{2}\ldots n_{k}} . Task Write a program to solve a system of linear congruences by applying the   Chinese Remainder Theorem. If the system of equations cannot be solved, your program must somehow indicate this. (It may throw an exception or return a special false value.) Since there are infinitely many solutions, the program should return the unique solution   s {\displaystyle s}   where   0 ≤ s ≤ n 1 n 2 … n k {\displaystyle 0\leq s\leq n_{1}n_{2}\ldots n_{k}} . Show the functionality of this program by printing the result such that the   n {\displaystyle n} 's   are   [ 3 , 5 , 7 ] {\displaystyle [3,5,7]}   and the   a {\displaystyle a} 's   are   [ 2 , 3 , 2 ] {\displaystyle [2,3,2]} . Algorithm:   The following algorithm only applies if the   n i {\displaystyle n_{i}} 's   are pairwise co-prime. Suppose, as above, that a solution is required for the system of congruences: x ≡ a i ( mod n i ) f o r i = 1 , … , k {\displaystyle x\equiv a_{i}{\pmod {n_{i}}}\quad \mathrm {for} \;i=1,\ldots ,k} Again, to begin, the product   N = n 1 n 2 … n k {\displaystyle N=n_{1}n_{2}\ldots n_{k}}   is defined. Then a solution   x {\displaystyle x}   can be found as follows: For each   i {\displaystyle i} ,   the integers   n i {\displaystyle n_{i}}   and   N / n i {\displaystyle N/n_{i}}   are co-prime. Using the   Extended Euclidean algorithm,   we can find integers   r i {\displaystyle r_{i}}   and   s i {\displaystyle s_{i}}   such that   r i n i + s i N / n i = 1 {\displaystyle r_{i}n_{i}+s_{i}N/n_{i}=1} . Then, one solution to the system of simultaneous congruences is: x = ∑ i = 1 k a i s i N / n i {\displaystyle x=\sum _{i=1}^{k}a_{i}s_{i}N/n_{i}} and the minimal solution, x ( mod N ) {\displaystyle x{\pmod {N}}} .
#Lobster
Lobster
import std   def extended_gcd(a, b): var s = 0 var old_s = 1 var t = 1 var old_t = 0 var r = b var old_r = a   while r != 0: let quotient = old_r / r old_r, r = r, old_r - quotient * r old_s, s = s, old_s - quotient * s old_t, t = t, old_t - quotient * t   return old_r, old_s, old_t, t, s   def for2(xs, ys, fun): return for xs.length: fun(xs[_], ys[_])   def crt(xs, ys): let p = reduce(xs): _a * _b var r = 0 for2(xs,ys) x, y: let q = p / x let z,s,_t,_qt,_qs = q.extended_gcd(x) if z != 1: return "ng " + x + " not coprime", 0 if s < 0: r += y * (s + x) * q else: r += y * s * q return "ok", r % p     def print_crt(xs, ys): let msg, res = crt(xs, ys) print(msg + " " + res)   print_crt([3,5,7],[2,3,2]) print_crt([11,12,13],[10,4,12]) print_crt([11,22,19],[10,4,9]) print_crt([100,23],[19,0])  
http://rosettacode.org/wiki/Chowla_numbers
Chowla numbers
Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n   is a positive integer The sequence is named after   Sarvadaman D. S. Chowla,   (22 October 1907 ──► 10 December 1995), a London born Indian American mathematician specializing in number theory. German mathematician Carl Friedrich Gauss (1777─1855) said: "Mathematics is the queen of the sciences ─ and number theory is the queen of mathematics". Definitions Chowla numbers can also be expressed as: chowla(n) = sum of divisors of n excluding unity and n chowla(n) = sum( divisors(n)) - 1 - n chowla(n) = sum( properDivisors(n)) - 1 chowla(n) = sum(aliquotDivisors(n)) - 1 chowla(n) = aliquot(n) - 1 chowla(n) = sigma(n) - 1 - n chowla(n) = sigmaProperDivisiors(n) - 1   chowla(a*b) = a + b,   if a and b are distinct primes if chowla(n) = 0,  and n > 1, then n is prime if chowla(n) = n - 1, and n > 1, then n is a perfect number Task   create a   chowla   function that returns the   chowla number   for a positive integer   n   Find and display   (1 per line)   for the 1st   37   integers:   the integer   (the index)   the chowla number for that integer   For finding primes, use the   chowla   function to find values of zero   Find and display the   count   of the primes up to              100   Find and display the   count   of the primes up to           1,000   Find and display the   count   of the primes up to         10,000   Find and display the   count   of the primes up to       100,000   Find and display the   count   of the primes up to    1,000,000   Find and display the   count   of the primes up to  10,000,000   For finding perfect numbers, use the   chowla   function to find values of   n - 1   Find and display all   perfect numbers   up to   35,000,000   use commas within appropriate numbers   show all output here Related tasks   totient function   perfect numbers   Proper divisors   Sieve of Eratosthenes See also   the OEIS entry for   A48050 Chowla's function.
#Swift
Swift
import Foundation   @inlinable public func chowla<T: BinaryInteger>(n: T) -> T { stride(from: 2, to: T(Double(n).squareRoot()+1), by: 1) .lazy .filter({ n % $0 == 0 }) .reduce(0, {(s: T, m: T) in m*m == n ? s + m : s + m + (n / m) }) }   extension Dictionary where Key == ClosedRange<Int> { subscript(n: Int) -> Value { get { guard let key = keys.first(where: { $0.contains(n) }) else { fatalError("dict does not contain range for \(n)") }   return self[key]! }   set { guard let key = keys.first(where: { $0.contains(n) }) else { fatalError("dict does not contain range for \(n)") }   self[key] = newValue } } }   let lock = DispatchSemaphore(value: 1)   var perfect = [Int]() var primeCounts = [ 1...100: 0, 101...1_000: 0, 1_001...10_000: 0, 10_001...100_000: 0, 100_001...1_000_000: 0, 1_000_001...10_000_000: 0 ]   for i in 1...37 { print("chowla(\(i)) = \(chowla(n: i))") }   DispatchQueue.concurrentPerform(iterations: 35_000_000) {i in let chowled = chowla(n: i)   if chowled == 0 && i > 1 && i < 10_000_000 { lock.wait() primeCounts[i] += 1 lock.signal() }   if chowled == i - 1 && i > 1 { lock.wait() perfect.append(i) lock.signal() } }   let numPrimes = primeCounts .sorted(by: { $0.key.lowerBound < $1.key.lowerBound }) .reduce(into: [(Int, Int)](), {counts, oneCount in guard !counts.isEmpty else { counts.append((oneCount.key.upperBound, oneCount.value))   return }   counts.append((oneCount.key.upperBound, counts.last!.1 + oneCount.value)) })   for (upper, count) in numPrimes { print("Number of primes < \(upper) = \(count)") }   for p in perfect { print("\(p) is a perfect number") }  
http://rosettacode.org/wiki/Chowla_numbers
Chowla numbers
Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n   is a positive integer The sequence is named after   Sarvadaman D. S. Chowla,   (22 October 1907 ──► 10 December 1995), a London born Indian American mathematician specializing in number theory. German mathematician Carl Friedrich Gauss (1777─1855) said: "Mathematics is the queen of the sciences ─ and number theory is the queen of mathematics". Definitions Chowla numbers can also be expressed as: chowla(n) = sum of divisors of n excluding unity and n chowla(n) = sum( divisors(n)) - 1 - n chowla(n) = sum( properDivisors(n)) - 1 chowla(n) = sum(aliquotDivisors(n)) - 1 chowla(n) = aliquot(n) - 1 chowla(n) = sigma(n) - 1 - n chowla(n) = sigmaProperDivisiors(n) - 1   chowla(a*b) = a + b,   if a and b are distinct primes if chowla(n) = 0,  and n > 1, then n is prime if chowla(n) = n - 1, and n > 1, then n is a perfect number Task   create a   chowla   function that returns the   chowla number   for a positive integer   n   Find and display   (1 per line)   for the 1st   37   integers:   the integer   (the index)   the chowla number for that integer   For finding primes, use the   chowla   function to find values of zero   Find and display the   count   of the primes up to              100   Find and display the   count   of the primes up to           1,000   Find and display the   count   of the primes up to         10,000   Find and display the   count   of the primes up to       100,000   Find and display the   count   of the primes up to    1,000,000   Find and display the   count   of the primes up to  10,000,000   For finding perfect numbers, use the   chowla   function to find values of   n - 1   Find and display all   perfect numbers   up to   35,000,000   use commas within appropriate numbers   show all output here Related tasks   totient function   perfect numbers   Proper divisors   Sieve of Eratosthenes See also   the OEIS entry for   A48050 Chowla's function.
#Visual_Basic
Visual Basic
Option Explicit   Private Declare Function AllocConsole Lib "kernel32.dll" () As Long Private Declare Function FreeConsole Lib "kernel32.dll" () As Long Dim mStdOut As Scripting.TextStream   Function chowla(ByVal n As Long) As Long Dim j As Long, i As Long i = 2 Do While i * i <= n j = n \ i If n Mod i = 0 Then chowla = chowla + i If i <> j Then chowla = chowla + j End If End If i = i + 1 Loop End Function   Function sieve(ByVal limit As Long) As Boolean() Dim c() As Boolean Dim i As Long Dim j As Long i = 3 ReDim c(limit - 1) Do While i * 3 < limit If Not c(i) Then If (chowla(i) = 0) Then j = 3 * i Do While j < limit c(j) = True j = j + 2 * i Loop End If End If i = i + 2 Loop sieve = c() End Function   Sub Display(ByVal s As String) Debug.Print s mStdOut.Write s & vbNewLine End Sub   Sub Main() Dim i As Long Dim count As Long Dim limit As Long Dim power As Long Dim c() As Boolean Dim p As Long Dim k As Long Dim kk As Long Dim s As String * 30 Dim mFSO As Scripting.FileSystemObject Dim mStdIn As Scripting.TextStream   AllocConsole Set mFSO = New Scripting.FileSystemObject Set mStdIn = mFSO.GetStandardStream(StdIn) Set mStdOut = mFSO.GetStandardStream(StdOut)   For i = 1 To 37 Display "chowla(" & i & ")=" & chowla(i) Next i   count = 1 limit = 10000000 power = 100 c = sieve(limit)   For i = 3 To limit - 1 Step 2 If Not c(i) Then count = count + 1 End If If i = power - 1 Then RSet s = FormatNumber(power, 0, vbUseDefault, vbUseDefault, True) Display "Count of primes up to " & s & " = " & FormatNumber(count, 0, vbUseDefault, vbUseDefault, True) power = power * 10 End If Next i   count = 0: limit = 35000000 k = 2: kk = 3   Do p = k * kk If p > limit Then Exit Do End If   If chowla(p) = p - 1 Then RSet s = FormatNumber(p, 0, vbUseDefault, vbUseDefault, True) Display s & " is a number that is perfect" count = count + 1 End If k = kk + 1 kk = kk + k Loop   Display "There are " & CStr(count) & " perfect numbers <= 35.000.000"   mStdOut.Write "press enter to quit program." mStdIn.Read 1   FreeConsole   End Sub
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, as a type, has the values and operations of its own. The operations of are usually called methods of the root type. Both operations and values are called polymorphic. A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument. The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual. Operations with multiple arguments and/or the results of the class are called multi-methods. A further generalization of is the operation with arguments and/or results from different classes. single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x). multiple-dispatch languages allow many arguments and/or results to control the dispatch. A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type. This type is sometimes called the most specific type of a [polymorphic] value. The type tag of the value is used in order to resolve the dispatch. The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class. In many OO languages the type of the class of T and T itself are considered equivalent. In some languages they are distinct (like in Ada). When class T and T are equivalent, there is no way to distinguish polymorphic and specific values. Task Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
#Nim
Nim
type MyClass = object name: int   proc initMyClass(): MyClass = result.name = 2   proc someMethod(m: var MyClass) = m.name = 1   var mc = initMyClass() mc.someMethod()   type Gender = enum male, female, other   MyOtherClass = object name: string gender: Gender age: Natural   proc initMyOtherClass(name; gender = female; age = 50): auto = MyOtherClass(name: name, gender: gender, age: age)   var person1 = initMyOtherClass("Jane") echo person1.name, " ", person1.gender, " ", person1.age # Jane female 50 var person2 = initMyOtherClass("John", male, 23) echo person2.name, " ", person2.gender, " ", person2.age # John male 23
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)
#PicoLisp
PicoLisp
(de closestPairBF (Lst) (let Min T (use (Pt1 Pt2) (for P Lst (for Q Lst (or (== P Q) (>= (setq N (let (A (- (car P) (car Q)) B (- (cdr P) (cdr Q))) (+ (* A A) (* B B)) ) ) Min ) (setq Min N Pt1 P Pt2 Q) ) ) ) (list Pt1 Pt2 (sqrt Min)) ) ) )
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points
Circles of given radius through two points
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. Exceptions r==0.0 should be treated as never describing circles (except in the case where the points are coincident). If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point. If the points form a diameter then return two identical circles or return a single circle, according to which is the most natural mechanism for the implementation language. If the points are too far apart then no circles can be drawn. Task detail Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, or some indication of special cases where two, possibly equal, circles cannot be returned. Show here the output for the following inputs: p1 p2 r 0.1234, 0.9876 0.8765, 0.2345 2.0 0.0000, 2.0000 0.0000, 0.0000 1.0 0.1234, 0.9876 0.1234, 0.9876 2.0 0.1234, 0.9876 0.8765, 0.2345 0.5 0.1234, 0.9876 0.1234, 0.9876 0.0 Related task   Total circles area. See also   Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
#Lua
Lua
function distance(p1, p2) local dx = (p1.x-p2.x) local dy = (p1.y-p2.y) return math.sqrt(dx*dx + dy*dy) end   function findCircles(p1, p2, radius) local seperation = distance(p1, p2) if seperation == 0.0 then if radius == 0.0 then print("No circles can be drawn through ("..p1.x..", "..p1.y..")") else print("Infinitely many circles can be drawn through ("..p1.x..", "..p1.y..")") end elseif seperation == 2*radius then local cx = (p1.x+p2.x)/2 local cy = (p1.y+p2.y)/2 print("Given points are opposite ends of a diameter of the circle with center ("..cx..", "..cy..") and radius "..radius) elseif seperation > 2*radius then print("Given points are further away from each other than a diameter of a circle with radius "..radius) else local mirrorDistance = math.sqrt(math.pow(radius,2) - math.pow(seperation/2,2)) local dx = p2.x - p1.x local dy = p1.y - p2.y local ax = (p1.x + p2.x) / 2 local ay = (p1.y + p2.y) / 2 local mx = mirrorDistance * dx / seperation local my = mirrorDistance * dy / seperation c1 = {x=ax+my, y=ay+mx} c2 = {x=ax-my, y=ay-mx}   print("Two circles are possible.") print("Circle C1 with center ("..c1.x..", "..c1.y.."), radius "..radius) print("Circle C2 with center ("..c2.x..", "..c2.y.."), radius "..radius) end print() end   cases = { {x=0.1234, y=0.9876}, {x=0.8765, y=0.2345}, {x=0.0000, y=2.0000}, {x=0.0000, y=0.0000}, {x=0.1234, y=0.9876}, {x=0.1234, y=0.9876}, {x=0.1234, y=0.9876}, {x=0.8765, y=0.2345}, {x=0.1234, y=0.9876}, {x=0.1234, y=0.9876} } radii = { 2.0, 1.0, 2.0, 0.5, 0.0 } for i=1, #radii do print("Case "..i) findCircles(cases[i*2-1], cases[i*2], radii[i]) end
http://rosettacode.org/wiki/Chinese_zodiac
Chinese zodiac
Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Tuesday, February 1, 2022 CE (in the common Gregorian calendar) will begin the lunisolar Year of the Tiger. The celestial stems have no one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems each belong to one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element's governance is associated with yin, the other with yang. Thus, 2022 is also the yang year of Water. Note that since 12 is an even number, the association between animals and yin/yang doesn't change. Consecutive Years of the Rooster will cycle through the five elements, but will always be yin, despite the apparent conceptual mismatch between the specifically-male English animal name and the female aspect denoted by yin. Task Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year. You may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration). Requisite information The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig. The element cycle runs in this order: Wood, Fire, Earth, Metal, Water. The yang year precedes the yin year within each element. The current 60-year cycle began in 1984 CE; the first cycle of the Common Era began in 4 CE. Thus, 1984 was the year of the Wood Rat (yang), 1985 was the year of the Wood Ox (yin), and 1986 the year of the Fire Tiger (yang); 2022 - which, as already noted, is the year of the Water Tiger (yang) - is the 39th year of the current cycle. Information for optional task The ten celestial stems are 甲 jiă, 乙 yĭ, 丙 bĭng, 丁 dīng, 戊 wù, 己 jĭ, 庚 gēng, 辛 xīn, 壬 rén, and 癸 gŭi. With the ASCII version of Pinyin tones, the names are written "jia3", "yi3", "bing3", "ding1", "wu4", "ji3", "geng1", "xin1", "ren2", and "gui3". The twelve terrestrial branches are 子 zĭ, 丑 chŏu, 寅 yín, 卯 măo, 辰 chén, 巳 sì, 午 wŭ, 未 wèi, 申 shēn, 酉 yŏu, 戌 xū, 亥 hài. In ASCII Pinyin, those are "zi3", "chou3", "yin2", "mao3", "chen2", "si4", "wu3", "wei4", "shen1", "you3", "xu1", and "hai4". Therefore 1984 was 甲子 (jiă-zĭ, or jia3-zi3). 2022 is 壬寅 (rén-yín or ren2-yin2).
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
pinyin = <|"甲" -> "jiă", "乙" -> "yĭ", "丙" -> "bĭng", "丁" -> "dīng", "戊" -> "wù", "己" -> "jĭ", "庚" -> "gēng", "辛" -> "xīn", "壬" -> "rén", "癸" -> "gŭi", "子" -> "zĭ", "丑" -> "chŏu", "寅" -> "yín", "卯" -> "măo", "辰" -> "chén", "巳" -> "sì", "午" -> "wŭ", "未" -> "wèi", "申" -> "shēn", "酉" -> "yŏu", "戌" -> "xū", "亥" -> "hài"|>; animals = {"Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"}; elements = {"Wood", "Fire", "Earth", "Metal", "Water"}; celestial = {"甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"}; terrestrial = {"子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"}; aspects = {"yang", "yin"}; ClearAll[calculate] calculate[year_] := Module[{BASE, cycleyear, stemnumber, stempinyin, element, elementnumber, branchnumber, branchhan, branchpinyin, animal, aspectnumber, aspect, stemhan}, BASE = 4; cycleyear = year - BASE; stemnumber = Mod[cycleyear + 1, 10, 1]; stemhan = celestial[[stemnumber]]; stempinyin = pinyin[[stemhan]]; elementnumber = Floor[stemnumber/2 + 1/2]; element = elements[[elementnumber]]; branchnumber = Mod[cycleyear + 1, 12, 1]; branchhan = terrestrial[[branchnumber]]; branchpinyin = pinyin[[branchhan]]; animal = animals[[branchnumber]]; aspectnumber = Mod[cycleyear + 1, 2, 1]; aspect = aspects[[aspectnumber]]; Row@{year, ": ", stemhan, branchhan, " (", stempinyin, "-", branchpinyin, ", ", element, " ", animal, "; ", aspect, ")"} ] calculate[1935] calculate[1938] calculate[1941] calculate[1947] calculate[1968] calculate[1972] calculate[1976]
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an unusual filename:   `Abdu'l-Bahá.txt
#Erlang
Erlang
#!/usr/bin/escript existence( true ) ->"exists"; existence( false ) ->"does not exist".   print_result(Type, Name, Flag) -> io:fwrite( "~s ~s ~s~n", [Type, Name, existence(Flag)] ).     main(_) -> print_result( "File", "input.txt", filelib:is_regular("input.txt") ), print_result( "Directory", "docs", filelib:is_dir("docs") ), print_result( "File", "/input.txt", filelib:is_regular("/input.txt") ), print_result( "Directory", "/docs", filelib:is_dir("/docs") ).  
http://rosettacode.org/wiki/Chaos_game
Chaos game
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a starting point at random (preferably inside the triangle).   Then add the next point halfway between the starting point and one of the reference points.   This reference point is chosen at random. After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge. See also The Game of Chaos
#Haskell
Haskell
import Control.Monad (replicateM) import Control.Monad.Random (fromList)   type Point = (Float,Float) type Transformations = [(Point -> Point, Float)] -- weighted transformations   -- realization of the game for given transformations gameOfChaos :: MonadRandom m => Int -> Transformations -> Point -> m [Point] gameOfChaos n transformations x = iterateA (fromList transformations) x where iterateA f x = scanr ($) x <$> replicateM n f
http://rosettacode.org/wiki/Chat_server
Chat server
Task Write a server for a minimal text based chat. People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.
#Ol
Ol
  (define (timestamp) (syscall 201 "%c"))   (fork-server 'chat-room (lambda () (let this ((visitors #empty)) (let* ((envelope (wait-mail)) (sender msg envelope)) (case msg (['join who name] (let ((visitors (put visitors who name))) (for-each (lambda (who) (print-to (car who) name " joined to as")) (ff->alist visitors)) (this visitors))) (['talk message] (for-each (lambda (who) (print-to (car who) (cdr who) ": " message)) (ff->alist visitors)) (this visitors)) (['part who] (for-each (lambda (who) (print-to (car who) (visitors (car who) "unknown") " leaved")) (ff->alist visitors)) (let ((visitors (del visitors who))) (this visitors))))))))     (define (on-accept name fd) (lambda () (print "# " (timestamp) "> we got new visitor: " name) (mail 'chat-room ['join fd name])   (let*((ss1 ms1 (clock))) (let loop ((str #null) (stream (force (port->bytestream fd)))) (cond ((null? stream) #false) ((function? stream) (mail 'chat-room ['talk (list->string (reverse str))]) (loop #null (force stream))) (else (loop (cons (car stream) str) (cdr stream))))) (syscall 3 fd) (let*((ss2 ms2 (clock))) (print "# " (timestamp) "> visitor leave us. It takes " (+ (* (- ss2 ss1) 1000) (- ms2 ms1)) "ms."))) (mail 'chat-room ['part fd]) ))   (define (run port) (let ((socket (syscall 41))) ; bind (let loop ((port port)) (if (not (syscall 49 socket port)) ; bind (loop (+ port 2)) (print "Server binded to " port))) ; listen (if (not (syscall 50 socket)) ; listen (shutdown (print "Can't listen")))   ; accept (let loop () (if (syscall 23 socket) ; select (let ((fd (syscall 43 socket))) ; accept ;(print "\n# " (timestamp) ": new request from " (syscall 51 fd)) (fork (on-accept (syscall 51 fd) fd)))) (sleep 0) (loop))))   (run 8080)  
http://rosettacode.org/wiki/Check_Machin-like_formulas
Check Machin-like formulas
Machin-like formulas   are useful for efficiently computing numerical approximations for π {\displaystyle \pi } Task Verify the following Machin-like formulas are correct by calculating the value of tan   (right hand side) for each equation using exact arithmetic and showing they equal 1: π 4 = arctan ⁡ 1 2 + arctan ⁡ 1 3 {\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 3}} π 4 = 2 arctan ⁡ 1 3 + arctan ⁡ 1 7 {\displaystyle {\pi \over 4}=2\arctan {1 \over 3}+\arctan {1 \over 7}} π 4 = 4 arctan ⁡ 1 5 − arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 239}} π 4 = 5 arctan ⁡ 1 7 + 2 arctan ⁡ 3 79 {\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+2\arctan {3 \over 79}} π 4 = 5 arctan ⁡ 29 278 + 7 arctan ⁡ 3 79 {\displaystyle {\pi \over 4}=5\arctan {29 \over 278}+7\arctan {3 \over 79}} π 4 = arctan ⁡ 1 2 + arctan ⁡ 1 5 + arctan ⁡ 1 8 {\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 5}+\arctan {1 \over 8}} π 4 = 4 arctan ⁡ 1 5 − arctan ⁡ 1 70 + arctan ⁡ 1 99 {\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 70}+\arctan {1 \over 99}} π 4 = 5 arctan ⁡ 1 7 + 4 arctan ⁡ 1 53 + 2 arctan ⁡ 1 4443 {\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+4\arctan {1 \over 53}+2\arctan {1 \over 4443}} π 4 = 6 arctan ⁡ 1 8 + 2 arctan ⁡ 1 57 + arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=6\arctan {1 \over 8}+2\arctan {1 \over 57}+\arctan {1 \over 239}} π 4 = 8 arctan ⁡ 1 10 − arctan ⁡ 1 239 − 4 arctan ⁡ 1 515 {\displaystyle {\pi \over 4}=8\arctan {1 \over 10}-\arctan {1 \over 239}-4\arctan {1 \over 515}} π 4 = 12 arctan ⁡ 1 18 + 8 arctan ⁡ 1 57 − 5 arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=12\arctan {1 \over 18}+8\arctan {1 \over 57}-5\arctan {1 \over 239}} π 4 = 16 arctan ⁡ 1 21 + 3 arctan ⁡ 1 239 + 4 arctan ⁡ 3 1042 {\displaystyle {\pi \over 4}=16\arctan {1 \over 21}+3\arctan {1 \over 239}+4\arctan {3 \over 1042}} π 4 = 22 arctan ⁡ 1 28 + 2 arctan ⁡ 1 443 − 5 arctan ⁡ 1 1393 − 10 arctan ⁡ 1 11018 {\displaystyle {\pi \over 4}=22\arctan {1 \over 28}+2\arctan {1 \over 443}-5\arctan {1 \over 1393}-10\arctan {1 \over 11018}} π 4 = 22 arctan ⁡ 1 38 + 17 arctan ⁡ 7 601 + 10 arctan ⁡ 7 8149 {\displaystyle {\pi \over 4}=22\arctan {1 \over 38}+17\arctan {7 \over 601}+10\arctan {7 \over 8149}} π 4 = 44 arctan ⁡ 1 57 + 7 arctan ⁡ 1 239 − 12 arctan ⁡ 1 682 + 24 arctan ⁡ 1 12943 {\displaystyle {\pi \over 4}=44\arctan {1 \over 57}+7\arctan {1 \over 239}-12\arctan {1 \over 682}+24\arctan {1 \over 12943}} π 4 = 88 arctan ⁡ 1 172 + 51 arctan ⁡ 1 239 + 32 arctan ⁡ 1 682 + 44 arctan ⁡ 1 5357 + 68 arctan ⁡ 1 12943 {\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12943}} and confirm that the following formula is incorrect by showing   tan   (right hand side)   is not   1: π 4 = 88 arctan ⁡ 1 172 + 51 arctan ⁡ 1 239 + 32 arctan ⁡ 1 682 + 44 arctan ⁡ 1 5357 + 68 arctan ⁡ 1 12944 {\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12944}} These identities are useful in calculating the values: tan ⁡ ( a + b ) = tan ⁡ ( a ) + tan ⁡ ( b ) 1 − tan ⁡ ( a ) tan ⁡ ( b ) {\displaystyle \tan(a+b)={\tan(a)+\tan(b) \over 1-\tan(a)\tan(b)}} tan ⁡ ( arctan ⁡ a b ) = a b {\displaystyle \tan \left(\arctan {a \over b}\right)={a \over b}} tan ⁡ ( − a ) = − tan ⁡ ( a ) {\displaystyle \tan(-a)=-\tan(a)} You can store the equations in any convenient data structure, but for extra credit parse them from human-readable text input. Note: to formally prove the formula correct, it would have to be shown that − 3 p i 4 {\displaystyle {-3pi \over 4}} < right hand side < 5 p i 4 {\displaystyle {5pi \over 4}} due to tan ⁡ ( ) {\displaystyle \tan()} periodicity.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "bigint.s7i"; include "bigrat.s7i";   const type: mTerms is array array bigInteger;   const array mTerms: testCases is [] ( [] ([] ( 1_, 1_, 2_), [] ( 1_, 1_, 3_)), [] ([] ( 2_, 1_, 3_), [] ( 1_, 1_, 7_)), [] ([] ( 4_, 1_, 5_), [] (-1_, 1_, 239_)), [] ([] ( 5_, 1_, 7_), [] ( 2_, 3_, 79_)), [] ([] ( 1_, 1_, 2_), [] ( 1_, 1_, 5_), [] ( 1_, 1_, 8_)), [] ([] ( 4_, 1_, 5_), [] (-1_, 1_, 70_), [] ( 1_, 1_, 99_)), [] ([] ( 5_, 1_, 7_), [] ( 4_, 1_, 53_), [] ( 2_, 1_, 4443_)), [] ([] ( 6_, 1_, 8_), [] ( 2_, 1_, 57_), [] ( 1_, 1_, 239_)), [] ([] ( 8_, 1_, 10_), [] (-1_, 1_, 239_), [] ( -4_, 1_, 515_)), [] ([] (12_, 1_, 18_), [] ( 8_, 1_, 57_), [] ( -5_, 1_, 239_)), [] ([] (16_, 1_, 21_), [] ( 3_, 1_, 239_), [] ( 4_, 3_, 1042_)), [] ([] (22_, 1_, 28_), [] ( 2_, 1_, 443_), [] ( -5_, 1_, 1393_), [] (-10_, 1_, 11018_)), [] ([] (22_, 1_, 38_), [] (17_, 7_, 601_), [] ( 10_, 7_, 8149_)), [] ([] (44_, 1_, 57_), [] ( 7_, 1_, 239_), [] (-12_, 1_, 682_), [] ( 24_, 1_, 12943_)), [] ([] (88_, 1_, 172_), [] (51_, 1_, 239_), [] ( 32_, 1_, 682_), [] ( 44_, 1_, 5357_), [] (68_, 1_, 12943_)), [] ([] (88_, 1_, 172_), [] (51_, 1_, 239_), [] ( 32_, 1_, 682_), [] ( 44_, 1_, 5357_), [] (68_, 1_, 12944_)) );   const func bigRational: tanEval (in bigInteger: coef, in bigRational: f) is func result var bigRational: tanEval is bigRational.value; local var bigRational: a is bigRational.value; var bigRational: b is bigRational.value; begin if coef = 1_ then tanEval := f; elsif coef < 0_ then tanEval := -tanEval(-coef, f); else a := tanEval(coef div 2_, f); b := tanEval(coef - coef div 2_, f); tanEval := (a + b) / (1_/1_ - a * b); end if; end func;   const func bigRational: tans (in mTerms: terms) is func result var bigRational: tans is bigRational.value; local var bigRational: a is bigRational.value; var bigRational: b is bigRational.value; begin if length(terms) = 1 then tans := tanEval(terms[1][1], terms[1][2] / terms[1][3]); else a := tans(terms[.. length(terms) div 2]); b := tans(terms[succ(length(terms) div 2) ..]); tans := (a + b) / (1_/1_ - a * b); end if; end func;   const proc: main is func local var integer: index is 0; var array bigInteger: term is 0 times 0_; begin for key index range testCases do write(tans(testCases[index]) = 1_/1_ <& ": pi/4 = "); for term range testCases[index] do write([0] ("+", "-")[ord(term[1] < 0_)] <& abs(term[1]) <& "*arctan(" <& term[2] <& "/" <& term[3] <& ")"); end for; writeln; end for; end func;
http://rosettacode.org/wiki/Check_Machin-like_formulas
Check Machin-like formulas
Machin-like formulas   are useful for efficiently computing numerical approximations for π {\displaystyle \pi } Task Verify the following Machin-like formulas are correct by calculating the value of tan   (right hand side) for each equation using exact arithmetic and showing they equal 1: π 4 = arctan ⁡ 1 2 + arctan ⁡ 1 3 {\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 3}} π 4 = 2 arctan ⁡ 1 3 + arctan ⁡ 1 7 {\displaystyle {\pi \over 4}=2\arctan {1 \over 3}+\arctan {1 \over 7}} π 4 = 4 arctan ⁡ 1 5 − arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 239}} π 4 = 5 arctan ⁡ 1 7 + 2 arctan ⁡ 3 79 {\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+2\arctan {3 \over 79}} π 4 = 5 arctan ⁡ 29 278 + 7 arctan ⁡ 3 79 {\displaystyle {\pi \over 4}=5\arctan {29 \over 278}+7\arctan {3 \over 79}} π 4 = arctan ⁡ 1 2 + arctan ⁡ 1 5 + arctan ⁡ 1 8 {\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 5}+\arctan {1 \over 8}} π 4 = 4 arctan ⁡ 1 5 − arctan ⁡ 1 70 + arctan ⁡ 1 99 {\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 70}+\arctan {1 \over 99}} π 4 = 5 arctan ⁡ 1 7 + 4 arctan ⁡ 1 53 + 2 arctan ⁡ 1 4443 {\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+4\arctan {1 \over 53}+2\arctan {1 \over 4443}} π 4 = 6 arctan ⁡ 1 8 + 2 arctan ⁡ 1 57 + arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=6\arctan {1 \over 8}+2\arctan {1 \over 57}+\arctan {1 \over 239}} π 4 = 8 arctan ⁡ 1 10 − arctan ⁡ 1 239 − 4 arctan ⁡ 1 515 {\displaystyle {\pi \over 4}=8\arctan {1 \over 10}-\arctan {1 \over 239}-4\arctan {1 \over 515}} π 4 = 12 arctan ⁡ 1 18 + 8 arctan ⁡ 1 57 − 5 arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=12\arctan {1 \over 18}+8\arctan {1 \over 57}-5\arctan {1 \over 239}} π 4 = 16 arctan ⁡ 1 21 + 3 arctan ⁡ 1 239 + 4 arctan ⁡ 3 1042 {\displaystyle {\pi \over 4}=16\arctan {1 \over 21}+3\arctan {1 \over 239}+4\arctan {3 \over 1042}} π 4 = 22 arctan ⁡ 1 28 + 2 arctan ⁡ 1 443 − 5 arctan ⁡ 1 1393 − 10 arctan ⁡ 1 11018 {\displaystyle {\pi \over 4}=22\arctan {1 \over 28}+2\arctan {1 \over 443}-5\arctan {1 \over 1393}-10\arctan {1 \over 11018}} π 4 = 22 arctan ⁡ 1 38 + 17 arctan ⁡ 7 601 + 10 arctan ⁡ 7 8149 {\displaystyle {\pi \over 4}=22\arctan {1 \over 38}+17\arctan {7 \over 601}+10\arctan {7 \over 8149}} π 4 = 44 arctan ⁡ 1 57 + 7 arctan ⁡ 1 239 − 12 arctan ⁡ 1 682 + 24 arctan ⁡ 1 12943 {\displaystyle {\pi \over 4}=44\arctan {1 \over 57}+7\arctan {1 \over 239}-12\arctan {1 \over 682}+24\arctan {1 \over 12943}} π 4 = 88 arctan ⁡ 1 172 + 51 arctan ⁡ 1 239 + 32 arctan ⁡ 1 682 + 44 arctan ⁡ 1 5357 + 68 arctan ⁡ 1 12943 {\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12943}} and confirm that the following formula is incorrect by showing   tan   (right hand side)   is not   1: π 4 = 88 arctan ⁡ 1 172 + 51 arctan ⁡ 1 239 + 32 arctan ⁡ 1 682 + 44 arctan ⁡ 1 5357 + 68 arctan ⁡ 1 12944 {\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12944}} These identities are useful in calculating the values: tan ⁡ ( a + b ) = tan ⁡ ( a ) + tan ⁡ ( b ) 1 − tan ⁡ ( a ) tan ⁡ ( b ) {\displaystyle \tan(a+b)={\tan(a)+\tan(b) \over 1-\tan(a)\tan(b)}} tan ⁡ ( arctan ⁡ a b ) = a b {\displaystyle \tan \left(\arctan {a \over b}\right)={a \over b}} tan ⁡ ( − a ) = − tan ⁡ ( a ) {\displaystyle \tan(-a)=-\tan(a)} You can store the equations in any convenient data structure, but for extra credit parse them from human-readable text input. Note: to formally prove the formula correct, it would have to be shown that − 3 p i 4 {\displaystyle {-3pi \over 4}} < right hand side < 5 p i 4 {\displaystyle {5pi \over 4}} due to tan ⁡ ( ) {\displaystyle \tan()} periodicity.
#Sidef
Sidef
var equationtext = <<'EOT' pi/4 = arctan(1/2) + arctan(1/3) pi/4 = 2*arctan(1/3) + arctan(1/7) pi/4 = 4*arctan(1/5) - arctan(1/239) pi/4 = 5*arctan(1/7) + 2*arctan(3/79) pi/4 = 5*arctan(29/278) + 7*arctan(3/79) pi/4 = arctan(1/2) + arctan(1/5) + arctan(1/8) pi/4 = 4*arctan(1/5) - arctan(1/70) + arctan(1/99) pi/4 = 5*arctan(1/7) + 4*arctan(1/53) + 2*arctan(1/4443) pi/4 = 6*arctan(1/8) + 2*arctan(1/57) + arctan(1/239) pi/4 = 8*arctan(1/10) - arctan(1/239) - 4*arctan(1/515) pi/4 = 12*arctan(1/18) + 8*arctan(1/57) - 5*arctan(1/239) pi/4 = 16*arctan(1/21) + 3*arctan(1/239) + 4*arctan(3/1042) pi/4 = 22*arctan(1/28) + 2*arctan(1/443) - 5*arctan(1/1393) - 10*arctan(1/11018) pi/4 = 22*arctan(1/38) + 17*arctan(7/601) + 10*arctan(7/8149) pi/4 = 44*arctan(1/57) + 7*arctan(1/239) - 12*arctan(1/682) + 24*arctan(1/12943) pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12943) pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12944) EOT   func parse_eqn(equation) { static eqn_re = %r{ (^ \s* pi/4 \s* = \s* )? # LHS of equation (?: # RHS \s* ( [-+] )? \s* (?: ( \d+ ) \s* \*)? \s* arctan\((.*?)\) )}x   gather { for lhs,sign,mult,rat in (equation.findall(eqn_re)) { take([ [+1, -1][sign == '-'] * (mult ? Num(mult) : 1), Num(rat) ]) } } }   func tanEval(coef, f) { return f if (coef == 1) return -tanEval(-coef, f) if (coef < 0) var ca = coef>>1 var cb = (coef - ca) var (a, b) = (tanEval(ca, f), tanEval(cb, f)) (a + b) / (1 - a*b) }   func tans(xs) { var xslen = xs.len return tanEval(xs[0]...) if (xslen == 1) var (aa, bb) = xs.part(xslen>>1) var (a, b) = (tans(aa), tans(bb)) (a + b) / (1 - a*b) }   var machins = equationtext.lines.map(parse_eqn)   for machin,eqn in (machins ~Z equationtext.lines) { var ans = tans(machin) printf("%5s: %s\n", (ans == 1 ? 'OK' : 'ERROR'), eqn) }
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out the corresponding character.
#Common_Lisp
Common Lisp
(princ (char-code #\a)) ; prints "97" (princ (code-char 97)) ; prints "a"
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out the corresponding character.
#Component_Pascal
Component Pascal
PROCEDURE CharCodes*; VAR c : CHAR; BEGIN c := 'A'; StdLog.Char(c);StdLog.String(":> ");StdLog.Int(ORD(c));StdLog.Ln; c := CHR(3A9H); StdLog.Char(c);StdLog.String(":> ");StdLog.Int(ORD(c));StdLog.Ln END CharCodes;
http://rosettacode.org/wiki/Cholesky_decomposition
Cholesky decomposition
Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interpreted as a generalized square root of A {\displaystyle A} , as described in Cholesky decomposition. In a 3x3 example, we have to solve the following system of equations: A = ( a 11 a 21 a 31 a 21 a 22 a 32 a 31 a 32 a 33 ) = ( l 11 0 0 l 21 l 22 0 l 31 l 32 l 33 ) ( l 11 l 21 l 31 0 l 22 l 32 0 0 l 33 ) ≡ L L T = ( l 11 2 l 21 l 11 l 31 l 11 l 21 l 11 l 21 2 + l 22 2 l 31 l 21 + l 32 l 22 l 31 l 11 l 31 l 21 + l 32 l 22 l 31 2 + l 32 2 + l 33 2 ) {\displaystyle {\begin{aligned}A&={\begin{pmatrix}a_{11}&a_{21}&a_{31}\\a_{21}&a_{22}&a_{32}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}\\&={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}l_{11}&l_{21}&l_{31}\\0&l_{22}&l_{32}\\0&0&l_{33}\end{pmatrix}}\equiv LL^{T}\\&={\begin{pmatrix}l_{11}^{2}&l_{21}l_{11}&l_{31}l_{11}\\l_{21}l_{11}&l_{21}^{2}+l_{22}^{2}&l_{31}l_{21}+l_{32}l_{22}\\l_{31}l_{11}&l_{31}l_{21}+l_{32}l_{22}&l_{31}^{2}+l_{32}^{2}+l_{33}^{2}\end{pmatrix}}\end{aligned}}} We can see that for the diagonal elements ( l k k {\displaystyle l_{kk}} ) of L {\displaystyle L} there is a calculation pattern: l 11 = a 11 {\displaystyle l_{11}={\sqrt {a_{11}}}} l 22 = a 22 − l 21 2 {\displaystyle l_{22}={\sqrt {a_{22}-l_{21}^{2}}}} l 33 = a 33 − ( l 31 2 + l 32 2 ) {\displaystyle l_{33}={\sqrt {a_{33}-(l_{31}^{2}+l_{32}^{2})}}} or in general: l k k = a k k − ∑ j = 1 k − 1 l k j 2 {\displaystyle l_{kk}={\sqrt {a_{kk}-\sum _{j=1}^{k-1}l_{kj}^{2}}}} For the elements below the diagonal ( l i k {\displaystyle l_{ik}} , where i > k {\displaystyle i>k} ) there is also a calculation pattern: l 21 = 1 l 11 a 21 {\displaystyle l_{21}={\frac {1}{l_{11}}}a_{21}} l 31 = 1 l 11 a 31 {\displaystyle l_{31}={\frac {1}{l_{11}}}a_{31}} l 32 = 1 l 22 ( a 32 − l 31 l 21 ) {\displaystyle l_{32}={\frac {1}{l_{22}}}(a_{32}-l_{31}l_{21})} which can also be expressed in a general formula: l i k = 1 l k k ( a i k − ∑ j = 1 k − 1 l i j l k j ) {\displaystyle l_{ik}={\frac {1}{l_{kk}}}\left(a_{ik}-\sum _{j=1}^{k-1}l_{ij}l_{kj}\right)} Task description The task is to implement a routine which will return a lower Cholesky factor L {\displaystyle L} for every given symmetric, positive definite nxn matrix A {\displaystyle A} . You should then test it on the following two examples and include your output. Example 1: 25 15 -5 5 0 0 15 18 0 --> 3 3 0 -5 0 11 -1 1 3 Example 2: 18 22 54 42 4.24264 0.00000 0.00000 0.00000 22 70 86 62 --> 5.18545 6.56591 0.00000 0.00000 54 86 174 134 12.72792 3.04604 1.64974 0.00000 42 62 134 106 9.89949 1.62455 1.84971 1.39262 Note The Cholesky decomposition of a Pascal upper-triangle matrix is the Identity matrix of the same size. The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
#OCaml
OCaml
let cholesky inp = let n = Array.length inp in let res = Array.make_matrix n n 0.0 in let factor i k = let rec sum j = if j = k then 0.0 else res.(i).(j) *. res.(k).(j) +. sum (j+1) in inp.(i).(k) -. sum 0 in for col = 0 to n-1 do res.(col).(col) <- sqrt (factor col col); for row = col+1 to n-1 do res.(row).(col) <- (factor row col) /. res.(col).(col) done done; res   let pr_vec v = Array.iter (Printf.printf " %9.5f") v; print_newline() let show = Array.iter pr_vec let test a = print_endline "\nin:"; show a; print_endline "out:"; show (cholesky a)   let _ = test [| [|25.0; 15.0; -5.0|]; [|15.0; 18.0; 0.0|]; [|-5.0; 0.0; 11.0|] |]; test [| [|18.0; 22.0; 54.0; 42.0|]; [|22.0; 70.0; 86.0; 62.0|]; [|54.0; 86.0; 174.0; 134.0|]; [|42.0; 62.0; 134.0; 106.0|] |];
http://rosettacode.org/wiki/Cheryl%27s_birthday
Cheryl's birthday
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the   month   of birth,   and Bernard the   day   (of the month)   of birth. 1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too. 2) Bernard: At first I don't know when Cheryl's birthday is, but I know now. 3) Albert: Then I also know when Cheryl's birthday is. Task Write a computer program to deduce, by successive elimination, Cheryl's birthday. Related task Sum and Product Puzzle References Wikipedia article of the same name. Tuple Relational Calculus
#Racket
Racket
#lang racket   (define ((is x #:key [key identity]) y) (equal? (key x) (key y)))   (define albert first) (define bernard second)   (define (((unique who) chs) date) (= 1 (count (is date #:key who) chs)))   (define (((unique-fix who-fix who) chs) date) (ormap (conjoin (is date #:key who-fix) ((unique who) chs)) chs))   (define-syntax-rule (solve <chs> [<act> <arg>] ...) (let* ([chs <chs>] [chs (<act> (<arg> chs) chs)] ...) chs))   (solve '((May 15) (May 16) (May 19) (June 17) (June 18) (July 14) (July 16) (August 14) (August 15) (August 17))    ;; Albert knows the month but doesn't know the day.  ;; So the month can't be unique within the choices. [filter-not (unique albert)]  ;; Albert also knows that Bernard doesn't know the answer.  ;; So the month can't have a unique day. [filter-not (unique-fix albert bernard)]  ;; Bernard now knows the answer.  ;; So the day must be unique within the remaining choices. [filter (unique bernard)]  ;; Albert now knows the answer too.  ;; So the month must be unique within the remaining choices [filter (unique albert)])
http://rosettacode.org/wiki/Cheryl%27s_birthday
Cheryl's birthday
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the   month   of birth,   and Bernard the   day   (of the month)   of birth. 1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too. 2) Bernard: At first I don't know when Cheryl's birthday is, but I know now. 3) Albert: Then I also know when Cheryl's birthday is. Task Write a computer program to deduce, by successive elimination, Cheryl's birthday. Related task Sum and Product Puzzle References Wikipedia article of the same name. Tuple Relational Calculus
#Raku
Raku
my @dates = { :15day, :5month }, { :16day, :5month }, { :19day, :5month }, { :17day, :6month }, { :18day, :6month }, { :14day, :7month }, { :16day, :7month }, { :14day, :8month }, { :15day, :8month }, { :17day, :8month } ;   # Month can't have a unique day my @filtered = @dates.grep(*.<month> != one(@dates.grep(*.<day> == one(@dates».<day>))».<month>));   # Day must be unique and unambiguous in remaining months my $birthday = @filtered.grep(*.<day> == one(@filtered».<day>)).classify({.<month>})\ .first(*.value.elems == 1).value[0];   # convenience array my @months = <'' January February March April May June July August September October November December>;   say "Cheryl's birthday is { @months[$birthday<month>] } {$birthday<day>}.";
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
#MATLAB_.2F_Octave
MATLAB / Octave
>> A = {2,'TPS Report'} %Declare cell-array and initialize   A =   [2] 'TPS Report'   >> A{2} = struct('make','honda','year',2003)   A =   [2] [1x1 struct]   >> A{3} = {3,'HOVA'} %Create and assign A{3}   A =   [2] [1x1 struct] {1x2 cell}   >> A{2} %Get A{2}   ans =   make: 'honda' year: 2003
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
#PowerShell
PowerShell
  $source = @' using System; using System.Collections.Generic;   namespace Powershell { public class CSharp { public static IEnumerable<int[]> Combinations(int m, int n) { int[] result = new int[m]; Stack<int> stack = new Stack<int>(); stack.Push(0);   while (stack.Count > 0) { int index = stack.Count - 1; int value = stack.Pop();   while (value < n) { result[index++] = value++; stack.Push(value); if (index == m) { yield return result; break; } } } } } } '@   Add-Type -TypeDefinition $source -Language CSharp   [Powershell.CSharp]::Combinations(3,5) | Format-Wide {$_} -Column 3 -Force  
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.
#Smalltalk
Smalltalk
  balance > 0 ifTrue: [Transcript cr; show: 'still sitting pretty!'.] ifFalse: [Transcript cr; show: 'No money till payday!'.].   balance < 10 ifTrue:[ self goGetSomeMoney ].   balance > 1000 ifTrue:[ self beHappy ].   (balance < 10) ifFalse:[ self gotoHappyHour ] ifTrue:[ self noDrinksToday ].  
http://rosettacode.org/wiki/Chinese_remainder_theorem
Chinese remainder theorem
Suppose   n 1 {\displaystyle n_{1}} ,   n 2 {\displaystyle n_{2}} ,   … {\displaystyle \ldots } ,   n k {\displaystyle n_{k}}   are positive integers that are pairwise co-prime.   Then, for any given sequence of integers   a 1 {\displaystyle a_{1}} ,   a 2 {\displaystyle a_{2}} ,   … {\displaystyle \dots } ,   a k {\displaystyle a_{k}} ,   there exists an integer   x {\displaystyle x}   solving the following system of simultaneous congruences: x ≡ a 1 ( mod n 1 ) x ≡ a 2 ( mod n 2 )     ⋮ x ≡ a k ( mod n k ) {\displaystyle {\begin{aligned}x&\equiv a_{1}{\pmod {n_{1}}}\\x&\equiv a_{2}{\pmod {n_{2}}}\\&{}\ \ \vdots \\x&\equiv a_{k}{\pmod {n_{k}}}\end{aligned}}} Furthermore, all solutions   x {\displaystyle x}   of this system are congruent modulo the product,   N = n 1 n 2 … n k {\displaystyle N=n_{1}n_{2}\ldots n_{k}} . Task Write a program to solve a system of linear congruences by applying the   Chinese Remainder Theorem. If the system of equations cannot be solved, your program must somehow indicate this. (It may throw an exception or return a special false value.) Since there are infinitely many solutions, the program should return the unique solution   s {\displaystyle s}   where   0 ≤ s ≤ n 1 n 2 … n k {\displaystyle 0\leq s\leq n_{1}n_{2}\ldots n_{k}} . Show the functionality of this program by printing the result such that the   n {\displaystyle n} 's   are   [ 3 , 5 , 7 ] {\displaystyle [3,5,7]}   and the   a {\displaystyle a} 's   are   [ 2 , 3 , 2 ] {\displaystyle [2,3,2]} . Algorithm:   The following algorithm only applies if the   n i {\displaystyle n_{i}} 's   are pairwise co-prime. Suppose, as above, that a solution is required for the system of congruences: x ≡ a i ( mod n i ) f o r i = 1 , … , k {\displaystyle x\equiv a_{i}{\pmod {n_{i}}}\quad \mathrm {for} \;i=1,\ldots ,k} Again, to begin, the product   N = n 1 n 2 … n k {\displaystyle N=n_{1}n_{2}\ldots n_{k}}   is defined. Then a solution   x {\displaystyle x}   can be found as follows: For each   i {\displaystyle i} ,   the integers   n i {\displaystyle n_{i}}   and   N / n i {\displaystyle N/n_{i}}   are co-prime. Using the   Extended Euclidean algorithm,   we can find integers   r i {\displaystyle r_{i}}   and   s i {\displaystyle s_{i}}   such that   r i n i + s i N / n i = 1 {\displaystyle r_{i}n_{i}+s_{i}N/n_{i}=1} . Then, one solution to the system of simultaneous congruences is: x = ∑ i = 1 k a i s i N / n i {\displaystyle x=\sum _{i=1}^{k}a_{i}s_{i}N/n_{i}} and the minimal solution, x ( mod N ) {\displaystyle x{\pmod {N}}} .
#Lua
Lua
-- Taken from https://www.rosettacode.org/wiki/Sum_and_product_of_an_array#Lua function prodf(a, ...) return a and a * prodf(...) or 1 end function prodt(t) return prodf(unpack(t)) end   function mulInv(a, b) local b0 = b local x0 = 0 local x1 = 1   if b == 1 then return 1 end   while a > 1 do local q = math.floor(a / b) local amb = math.fmod(a, b) a = b b = amb local xqx = x1 - q * x0 x1 = x0 x0 = xqx end   if x1 < 0 then x1 = x1 + b0 end   return x1 end   function chineseRemainder(n, a) local prod = prodt(n)   local p local sm = 0 for i=1,#n do p = prod / n[i] sm = sm + a[i] * mulInv(p, n[i]) * p end   return math.fmod(sm, prod) end   n = {3, 5, 7} a = {2, 3, 2} io.write(chineseRemainder(n, a))
http://rosettacode.org/wiki/Chowla_numbers
Chowla numbers
Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n   is a positive integer The sequence is named after   Sarvadaman D. S. Chowla,   (22 October 1907 ──► 10 December 1995), a London born Indian American mathematician specializing in number theory. German mathematician Carl Friedrich Gauss (1777─1855) said: "Mathematics is the queen of the sciences ─ and number theory is the queen of mathematics". Definitions Chowla numbers can also be expressed as: chowla(n) = sum of divisors of n excluding unity and n chowla(n) = sum( divisors(n)) - 1 - n chowla(n) = sum( properDivisors(n)) - 1 chowla(n) = sum(aliquotDivisors(n)) - 1 chowla(n) = aliquot(n) - 1 chowla(n) = sigma(n) - 1 - n chowla(n) = sigmaProperDivisiors(n) - 1   chowla(a*b) = a + b,   if a and b are distinct primes if chowla(n) = 0,  and n > 1, then n is prime if chowla(n) = n - 1, and n > 1, then n is a perfect number Task   create a   chowla   function that returns the   chowla number   for a positive integer   n   Find and display   (1 per line)   for the 1st   37   integers:   the integer   (the index)   the chowla number for that integer   For finding primes, use the   chowla   function to find values of zero   Find and display the   count   of the primes up to              100   Find and display the   count   of the primes up to           1,000   Find and display the   count   of the primes up to         10,000   Find and display the   count   of the primes up to       100,000   Find and display the   count   of the primes up to    1,000,000   Find and display the   count   of the primes up to  10,000,000   For finding perfect numbers, use the   chowla   function to find values of   n - 1   Find and display all   perfect numbers   up to   35,000,000   use commas within appropriate numbers   show all output here Related tasks   totient function   perfect numbers   Proper divisors   Sieve of Eratosthenes See also   the OEIS entry for   A48050 Chowla's function.
#Visual_Basic_.NET
Visual Basic .NET
Imports System   Module Program Function chowla(ByVal n As Integer) As Integer chowla = 0 : Dim j As Integer, i As Integer = 2 While i * i <= n j = n / i : If n Mod i = 0 Then chowla += i + (If(i = j, 0, j)) i += 1 End While End Function   Function sieve(ByVal limit As Integer) As Boolean() Dim c As Boolean() = New Boolean(limit - 1) {}, i As Integer = 3 While i * 3 < limit If Not c(i) AndAlso (chowla(i) = 0) Then Dim j As Integer = 3 * i While j < limit : c(j) = True : j += 2 * i : End While End If : i += 2 End While Return c End Function   Sub Main(args As String()) For i As Integer = 1 To 37 Console.WriteLine("chowla({0}) = {1}", i, chowla(i)) Next Dim count As Integer = 1, limit As Integer = CInt((10000000.0)), power As Integer = 100, c As Boolean() = sieve(limit) For i As Integer = 3 To limit - 1 Step 2 If Not c(i) Then count += 1 If i = power - 1 Then Console.WriteLine("Count of primes up to {0,10:n0} = {1:n0}", power, count) power = power * 10 End If Next count = 0 : limit = 35000000 Dim p As Integer, k As Integer = 2, kk As Integer = 3 While True p = k * kk : If p > limit Then Exit While If chowla(p) = p - 1 Then Console.WriteLine("{0,10:n0} is a number that is perfect", p) count += 1 End If k = kk + 1 : kk += k End While Console.WriteLine("There are {0} perfect numbers <= 35,000,000", count) If System.Diagnostics.Debugger.IsAttached Then Console.ReadKey() End Sub End Module
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.
#Oberon-2
Oberon-2
MODULE M;   TYPE T = POINTER TO TDesc; TDesc = RECORD x: INTEGER END;   PROCEDURE New*(): T; VAR t: T; BEGIN NEW(t); t.x := 0; RETURN t END New;     PROCEDURE (t: T) Increment*; BEGIN INC(t.x) END Increment;   END M.
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.
#Objeck
Objeck
bundle Default { class MyClass { @var : Int;   New() { }   method : public : SomeMethod() ~ Nil { @var := 1; }   method : public : SetVar(var : Int) ~ Nil { @var := var; }   method : public : GetVar() ~ Int { return @var; } }   class Test { function : Main(args : String[]) ~ Nil { inst := MyClass->New(); inst->GetVar()->PrintLine();   inst->SomeMethod(); inst->GetVar()->PrintLine();   inst->SetVar(15); inst->GetVar()->PrintLine(); } } }
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)
#PL.2FI
PL/I
  /* Closest Pair Problem */ closest: procedure options (main); declare n fixed binary;   get list (n); begin; declare 1 P(n), 2 x float, 2 y float; declare (i, ii, j, jj) fixed binary; declare (distance, min_distance initial (0) ) float;   get list (P); min_distance = sqrt( (P.x(1) - P.x(2))**2 + (P.y(1) - P.y(2))**2 ); ii = 1; jj = 2; do i = 1 to n; do j = 1 to n; distance = sqrt( (P.x(i) - P.x(j))**2 + (P.y(i) - P.y(j))**2 ); if distance > 0 then if distance < min_distance then do; min_distance = distance; ii = i; jj = j; end; end; end; put skip edit ('The minimum distance ', min_distance, ' is between the points [', P.x(ii), ',', P.y(ii), '] and [', P.x(jj), ',', P.y(jj), ']' ) (a, f(6,2)); end; end closest;  
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points
Circles of given radius through two points
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. Exceptions r==0.0 should be treated as never describing circles (except in the case where the points are coincident). If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point. If the points form a diameter then return two identical circles or return a single circle, according to which is the most natural mechanism for the implementation language. If the points are too far apart then no circles can be drawn. Task detail Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, or some indication of special cases where two, possibly equal, circles cannot be returned. Show here the output for the following inputs: p1 p2 r 0.1234, 0.9876 0.8765, 0.2345 2.0 0.0000, 2.0000 0.0000, 0.0000 1.0 0.1234, 0.9876 0.1234, 0.9876 2.0 0.1234, 0.9876 0.8765, 0.2345 0.5 0.1234, 0.9876 0.1234, 0.9876 0.0 Related task   Total circles area. See also   Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
#Maple
Maple
drawCircles := proc(x1, y1, x2, y2, r, $) local c1, c2, p1, p2; use geometry in if x1 = x2 and y1 = y2 then if r = 0 then printf("The circle is a point at [%a, %a].\n", x1, y1); else printf("The two points are the same. Infinite circles can be drawn.\n"); end if; elif evalf(distance(point(A, x1, y1), point(B, x2, y2))) >r*2 then printf("The two points are too far apart. No circles can be drawn.\n"); else circle(P1Cir, [A, r]);#make a circle around the first point circle(P2Cir, [B, r]);#make a circle around the second point intersection('i', P1Cir, P2Cir); #the intersection of the above 2 circles should give you the centers of the two circles you need to draw c1 := plottools[circle](coordinates(`if`(type(i, list), i[1], i)), r);#make the first circle c2 := plottools[circle](coordinates(`if`(type(i, list), i[2], i)), r);#make the second circle plots[display](c1, c2, scaling = constrained);#draw end if; end use; end proc:   drawCircles(0.1234, 0.9876, 0.8765, 0.2345, 2.0); drawCircles(0.0000, 2.0000, 0.0000, 0.0000, 1.0); drawCircles(0.1234, 0.9876, 0.1234, 0.9876, 2.0); drawCircles(0.1234, 0.9876, 0.8765, 0.2345, 0.5); drawCircles(0.1234, 0.9876, 0.1234, 0.9876, 0.0);
http://rosettacode.org/wiki/Chinese_zodiac
Chinese zodiac
Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Tuesday, February 1, 2022 CE (in the common Gregorian calendar) will begin the lunisolar Year of the Tiger. The celestial stems have no one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems each belong to one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element's governance is associated with yin, the other with yang. Thus, 2022 is also the yang year of Water. Note that since 12 is an even number, the association between animals and yin/yang doesn't change. Consecutive Years of the Rooster will cycle through the five elements, but will always be yin, despite the apparent conceptual mismatch between the specifically-male English animal name and the female aspect denoted by yin. Task Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year. You may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration). Requisite information The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig. The element cycle runs in this order: Wood, Fire, Earth, Metal, Water. The yang year precedes the yin year within each element. The current 60-year cycle began in 1984 CE; the first cycle of the Common Era began in 4 CE. Thus, 1984 was the year of the Wood Rat (yang), 1985 was the year of the Wood Ox (yin), and 1986 the year of the Fire Tiger (yang); 2022 - which, as already noted, is the year of the Water Tiger (yang) - is the 39th year of the current cycle. Information for optional task The ten celestial stems are 甲 jiă, 乙 yĭ, 丙 bĭng, 丁 dīng, 戊 wù, 己 jĭ, 庚 gēng, 辛 xīn, 壬 rén, and 癸 gŭi. With the ASCII version of Pinyin tones, the names are written "jia3", "yi3", "bing3", "ding1", "wu4", "ji3", "geng1", "xin1", "ren2", and "gui3". The twelve terrestrial branches are 子 zĭ, 丑 chŏu, 寅 yín, 卯 măo, 辰 chén, 巳 sì, 午 wŭ, 未 wèi, 申 shēn, 酉 yŏu, 戌 xū, 亥 hài. In ASCII Pinyin, those are "zi3", "chou3", "yin2", "mao3", "chen2", "si4", "wu3", "wei4", "shen1", "you3", "xu1", and "hai4". Therefore 1984 was 甲子 (jiă-zĭ, or jia3-zi3). 2022 is 壬寅 (rén-yín or ren2-yin2).
#Modula-2
Modula-2
MODULE ChineseZodiac; FROM FormatString IMPORT FormatString; FROM Terminal IMPORT WriteString,ReadChar;   TYPE Str = ARRAY[0..7] OF CHAR;   TYPE AA = ARRAY[0..11] OF Str; CONST ANIMALS = AA{"Rat","Ox","Tiger","Rabbit","Dragon","Snake","Horse","Goat","Monkey","Rooster","Dog","Pig"};   TYPE EA = ARRAY[0..4] OF Str; CONST ELEMENTS = EA{"Wood","Fire","Earth","Metal","Water"};   PROCEDURE element(year : INTEGER) : Str; VAR idx : CARDINAL; BEGIN idx := ((year - 4) MOD 10) / 2; RETURN ELEMENTS[idx]; END element;   PROCEDURE animal(year : INTEGER) : Str; VAR idx : CARDINAL; BEGIN idx := (year - 4) MOD 12; RETURN ANIMALS[idx]; END animal;   PROCEDURE yy(year : INTEGER) : Str; BEGIN IF year MOD 2 = 0 THEN RETURN "yang" ELSE RETURN "yin" END END yy;   PROCEDURE print(year : INTEGER); VAR buf : ARRAY[0..63] OF CHAR; BEGIN FormatString("%i is the year of the %s %s (%s)\n", buf, year, element(year), animal(year), yy(year)); WriteString(buf); END print;   (* main *) BEGIN print(1935); print(1938); print(1968); print(1972); print(1976); print(2017);   ReadChar END ChineseZodiac.
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an unusual filename:   `Abdu'l-Bahá.txt
#Euphoria
Euphoria
include file.e   procedure ensure_exists(sequence name) object x sequence s x = dir(name) if sequence(x) then if find('d',x[1][D_ATTRIBUTES]) then s = "directory" else s = "file" end if printf(1,"%s %s exists.\n",{name,s}) else printf(1,"%s does not exist.\n",{name}) end if end procedure   ensure_exists("input.txt") ensure_exists("docs") ensure_exists("/input.txt") ensure_exists("/docs")
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an unusual filename:   `Abdu'l-Bahá.txt
#F.23
F#
open System.IO File.Exists("input.txt") Directory.Exists("docs") File.Exists("/input.txt") Directory.Exists(@"\docs")
http://rosettacode.org/wiki/Chaos_game
Chaos game
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a starting point at random (preferably inside the triangle).   Then add the next point halfway between the starting point and one of the reference points.   This reference point is chosen at random. After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge. See also The Game of Chaos
#J
J
  Note 'plan, Working in complex plane' Make an equilateral triangle. Make a list of N targets Starting with a random point near the triangle, iteratively generate new points. plot the new points.   j has a particularly rich notation for numbers.   1ad_90 specifies a complex number with radius 1 at an angle of negative 90 degrees.   2p1 is 2 times (pi raised to the first power). )   N=: 3000   require'plot' TAU=: 2p1 NB. tauday.com mean=: +/ % #   NB. equilateral triangle with vertices on unit circle NB. rotated for fun. TRIANGLE=: *(j./2 1 o.(TAU%6)*?0)*1ad_90 1ad150 1ad30   TARGETS=: (N ?@:# 3) { TRIANGLE   NB. start on unit circle START=: j./2 1 o.TAU*?0   NEW_POINTS=: (mean@:(, {.) , ])/ TARGETS , START   'marker'plot NEW_POINTS  
http://rosettacode.org/wiki/Chaos_game
Chaos game
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a starting point at random (preferably inside the triangle).   Then add the next point halfway between the starting point and one of the reference points.   This reference point is chosen at random. After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge. See also The Game of Chaos
#Java
Java
import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.Timer;   public class ChaosGame extends JPanel { static class ColoredPoint extends Point { int colorIndex;   ColoredPoint(int x, int y, int idx) { super(x, y); colorIndex = idx; } }   Stack<ColoredPoint> stack = new Stack<>(); Point[] points = new Point[3]; Color[] colors = {Color.red, Color.green, Color.blue}; Random r = new Random();   public ChaosGame() { Dimension dim = new Dimension(640, 640); setPreferredSize(dim); setBackground(Color.white);   int margin = 60; int size = dim.width - 2 * margin;   points[0] = new Point(dim.width / 2, margin); points[1] = new Point(margin, size); points[2] = new Point(margin + size, size);   stack.push(new ColoredPoint(-1, -1, 0));   new Timer(10, (ActionEvent e) -> { if (stack.size() < 50_000) { for (int i = 0; i < 1000; i++) addPoint(); repaint(); } }).start(); }   private void addPoint() { try { int colorIndex = r.nextInt(3); Point p1 = stack.peek(); Point p2 = points[colorIndex]; stack.add(halfwayPoint(p1, p2, colorIndex)); } catch (EmptyStackException e) { e.printStackTrace(); } }   void drawPoints(Graphics2D g) { for (ColoredPoint p : stack) { g.setColor(colors[p.colorIndex]); g.fillOval(p.x, p.y, 1, 1); } }   ColoredPoint halfwayPoint(Point a, Point b, int idx) { return new ColoredPoint((a.x + b.x) / 2, (a.y + b.y) / 2, idx); }   @Override public void paintComponent(Graphics gg) { super.paintComponent(gg); Graphics2D g = (Graphics2D) gg; g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);   drawPoints(g); }   public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setTitle("Chaos Game"); f.setResizable(false); f.add(new ChaosGame(), BorderLayout.CENTER); f.pack(); f.setLocationRelativeTo(null); f.setVisible(true); }); } }
http://rosettacode.org/wiki/Chat_server
Chat server
Task Write a server for a minimal text based chat. People should be able to connect via ‘telnet’, sign on with a nickname, and type messages which will then be seen by all other connected users. Arrivals and departures of chat members should generate appropriate notification messages.
#Perl
Perl
use 5.010; use strict; use warnings;   use threads; use threads::shared;   use IO::Socket::INET; use Time::HiRes qw(sleep ualarm);   my $HOST = "localhost"; my $PORT = 4004;   my @open; my %users : shared;   sub broadcast { my ($id, $message) = @_; print "$message\n"; foreach my $i (keys %users) { if ($i != $id) { $open[$i]->send("$message\n"); } } }   sub sign_in { my ($conn) = @_;   state $id = 0;   threads->new( sub { while (1) { $conn->send("Please enter your name: "); $conn->recv(my $name, 1024, 0);   if (defined $name) { $name = unpack('A*', $name);   if (exists $users{$name}) { $conn->send("Name entered is already in use.\n"); } elsif ($name ne '') { $users{$id} = $name; broadcast($id, "+++ $name arrived +++"); last; } } } } );   ++$id; push @open, $conn; }   my $server = IO::Socket::INET->new( Timeout => 0, LocalPort => $PORT, Proto => "tcp", LocalAddr => $HOST, Blocking => 0, Listen => 1, Reuse => 1, );   local $| = 1; print "Listening on $HOST:$PORT\n";   while (1) { my ($conn) = $server->accept;   if (defined($conn)) { sign_in($conn); }   foreach my $i (keys %users) {   my $conn = $open[$i]; my $message;   eval { local $SIG{ALRM} = sub { die "alarm\n" }; ualarm(500); $conn->recv($message, 1024, 0); ualarm(0); };   if ($@ eq "alarm\n") { next; }   if (defined($message)) { if ($message ne '') { $message = unpack('A*', $message); broadcast($i, "$users{$i}> $message"); } else { broadcast($i, "--- $users{$i} leaves ---"); delete $users{$i}; undef $open[$i]; } } }   sleep(0.1); }
http://rosettacode.org/wiki/Check_Machin-like_formulas
Check Machin-like formulas
Machin-like formulas   are useful for efficiently computing numerical approximations for π {\displaystyle \pi } Task Verify the following Machin-like formulas are correct by calculating the value of tan   (right hand side) for each equation using exact arithmetic and showing they equal 1: π 4 = arctan ⁡ 1 2 + arctan ⁡ 1 3 {\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 3}} π 4 = 2 arctan ⁡ 1 3 + arctan ⁡ 1 7 {\displaystyle {\pi \over 4}=2\arctan {1 \over 3}+\arctan {1 \over 7}} π 4 = 4 arctan ⁡ 1 5 − arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 239}} π 4 = 5 arctan ⁡ 1 7 + 2 arctan ⁡ 3 79 {\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+2\arctan {3 \over 79}} π 4 = 5 arctan ⁡ 29 278 + 7 arctan ⁡ 3 79 {\displaystyle {\pi \over 4}=5\arctan {29 \over 278}+7\arctan {3 \over 79}} π 4 = arctan ⁡ 1 2 + arctan ⁡ 1 5 + arctan ⁡ 1 8 {\displaystyle {\pi \over 4}=\arctan {1 \over 2}+\arctan {1 \over 5}+\arctan {1 \over 8}} π 4 = 4 arctan ⁡ 1 5 − arctan ⁡ 1 70 + arctan ⁡ 1 99 {\displaystyle {\pi \over 4}=4\arctan {1 \over 5}-\arctan {1 \over 70}+\arctan {1 \over 99}} π 4 = 5 arctan ⁡ 1 7 + 4 arctan ⁡ 1 53 + 2 arctan ⁡ 1 4443 {\displaystyle {\pi \over 4}=5\arctan {1 \over 7}+4\arctan {1 \over 53}+2\arctan {1 \over 4443}} π 4 = 6 arctan ⁡ 1 8 + 2 arctan ⁡ 1 57 + arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=6\arctan {1 \over 8}+2\arctan {1 \over 57}+\arctan {1 \over 239}} π 4 = 8 arctan ⁡ 1 10 − arctan ⁡ 1 239 − 4 arctan ⁡ 1 515 {\displaystyle {\pi \over 4}=8\arctan {1 \over 10}-\arctan {1 \over 239}-4\arctan {1 \over 515}} π 4 = 12 arctan ⁡ 1 18 + 8 arctan ⁡ 1 57 − 5 arctan ⁡ 1 239 {\displaystyle {\pi \over 4}=12\arctan {1 \over 18}+8\arctan {1 \over 57}-5\arctan {1 \over 239}} π 4 = 16 arctan ⁡ 1 21 + 3 arctan ⁡ 1 239 + 4 arctan ⁡ 3 1042 {\displaystyle {\pi \over 4}=16\arctan {1 \over 21}+3\arctan {1 \over 239}+4\arctan {3 \over 1042}} π 4 = 22 arctan ⁡ 1 28 + 2 arctan ⁡ 1 443 − 5 arctan ⁡ 1 1393 − 10 arctan ⁡ 1 11018 {\displaystyle {\pi \over 4}=22\arctan {1 \over 28}+2\arctan {1 \over 443}-5\arctan {1 \over 1393}-10\arctan {1 \over 11018}} π 4 = 22 arctan ⁡ 1 38 + 17 arctan ⁡ 7 601 + 10 arctan ⁡ 7 8149 {\displaystyle {\pi \over 4}=22\arctan {1 \over 38}+17\arctan {7 \over 601}+10\arctan {7 \over 8149}} π 4 = 44 arctan ⁡ 1 57 + 7 arctan ⁡ 1 239 − 12 arctan ⁡ 1 682 + 24 arctan ⁡ 1 12943 {\displaystyle {\pi \over 4}=44\arctan {1 \over 57}+7\arctan {1 \over 239}-12\arctan {1 \over 682}+24\arctan {1 \over 12943}} π 4 = 88 arctan ⁡ 1 172 + 51 arctan ⁡ 1 239 + 32 arctan ⁡ 1 682 + 44 arctan ⁡ 1 5357 + 68 arctan ⁡ 1 12943 {\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12943}} and confirm that the following formula is incorrect by showing   tan   (right hand side)   is not   1: π 4 = 88 arctan ⁡ 1 172 + 51 arctan ⁡ 1 239 + 32 arctan ⁡ 1 682 + 44 arctan ⁡ 1 5357 + 68 arctan ⁡ 1 12944 {\displaystyle {\pi \over 4}=88\arctan {1 \over 172}+51\arctan {1 \over 239}+32\arctan {1 \over 682}+44\arctan {1 \over 5357}+68\arctan {1 \over 12944}} These identities are useful in calculating the values: tan ⁡ ( a + b ) = tan ⁡ ( a ) + tan ⁡ ( b ) 1 − tan ⁡ ( a ) tan ⁡ ( b ) {\displaystyle \tan(a+b)={\tan(a)+\tan(b) \over 1-\tan(a)\tan(b)}} tan ⁡ ( arctan ⁡ a b ) = a b {\displaystyle \tan \left(\arctan {a \over b}\right)={a \over b}} tan ⁡ ( − a ) = − tan ⁡ ( a ) {\displaystyle \tan(-a)=-\tan(a)} You can store the equations in any convenient data structure, but for extra credit parse them from human-readable text input. Note: to formally prove the formula correct, it would have to be shown that − 3 p i 4 {\displaystyle {-3pi \over 4}} < right hand side < 5 p i 4 {\displaystyle {5pi \over 4}} due to tan ⁡ ( ) {\displaystyle \tan()} periodicity.
#Tcl
Tcl
package require Tcl 8.5   # Compute tan(atan(p)+atan(q)) using rationals proc tadd {p q} { lassign $p pp pq lassign $q qp qq set topp [expr {$pp*$qq + $qp*$pq}] set topq [expr {$pq*$qq}] set prodp [expr {$pp*$qp}] set prodq [expr {$pq*$qq}] set lowp [expr {$prodq - $prodp}] set resultp [set gcd1 [expr {$topp * $prodq}]] set resultq [set gcd2 [expr {$topq * $lowp}]] # Critical! Normalize using the GCD while {$gcd2 != 0} { lassign [list $gcd2 [expr {$gcd1 % $gcd2}]] gcd1 gcd2 } list [expr {$resultp / abs($gcd1)}] [expr {$resultq / abs($gcd1)}] } proc termTan {n a b} { if {$n < 0} { set n [expr {-$n}] set a [expr {-$a}] } if {$n == 1} { return [list $a $b] } set k [expr {$n - [set m [expr {$n / 2}]]*2}] set t2 [termTan $m $a $b] set m2 [tadd $t2 $t2] if {$k == 0} { return $m2 } return [tadd [termTan $k $a $b] $m2] } proc machinTan {terms} { set sum {0 1} foreach term $terms { set sum [tadd $sum [termTan {*}$term]] } return $sum }   # Assumes that the formula is in the very specific form below! proc parseFormula {formula} { set RE {(-?\s*\d*\s*\*?)\s*arctan\s*\(\s*(-?\s*\d+)\s*/\s*(-?\s*\d+)\s*\)} set nospace {" " "" "*" ""} foreach {all n a b} [regexp -inline -all $RE $formula] { if {![regexp {\d} $n]} {append n 1} lappend result [list [string map $nospace $n] [string map $nospace $a] [string map $nospace $b]] } return $result }   foreach formula { "pi/4 = arctan(1/2) + arctan(1/3)" "pi/4 = 2*arctan(1/3) + arctan(1/7)" "pi/4 = 4*arctan(1/5) - arctan(1/239)" "pi/4 = 5*arctan(1/7) + 2*arctan(3/79)" "pi/4 = 5*arctan(29/278) + 7*arctan(3/79)" "pi/4 = arctan(1/2) + arctan(1/5) + arctan(1/8)" "pi/4 = 4*arctan(1/5) - arctan(1/70) + arctan(1/99)" "pi/4 = 5*arctan(1/7) + 4*arctan(1/53) + 2*arctan(1/4443)" "pi/4 = 6*arctan(1/8) + 2*arctan(1/57) + arctan(1/239)" "pi/4 = 8*arctan(1/10) - arctan(1/239) - 4*arctan(1/515)" "pi/4 = 12*arctan(1/18) + 8*arctan(1/57) - 5*arctan(1/239)" "pi/4 = 16*arctan(1/21) + 3*arctan(1/239) + 4*arctan(3/1042)" "pi/4 = 22*arctan(1/28) + 2*arctan(1/443) - 5*arctan(1/1393) - 10*arctan(1/11018)" "pi/4 = 22*arctan(1/38) + 17*arctan(7/601) + 10*arctan(7/8149)" "pi/4 = 44*arctan(1/57) + 7*arctan(1/239) - 12*arctan(1/682) + 24*arctan(1/12943)" "pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12943)" "pi/4 = 88*arctan(1/172) + 51*arctan(1/239) + 32*arctan(1/682) + 44*arctan(1/5357) + 68*arctan(1/12944)" } { if {[tcl::mathop::== {*}[machinTan [parseFormula $formula]]]} { puts "Yes! '$formula' is true" } else { puts "No! '$formula' not true" } }
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out the corresponding character.
#D
D
void main() { import std.stdio, std.utf;   string test = "a"; size_t index = 0;   // Get four-byte utf32 value for index 0. writefln("%d", test.decode(index));   // 'index' has moved to next character input position. assert(index == 1); }
http://rosettacode.org/wiki/Character_codes
Character codes
Task Given a character value in your language, print its code   (could be ASCII code, Unicode code, or whatever your language uses). Example The character   'a'   (lowercase letter A)   has a code of 97 in ASCII   (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out the corresponding character.
#Dc
Dc
97P
http://rosettacode.org/wiki/Cholesky_decomposition
Cholesky decomposition
Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interpreted as a generalized square root of A {\displaystyle A} , as described in Cholesky decomposition. In a 3x3 example, we have to solve the following system of equations: A = ( a 11 a 21 a 31 a 21 a 22 a 32 a 31 a 32 a 33 ) = ( l 11 0 0 l 21 l 22 0 l 31 l 32 l 33 ) ( l 11 l 21 l 31 0 l 22 l 32 0 0 l 33 ) ≡ L L T = ( l 11 2 l 21 l 11 l 31 l 11 l 21 l 11 l 21 2 + l 22 2 l 31 l 21 + l 32 l 22 l 31 l 11 l 31 l 21 + l 32 l 22 l 31 2 + l 32 2 + l 33 2 ) {\displaystyle {\begin{aligned}A&={\begin{pmatrix}a_{11}&a_{21}&a_{31}\\a_{21}&a_{22}&a_{32}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}\\&={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}l_{11}&l_{21}&l_{31}\\0&l_{22}&l_{32}\\0&0&l_{33}\end{pmatrix}}\equiv LL^{T}\\&={\begin{pmatrix}l_{11}^{2}&l_{21}l_{11}&l_{31}l_{11}\\l_{21}l_{11}&l_{21}^{2}+l_{22}^{2}&l_{31}l_{21}+l_{32}l_{22}\\l_{31}l_{11}&l_{31}l_{21}+l_{32}l_{22}&l_{31}^{2}+l_{32}^{2}+l_{33}^{2}\end{pmatrix}}\end{aligned}}} We can see that for the diagonal elements ( l k k {\displaystyle l_{kk}} ) of L {\displaystyle L} there is a calculation pattern: l 11 = a 11 {\displaystyle l_{11}={\sqrt {a_{11}}}} l 22 = a 22 − l 21 2 {\displaystyle l_{22}={\sqrt {a_{22}-l_{21}^{2}}}} l 33 = a 33 − ( l 31 2 + l 32 2 ) {\displaystyle l_{33}={\sqrt {a_{33}-(l_{31}^{2}+l_{32}^{2})}}} or in general: l k k = a k k − ∑ j = 1 k − 1 l k j 2 {\displaystyle l_{kk}={\sqrt {a_{kk}-\sum _{j=1}^{k-1}l_{kj}^{2}}}} For the elements below the diagonal ( l i k {\displaystyle l_{ik}} , where i > k {\displaystyle i>k} ) there is also a calculation pattern: l 21 = 1 l 11 a 21 {\displaystyle l_{21}={\frac {1}{l_{11}}}a_{21}} l 31 = 1 l 11 a 31 {\displaystyle l_{31}={\frac {1}{l_{11}}}a_{31}} l 32 = 1 l 22 ( a 32 − l 31 l 21 ) {\displaystyle l_{32}={\frac {1}{l_{22}}}(a_{32}-l_{31}l_{21})} which can also be expressed in a general formula: l i k = 1 l k k ( a i k − ∑ j = 1 k − 1 l i j l k j ) {\displaystyle l_{ik}={\frac {1}{l_{kk}}}\left(a_{ik}-\sum _{j=1}^{k-1}l_{ij}l_{kj}\right)} Task description The task is to implement a routine which will return a lower Cholesky factor L {\displaystyle L} for every given symmetric, positive definite nxn matrix A {\displaystyle A} . You should then test it on the following two examples and include your output. Example 1: 25 15 -5 5 0 0 15 18 0 --> 3 3 0 -5 0 11 -1 1 3 Example 2: 18 22 54 42 4.24264 0.00000 0.00000 0.00000 22 70 86 62 --> 5.18545 6.56591 0.00000 0.00000 54 86 174 134 12.72792 3.04604 1.64974 0.00000 42 62 134 106 9.89949 1.62455 1.84971 1.39262 Note The Cholesky decomposition of a Pascal upper-triangle matrix is the Identity matrix of the same size. The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
#ooRexx
ooRexx
/*REXX program performs the Cholesky decomposition on a square matrix. */ niner = '25 15 -5' , /*define a 3x3 matrix. */ '15 18 0' , '-5 0 11' call Cholesky niner hexer = 18 22 54 42, /*define a 4x4 matrix. */ 22 70 86 62, 54 86 174 134, 42 62 134 106 call Cholesky hexer exit /*stick a fork in it, we're all done. */ /*----------------------------------------------------------------------------*/ Cholesky: procedure; parse arg mat; say; say; call tell 'input matrix',mat do r=1 for ord do c=1 for r; d=0; do i=1 for c-1; d=d+!.r.i*!.c.i; end /*i*/ if r=c then !.r.r=sqrt(!.r.r-d) else !.r.c=1/!.c.c*(a.r.c-d) end /*c*/ end /*r*/ call tell 'Cholesky factor',,!.,'-' return /*----------------------------------------------------------------------------*/ err: say; say; say '***error***!'; say; say arg(1); say; say; exit 13 /*----------------------------------------------------------------------------*/ tell: parse arg hdr,x,y,sep; n=0; if sep=='' then sep='-' dPlaces= 5 /*n decimal places past the decimal point*/ width =10 /*width of field used to display elements*/ if y=='' then !.=0 else do row=1 for ord; do col=1 for ord; x=x !.row.col; end; end w=words(x) do ord=1 until ord**2>=w; end /*a fast way to find matrix's order*/ say if ord**2\==w then call err "matrix elements don't form a square matrix." say center(hdr, ((width+1)*w)%ord, sep) say do row=1 for ord; z='' do col=1 for ord; n=n+1 a.row.col=word(x,n) if col<=row then  !.row.col=a.row.col z=z right( format(a.row.col,, dPlaces) / 1, width) end /*col*/ say z end /*row*/ return /*----------------------------------------------------------------------------*/ sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=''; m.=9 numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ numeric digits d; return (g/1)i /*make complex if X < 0.*/
http://rosettacode.org/wiki/Cheryl%27s_birthday
Cheryl's birthday
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the   month   of birth,   and Bernard the   day   (of the month)   of birth. 1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too. 2) Bernard: At first I don't know when Cheryl's birthday is, but I know now. 3) Albert: Then I also know when Cheryl's birthday is. Task Write a computer program to deduce, by successive elimination, Cheryl's birthday. Related task Sum and Product Puzzle References Wikipedia article of the same name. Tuple Relational Calculus
#REXX
REXX
/*REXX pgm finds Cheryl's birth date based on a person knowing the birth month, another */ /*──────────────────────── person knowing the birth day, given a list of possible dates.*/ $= 'May-15 May-16 May-19 June-17 June-18 July-14 July-16 August-14 August-15 August-17' call delDays unique('day') $= unique('day') $= unique('month') if words($)==1 then say "Cheryl's birthday is" translate($, , '-') else say "error in the program's logic." exit 0 /*──────────────────────────────────────────────────────────────────────────────────────*/ unique: arg u 2, dups; #= words($); $$= $ do j=# to 2 by -1 if u=='D' then parse value word($, j) with '-' x else parse value word($, j) with x '-' do k=1 for j-1 if u=='D' then parse value word($, k) with '-' y else parse value word($, k) with y '-' if x==y then dups= dups k j end /*k*/ end /*j*/ do d=# for # by -1 do p=1 for words(dups) until ?==d;  ?= word(dups,p) if ?==d then $$= delword($$, ?, 1) end /*d*/ end /*d*/ if words($$)==0 then return $ else return $$ /*──────────────────────────────────────────────────────────────────────────────────────*/ delDays: parse arg days; #= words(days) do j=# for # by -1; parse value word(days, j) with x '-'; ##= words($) do k=## for ## by -1; parse value word($, k) with y '-' if x\==y then iterate; $= delword($, k, 1) end /*k*/ end /*j*/ return $
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
#MiniScript
MiniScript
seq = [0, "foo", pi] seq.push 42 seq = seq + [1, 2, 3] print seq
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
#Prolog
Prolog
:- use_module(library(clpfd)).   comb_clpfd(L, M, N) :- length(L, M), L ins 1..N, chain(L, #<), label(L).