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/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.
#SNOBOL4
SNOBOL4
A = "true" * "if-then-else" if A "true" :s(goTrue)f(goFalse) goTrue output = "A is TRUE" :(fi) goFalse output = "A is not TRUE" :(fi) fi   * "switch" switch A ("true" | "false") . switch :s($("case" switch))f(default) casetrue output = "A is TRUE" :(esac) casefalse output = "A is FALSE" :(esac) default output = "A is neither FALSE nor TRUE" esac end
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}}} .
#M2000_Interpreter
M2000 Interpreter
  Function ChineseRemainder(n(), a()) { Function mul_inv(a, b) { if b==1 then =1 : exit b0=b x1=1 : x0=0 while a>1 q=a div b t=b : b=a mod b: a=t t=x0: x0=x1-q*x0:x1=t end while if x1<0 then x1+=b0 =x1 } def p, i, prod=1, sum for i=0 to len(n())-1 {prod*=n(i)} for i=0 to len(a())-1 p=prod div n(i) sum+=a(i)*mul_inv(p, n(i))*p next =sum mod prod } Print ChineseRemainder((3,5,7), (2,3,2))  
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}}} .
#Maple
Maple
> chrem( [2, 3, 2], [3, 5, 7] ); 23  
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.
#Vlang
Vlang
fn chowla(n int) int { if n < 1 { panic("argument must be a positive integer") } mut sum := 0 for i := 2; i*i <= n; i++ { if n%i == 0 { j := n / i if i == j { sum += i } else { sum += i + j } } } return sum }   fn sieve(limit int) []bool { // True denotes composite, false denotes prime. // Only interested in odd numbers >= 3 mut c := []bool{len: limit} for i := 3; i*3 < limit; i += 2 { if !c[i] && chowla(i) == 0 { for j := 3 * i; j < limit; j += 2 * i { c[j] = true } } } return c }   fn main() { for i := 1; i <= 37; i++ { println("chowla(${i:2}) = ${chowla(i)}") } println('')   mut count := 1 mut limit := int(1e7) c := sieve(limit) mut power := 100 for i := 3; i < limit; i += 2 { if !c[i] { count++ } if i == power-1 { println("Count of primes up to ${power:-10} = $count") power *= 10 } }   println('') count = 0 limit = 35000000 for i := 2; ; i++ { p := (1 << (i -1)) * ((1<<i) - 1) if p > limit { break } if chowla(p) == p-1 { println("$p is a perfect number") count++ } } println("There are $count perfect numbers <= 35,000,000") }
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.
#Wren
Wren
import "./fmt" for Fmt import "./math" for Int, Nums   var chowla = Fn.new { |n| (n > 1) ? Nums.sum(Int.properDivisors(n)) - 1 : 0 }   for (i in 1..37) Fmt.print("chowla($2d) = $d", i, chowla.call(i)) System.print() var count = 1 var limit = 1e7 var c = Int.primeSieve(limit, false) var power = 100 var i = 3 while (i < limit) { if (!c[i]) count = count + 1 if (i == power - 1) { Fmt.print("Count of primes up to $,-10d = $,d", power, count) power = power * 10 } i = i + 2 } System.print() count = 0 limit = 35 * 1e6 i = 2 while (true) { var p = (1 << (i -1)) * ((1<<i) - 1) // perfect numbers must be of this form if (p > limit) break if (chowla.call(p) == p-1) { Fmt.print("$,d is a perfect number", p) count = count + 1 } i = i + 1 } System.print("There are %(count) perfect numbers <= 35,000,000")
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.
#Object_Pascal
Object Pascal
type MyClass = object variable: integer; constructor init; destructor done; procedure someMethod; end;   constructor MyClass.init; begin variable := 0; end;   procedure MyClass.someMethod; begin variable := 1; end;   var instance: MyClass; { as variable } pInstance: ^MyClass; { on free store }   begin { create instances } instance.init; new(pInstance, init); { alternatively: pInstance := new(MyClass, init); }   { call method } instance.someMethod; pInstance^.someMethod;   { get rid of the objects } instance.done; dispose(pInstance, done); end;
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)
#Prolog
Prolog
  % main predicate, find and print closest point do_find_closest_points(Points) :- points_closest(Points, points(point(X1,Y1),point(X2,Y2),Dist)), format('Point 1 : (~p, ~p)~n', [X1,Y1]), format('Point 1 : (~p, ~p)~n', [X2,Y2]), format('Distance: ~p~n', [Dist]).   % Find the distance between two points distance(point(X1,Y1), point(X2,Y2), points(point(X1,Y1),point(X2,Y2),Dist)) :- Dx is X2 - X1, Dy is Y2 - Y1, Dist is sqrt(Dx * Dx + Dy * Dy).   % find the closest point that relatest to another point point_closest(Points, Point, Closest) :- select(Point, Points, Remaining), maplist(distance(Point), Remaining, PointList), foldl(closest, PointList, 0, Closest).   % find the closest point/dist pair for all points points_closest(Points, Closest) :- maplist(point_closest(Points), Points, ClosestPerPoint), foldl(closest, ClosestPerPoint, 0, Closest).   % used by foldl to get the lowest point/distance combination closest(points(P1,P2,Dist), 0, points(P1,P2,Dist)). closest(points(_,_,Dist), points(P1,P2,Dist2), points(P1,P2,Dist2)) :- Dist2 < Dist. closest(points(P1,P2,Dist), points(_,_,Dist2), points(P1,P2,Dist)) :- Dist =< Dist2.  
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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
Off[Solve::ratnz]; circs::invrad = "The radius is invalid."; circs::equpts = "The given points (`1`, `2`) are equivalent."; circs::dist = "The given points (`1`, `2`) and (`3`, `4`) are too far apart for \ radius `5`."; circs[_, _, 0.] := Message[circs::invrad]; circs[{p1x_, p1y_}, {p1x_, p1y_}, _] := Message[circs::equpts, p1x, p1y]; circs[p1 : {p1x_, p1y_}, p2 : {p2x_, p2y_}, r_] /; EuclideanDistance[p1, p2] > 2 r := Message[circs::dist, p1x, p1y, p2x, p2y, r]; circs[p1 : {p1x_, p1y_}, p2 : {p2x_, p2y_}, r_] := Values /@ Solve[Abs[x - p1x]^2 + Abs[y - p1y]^2 == Abs[x - p2x]^2 + Abs[y - p2y]^2 == r^2, {x, y}];
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).
#Nim
Nim
import strformat   const ANIMALS: array[12, string] = ["Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"]   const ASPECTS: array[2, string] = ["Yang", "Yin"]   const ELEMENTS: array[5, string] = ["Wood", "Fire", "Earth", "Metal", "Water"]   const STEMS: array[10, string] = ["甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"]   const BRANCHES: array[12, string] = ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"]   const S_NAMES: array[10, string] = ["jiă", "yĭ", "bĭng", "dīng", "wù", "jĭ", "gēng", "xīn", "rén", "gŭi"]   const B_NAMES: array[12, string] = ["zĭ", "chŏu", "yín", "măo", "chén", "sì", "wŭ", "wèi", "shēn", "yŏu", "xū", "hài"]   proc chineseZodiac(year: int): string = let y = year - 4 let s = y mod 10 let b = y mod 12 let stem = STEMS[s] let branch = BRANCHES[b] let name = S_NAMES[s] & "-" & B_NAMES[b] let element = ELEMENTS[s div 2] let animal = ANIMALS[b] let aspect = ASPECTS[s mod 2] let cycle = y mod 60 + 1 &"{year} {stem}{branch} {name:9} {element:7} {animal:7} {aspect:6} {cycle:02}/60"   let years = [1935, 1938, 1968, 1972, 1976, 1984, 2017, 2020] echo "Year Chinese Pinyin Element Animal Aspect Cycle" echo "---- ------- ------ ------- ------ ------ -----" for year in years: echo &"{chineseZodiac(year)}"
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).
#Pascal
Pascal
type animalCycle = (rat, ox, tiger, rabbit, dragon, snake, horse, goat, monkey, rooster, dog, pig); elementCycle = (wood, fire, earth, metal, water); aspectCycle = (yang, yin);   zodiac = record animal: animalCycle; element: elementCycle; aspect: aspectCycle; end;   function getZodiac(year: integer): zodiac; begin year := pred(year, 4); getZodiac := zodiac[ animal: succ(rat, year mod 12); element: succ(wood, year mod 10 div 2); aspect: succ(yang, year mod 2); ] end;
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
#Factor
Factor
: print-exists? ( path -- ) [ write ": " write ] [ exists? "exists." "doesn't exist." ? print ] bi ;   { "input.txt" "/input.txt" "docs" "/docs" } [ print-exists? ] each
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
#Forth
Forth
: .exists ( str len -- ) 2dup file-status nip 0= if ." exists" else ." does not exist" then type ; s" input.txt" .exists s" /input.txt" .exists s" docs" .exists s" /docs" .exists
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
#JavaScript
JavaScript
<html>   <head>   <meta charset="UTF-8">   <title>Chaos Game</title>   </head>   <body>   <p> <canvas id="sierpinski" width=400 height=346></canvas> </p>   <p> <button onclick="chaosGame()">Click here to see a Sierpiński triangle</button> </p>   <script>   function chaosGame() { var canv = document.getElementById('sierpinski').getContext('2d'); var x = Math.random() * 400; var y = Math.random() * 346; for (var i=0; i<30000; i++) { var vertex = Math.floor(Math.random() * 3); switch(vertex) { case 0: x = x / 2; y = y / 2; canv.fillStyle = 'green'; break; case 1: x = 200 + (200 - x) / 2 y = 346 - (346 - y) / 2 canv.fillStyle = 'red'; break; case 2: x = 400 - (400 - x) / 2 y = y / 2; canv.fillStyle = 'blue'; } canv.fillRect(x,y, 1,1); } }   </script>   </body>   </html>
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.
#Phix
Phix
-- -- demo\rosetta\ChatServer.exw -- ======================== -- -- translation of (qchat) chatServ.exw -- -- Run this first, then ChatClient.exw, see also IRC_Gateway.exw -- -- Note that I've only got a 32-bit windows eulibnet.dll, but it should not -- be dificult to use a "real" libnet.dll/so, or something a little newer. -- without js include pGUI.e constant dl = `Download rosetta\eulibnet\ from http://phix.x10.mx/pmwiki/pmwiki.php?n=Main.Eulibnet` assert(get_file_type("eulibnet")=FILETYPE_DIRECTORY,dl) include eulibnet/eulibnet.ew Ihandle log_list, log_window, statusbar, timer atom listconn constant IP = "127.0.0.1", port = "29029", IPaddress = IP & ":" & port constant MAX_MSG = 550 sequence connections = {}, nicknames = {} constant max_log_len = 300 procedure log_to_window(string txt) integer count = to_number(IupGetAttribute(log_list,"COUNT")) if count > max_log_len then for t=1 to count-max_log_len do IupSetAttribute(log_list,"REMOVEITEM","1") end for end if IupSetAttribute(log_list,"APPENDITEM",txt) IupSetAttribute(log_list,"TOPITEM",IupGetAttribute(log_list,"COUNT")) IupUpdate(log_list) end procedure procedure message(string msg, sequence args={}) if length(args) then msg = sprintf(msg,args) end if IupSetStrAttribute(statusbar, "TITLE", msg) log_to_window(msg) end procedure procedure shutDown() message("Shutting down euLibnet...") for i = 1 to length(connections) do if net_closeconn(connections[i]) then crash("Error closing connection!") end if end for if net_closeconn(listconn) then crash("Error closing listconn!") end if if net_shutdown() then crash("Error shutting down euLibnet!") end if end procedure procedure sendToAll(string msg) -- Send msg to all clients for i=1 to length(connections) do atom ci = connections[i] message("Sending to connection %d (%s)",{ci,nicknames[i]}) if net_send_rdm(ci, msg) then message("Error sending to connection %d",{ci}) end if end for end procedure procedure mainWindow_onOpen() message("Initializing euLibnet...") if net_init() then crash("Error initializing euLibnet!") end if message("done.") message("Initializing driver...") if net_initdriver(NET_DRIVER_WSOCK_WIN) != 1 then crash("Error initializing WinSock driver!") end if message("done.") message("Opening port " & IPaddress & "...") listconn = net_openconn(NET_DRIVER_WSOCK_WIN, IPaddress) if listconn = NULL then crash("Couldn't open connection (server already running?)") end if message("done.") if net_listen(listconn) then crash("Error trying to listen to port") end if message("Listening on port " & IPaddress) end procedure function timer_cb(Ihandle /*timer*/) integer conn = net_poll_listen(listconn) if conn != NULL then connections = append(connections, conn) nicknames = append(nicknames, "") message("New connection open from " & net_getpeer(conn)) end if -- Check for messages from clients for i = 1 to length(connections) do integer ci = connections[i] if net_query_rdm(ci) > 0 then string ni = nicknames[i] --Get the message sequence msg = net_receive_rdm(ci, MAX_MSG) message("received msg \"%s\" of length %d from %d aka %s",{msg[2],msg[1],ci,ni}) if msg[1] < 0 then --Exit on error {} = net_ignore_rdm(ci) sendToAll("Server error: some data may be lost") exit end if msg = msg[2] if length(msg) > 4 and equal(msg[1..3], "/n:") then if find(msg[4..length(msg)], nicknames) then if net_send_rdm(ci, "/nt") then message("Error sending to %d",{ci}) end if else string prevname = ni ni = msg[4..length(msg)] nicknames[i] = ni if length(prevname) = 0 then sendToAll("/j:" & ni & " has joined") -- send fake "has joined"s to the new joiner, -- so that it can build a full members list (see allj) for n=1 to length(nicknames) do if n!=i then msg = "/j:" & nicknames[n] & " has joined" if net_send_rdm(ci, msg) then message("Error sending to connection %d",{ci}) exit end if end if end for else sendToAll("/c:" & prevname & " has changed name to " & ni) end if end if elsif equal(msg, "/d") then msg = "/l:"& ni & " has left" message(msg) nicknames[i..i] = {} connections[i..i] = {} sendToAll(msg) exit -- Aside: bunch of popup and file transfer stuff was here in qchat.exw, -- all ripped out in the name of keeping this short and sweet. else sendToAll(ni & ": " & msg) -- (Add nickname to message) end if end if end for return IUP_IGNORE end function function close_cb(Ihandle /*ih*/) shutDown() return IUP_DEFAULT end function IupOpen() log_list = IupList("EXPAND=YES, CANFOCUS=NO, MULTIPLE=YES") statusbar = IupLabel("Loading...","EXPAND=HORIZONTAL") log_window = IupDialog(IupVbox({log_list,statusbar}), `TITLE="Chat Server", RASTERSIZE=400x400`) IupSetCallback(log_window,"CLOSE_CB",Icallback("close_cb")) IupShow(log_window) mainWindow_onOpen() timer = IupTimer(Icallback("timer_cb"), 500) IupMainLoop() IupClose()
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.
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Numerics   Public Class BigRat ' Big Rational Class constructed with BigIntegers Implements IComparable Public nu, de As BigInteger Public Shared Zero = New BigRat(BigInteger.Zero, BigInteger.One), One = New BigRat(BigInteger.One, BigInteger.One) Sub New(bRat As BigRat) nu = bRat.nu : de = bRat.de End Sub Sub New(n As BigInteger, d As BigInteger) If d = BigInteger.Zero Then _ Throw (New Exception(String.Format("tried to set a BigRat with ({0}/{1})", n, d))) Dim bi As BigInteger = BigInteger.GreatestCommonDivisor(n, d) If bi > BigInteger.One Then n /= bi : d /= bi If d < BigInteger.Zero Then n = -n : d = -d nu = n : de = d End Sub Shared Operator -(x As BigRat) As BigRat Return New BigRat(-x.nu, x.de) End Operator Shared Operator +(x As BigRat, y As BigRat) Return New BigRat(x.nu * y.de + x.de * y.nu, x.de * y.de) End Operator Shared Operator -(x As BigRat, y As BigRat) As BigRat Return x + (-y) End Operator Shared Operator *(x As BigRat, y As BigRat) As BigRat Return New BigRat(x.nu * y.nu, x.de * y.de) End Operator Shared Operator /(x As BigRat, y As BigRat) As BigRat Return New BigRat(x.nu * y.de, x.de * y.nu) End Operator Public Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo Dim dif As BigRat = New BigRat(nu, de) - obj If dif.nu < BigInteger.Zero Then Return -1 If dif.nu > BigInteger.Zero Then Return 1 Return 0 End Function Shared Operator =(x As BigRat, y As BigRat) As Boolean Return x.CompareTo(y) = 0 End Operator Shared Operator <>(x As BigRat, y As BigRat) As Boolean Return x.CompareTo(y) <> 0 End Operator Overrides Function ToString() As String If de = BigInteger.One Then Return nu.ToString Return String.Format("({0}/{1})", nu, de) End Function Shared Function Combine(a As BigRat, b As BigRat) As BigRat Return (a + b) / (BigRat.One - (a * b)) End Function End Class   Public Structure Term ' coefficent, BigRational construction for each term Dim c As Integer, br As BigRat Sub New(cc As Integer, bigr As BigRat) c = cc : br = bigr End Sub End Structure   Module Module1 Function Eval(c As Integer, x As BigRat) As BigRat If c = 1 Then Return x Else If c < 0 Then Return Eval(-c, -x) Dim hc As Integer = c \ 2 Return BigRat.Combine(Eval(hc, x), Eval(c - hc, x)) End Function   Function Sum(terms As List(Of Term)) As BigRat If terms.Count = 1 Then Return Eval(terms(0).c, terms(0).br) Dim htc As Integer = terms.Count / 2 Return BigRat.Combine(Sum(terms.Take(htc).ToList), Sum(terms.Skip(htc).ToList)) End Function   Function ParseLine(ByVal s As String) As List(Of Term) ParseLine = New List(Of Term) : Dim t As String = s.ToLower, p As Integer, x As New Term(1, BigRat.Zero) While t.Contains(" ") : t = t.Replace(" ", "") : End While p = t.IndexOf("pi/4=") : If p < 0 Then _ Console.WriteLine("warning: tan(left side of equation) <> 1") : ParseLine.Add(x) : Exit Function t = t.Substring(p + 5) For Each item As String In t.Split(")") If item.Length > 5 Then If (Not item.Contains("tan") OrElse item.IndexOf("a") < 0 OrElse item.IndexOf("a") > item.IndexOf("tan")) AndAlso Not item.Contains("atn") Then Console.WriteLine("warning: a term is mising a valid arctangent identifier on the right side of the equation: [{0})]", item) ParseLine = New List(Of Term) : ParseLine.Add(New Term(1, BigRat.Zero)) : Exit Function End If x.c = 1 : x.br = New BigRat(BigRat.One) p = item.IndexOf("/") : If p > 0 Then x.br.de = UInt64.Parse(item.Substring(p + 1)) item = item.Substring(0, p) p = item.IndexOf("(") : If p > 0 Then x.br.nu = UInt64.Parse(item.Substring(p + 1)) p = item.IndexOf("a") : If p > 0 Then Integer.TryParse(item.Substring(0, p).Replace("*", ""), x.c) If x.c = 0 Then x.c = 1 If item.Contains("-") AndAlso x.c > 0 Then x.c = -x.c End If ParseLine.Add(x) End If End If End If Next End Function   Sub Main(ByVal args As String()) Dim nl As String = vbLf For Each item In ("pi/4 = ATan(1 / 2) + ATan(1/3)" & nl & "pi/4 = 2Atan(1/3) + ATan(1/7)" & nl & "pi/4 = 4ArcTan(1/5) - ATan(1 / 239)" & nl & "pi/4 = 5arctan(1/7) + 2 * atan(3/79)" & nl & "Pi/4 = 5ATan(29/278) + 7*ATan(3/79)" & nl & "pi/4 = atn(1/2) + ATan(1/5) + ATan(1/8)" & nl & "PI/4 = 4ATan(1/5) - Atan(1/70) + ATan(1/99)" & nl & "pi /4 = 5*ATan(1/7) + 4 ATan(1/53) + 2ATan(1/4443)" & nl & "pi / 4 = 6ATan(1/8) + 2arctangent(1/57) + ATan(1/239)" & nl & "pi/ 4 = 8ATan(1/10) - ATan(1/239) - 4ATan(1/515)" & nl & "pi/4 = 12ATan(1/18) + 8ATan(1/57) - 5ATan(1/239)" & nl & "pi/4 = 16 * ATan(1/21) + 3ATan(1/239) + 4ATan(3/1042)" & nl & "pi/4 = 22ATan(1/28) + 2ATan(1/443) - 5ATan(1/1393) - 10 ATan( 1 / 11018 )" & nl & "pi/4 = 22ATan(1/38) + 17ATan(7/601) + 10ATan(7 / 8149)" & nl & "pi/4 = 44ATan(1/57) + 7ATan(1/239) - 12ATan(1/682) + 24ATan(1/12943)" & nl & "pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12943)" & nl & "pi/4 = 88ATan(1/172) + 51ATan(1/239) + 32ATan(1/682) + 44ATan(1/5357) + 68ATan(1/12944)").Split(nl) Console.WriteLine("{0}: {1}", If(Sum(ParseLine(item)) = BigRat.One, "Pass", "Fail"), item) Next End Sub End Module
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.
#Delphi
Delphi
program Project1;   {$APPTYPE CONSOLE}   uses SysUtils; var aChar:Char; aCode:Byte; uChar:WideChar; uCode:Word; begin aChar := Chr(97); Writeln(aChar); aCode := Ord(aChar); Writeln(aCode); uChar := WideChar(97); Writeln(uChar); uCode := Ord(uChar); Writeln(uCode);   Readln; end.
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.
#PARI.2FGP
PARI/GP
cholesky(M) = { my (L = matrix(#M,#M));   for (i = 1, #M, for (j = 1, i, s = sum (k = 1, j-1, L[i,k] * L[j,k]); L[i,j] = if (i == j, sqrt(M[i,i] - s), (M[i,j] - s) / L[j,j]) ) ); 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
#Ruby
Ruby
dates = [ ["May", 15], ["May", 16], ["May", 19], ["June", 17], ["June", 18], ["July", 14], ["July", 16], ["August", 14], ["August", 15], ["August", 17], ]   print dates.length, " remaining\n"   # the month cannot have a unique day uniqueMonths = dates.group_by { |m,d| d } .select { |k,v| v.size == 1 } .map { |k,v| v.flatten } .map { |m,d| m } dates.delete_if { |m,d| uniqueMonths.include? m } print dates.length, " remaining\n"   # the day must be unique dates = dates .group_by { |m,d| d } .select { |k,v| v.size == 1 } .map { |k,v| v.flatten } print dates.length, " remaining\n"   # the month must now be unique dates = dates .group_by { |m,d| m } .select { |k,v| v.size == 1 } .map { |k,v| v } .flatten print dates
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
#MS_SmallBasic
MS SmallBasic
  ll=LDList.CreateFromValues("") LDList.Add(ll "Cars") LDList.Add(ll "Toys") LDList.Print(ll)  
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
#Pure
Pure
comb m n = comb m (0..n-1) with comb 0 _ = [[]]; comb _ [] = []; comb m (x:xs) = [x:xs | xs = comb (m-1) xs] + comb m xs; end;   comb 3 5;
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include if-then-else and switch. Less common are arithmetic if, ternary operator and Hash-based conditionals. Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
#SNUSP
SNUSP
$==?\==zero=====!/==# \==non zero==/
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}}} .
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ChineseRemainder[{2, 3, 2}, {3, 5, 7}] 23
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}}} .
#MATLAB_.2F_Octave
MATLAB / Octave
function f = chineseRemainder(r, m) s = prod(m) ./ m; [~, t] = gcd(s, m); f = s .* t * r';
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.
#XPL0
XPL0
func Chowla(N); \Return sum of divisors int N, Div, Sum, Quot; [Div:= 2; Sum:= 0; loop [Quot:= N/Div; if Quot < Div then quit; if Quot = Div and rem(0) = 0 then \N is a square [Sum:= Sum+Quot; quit]; if rem(0) = 0 then Sum:= Sum + Div + Quot; Div:= Div+1; ]; return Sum; ];   int N, C, P; [for N:= 1 to 37 do [IntOut(0, N); Text(0, ": "); IntOut(0, Chowla(N)); CrLf(0); ]; C:= 1; \count 2 as prime N:= 3; \only check odd numbers repeat if Chowla(N) = 0 then \N is prime C:= C+1; case N+1 of 100, 1000, 10_000, 100_000, 1_000_000, 10_000_000: [Text(0, "There are "); IntOut(0, C); Text(0, " primes < "); IntOut(0, N+1); CrLf(0)] other []; N:= N+2; until N >= 10_000_000; P:= 1; \perfect numbers are of form: 2^(P-1) * (2^P - 1) loop [P:= P*2; N:= P*(P*2-1); if N > 35_000_000 then quit; if Chowla(N) = N-1 then \N is perfect [IntOut(0, N); CrLf(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.
#zkl
zkl
fcn chowla(n){ if(n<1) throw(Exception.ValueError("Chowla function argument must be positive")); sum:=0; foreach i in ([2..n.toFloat().sqrt()]){ if(n%i == 0){ j:=n/i; if(i==j) sum+=i; else sum+=i+j; } } sum }   fcn chowlaSieve(limit){ // True denotes composite, false denotes prime. // Only interested in odd numbers >= 3 c:=Data(limit+100).fill(0); # slop at the end (for reverse wrap around) foreach i in ([3..limit/3,2]){ if(not c[i] and chowla(i)==0) { foreach j in ([3*i..limit,2*i]){ c[j]=True } } } c }
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.
#Objective-C
Objective-C
// There are no class variables, so static variables are used. static int myClassVariable = 0;   @interface MyClass : NSObject { int variable; // instance variable }   - (int)variable; // Typical accessor - you should use the same name as the variable   @end
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)
#PureBasic
PureBasic
Procedure.d bruteForceClosestPair(Array P.coordinate(1)) Protected N=ArraySize(P()), i, j Protected mindistance.f=Infinity(), t.d Shared a, b If N<2 a=0: b=0 Else For i=0 To N-1 For j=i+1 To N t=Pow(Pow(P(i)\x-P(j)\x,2)+Pow(P(i)\y-P(j)\y,2),0.5) If mindistance>t mindistance=t a=i: b=j EndIf Next Next EndIf ProcedureReturn mindistance EndProcedure  
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
#Maxima
Maxima
/* define helper function */ vabs(a):= sqrt(a.a); realp(e):=freeof(%i, e);   /* get a general solution */ sol: block( [p1: [x1, y1], p2: [x2, y2], c: [x0, y0], eq], local(r), eq: [vabs(p1-c) = r, vabs(p2-c) = r], load(to_poly_solve), assume(r>0), args(to_poly_solve(eq, c, use_grobner = true)))$   /* use general solution for concrete case */ getsol(sol, x1, y1, x2, y2, r):=block([n, lsol], if [x1, y1]=[x2, y2] then ( print("infinity many solutions"), return('infmany)), lsol: sublist(''sol, 'realp), n: length(lsol), if n=0 then ( print("no solutions"), []) else if n=1 then ( print("single solution"), lsol[1]) else if [assoc('x0, lsol[1]), assoc('y0, lsol[1])]=[assoc('x0, lsol[2]), assoc('y0, lsol[2])] then ( print("single solution"), lsol[1]) else ( print("two solutions"), lsol))$   /* [x1, y1, x2, y2, r] */ d[1]: [0.1234, 0.9876, 0.8765, 0.2345, 2]; d[2]: [0.0000, 2.0000, 0.0000, 0.0000, 1]; d[3]: [0, 0, 0, 1, 0.4]; d[4]: [0, 0, 0, 0, 0.4];   apply('getsol, cons(sol, d[1])); apply('getsol, cons(sol, d[2])); apply('getsol, cons(sol, d[3])); apply('getsol, cons(sol, d[4]));
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).
#Perl
Perl
sub zodiac { my $year = shift; my @animals = qw/Rat Ox Tiger Rabbit Dragon Snake Horse Goat Monkey Rooster Dog Pig/; my @elements = qw/Wood Fire Earth Metal Water/; my @terrestrial_han = qw/子 丑 寅 卯 辰 巳 午 未 申 酉 戌 亥/; my @terrestrial_pinyin = qw/zĭ chŏu yín măo chén sì wŭ wèi shēn yŏu xū hài/; my @celestial_han = qw/甲 乙 丙 丁 戊 己 庚 辛 壬 癸/; my @celestial_pinyin = qw/jiă yĭ bĭng dīng wù jĭ gēng xīn rén gŭi/; my @aspect = qw/yang yin/;   my $cycle_year = ($year-4) % 60; my($i2, $i10, $i12) = ($cycle_year % 2, $cycle_year % 10, $cycle_year % 12);   ($year, $celestial_han[$i10], $terrestrial_han[$i12], $celestial_pinyin[$i10], $terrestrial_pinyin[$i12], $elements[$i10 >> 1], $animals[$i12], $aspect[$i2], $cycle_year+1); }   printf("%4d: %s%s (%s-%s) %s %s; %s - year %d of the cycle\n", zodiac($_)) for (1935, 1938, 1968, 1972, 1976, 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
#Fortran
Fortran
LOGICAL :: file_exists INQUIRE(FILE="input.txt", EXIST=file_exists) ! file_exists will be TRUE if the file ! exists and FALSE otherwise INQUIRE(FILE="/input.txt", EXIST=file_exists)
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
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   ' Enable FileExists() function to be used #include "file.bi"   ' Use Win32 function to check if directory exists on Windows 10 Declare Function GetFileAttributes Lib "kernel32.dll" Alias "GetFileAttributesA" _ (ByVal lpFileName As ZString Ptr) As ULong   Const InvalidFileAttributes As ULong = -1UL Const FileAttributeDirectory As ULong = &H10UL   Sub CheckFileExists(ByRef filePath As String) If FileExists(filePath) Then Print "'"; filePath; "' exists" Else Print "'"; filePath; "' does not exist" End If End Sub   Sub CheckDirectoryExists(ByVal dirPath As ZString Ptr) Dim attrib As ULong = GetFileAttributes(dirPath) Dim dirExists As ULong = attrib <> InvalidFileAttributes AndAlso (attrib And FileAttributeDirectory) <> 0 If dirExists Then Print "'"; *dirPath; "' exists" Else Print "'"; *dirPath; "' does not exist" End If End Sub   CheckFileExists(CurDir + "\input.txt") Dim dirPath As String = CurDir + "\docs" CheckDirectoryExists(StrPtr(dirPath)) CheckFileExists("c:\input.txt") CheckDirectoryExists(StrPtr("c:\docs")) Print Print "Press any key to quit the program" Sleep
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
#Julia
Julia
using Luxor   function chaos() width = 1000 height = 1000 Drawing(width, height, "./chaos.png") t = Turtle(0, 0, true, 0, (0., 0., 0.)) x = rand(1:width) y = rand(1:height)   for l in 1:30_000 v = rand(1:3) if v == 1 x /= 2 y /= 2 elseif v == 2 x = width/2 + (width/2 - x)/2 y = height - (height - y)/2 else x = width - (width - x)/2 y = y / 2 end Reposition(t, x, height-y) Circle(t, 3) end end   chaos() finish() preview()  
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
#Kotlin
Kotlin
//Version 1.1.51   import java.awt.* import java.util.Stack import java.util.Random import javax.swing.JPanel import javax.swing.JFrame import javax.swing.Timer import javax.swing.SwingUtilities   class ChaosGame : JPanel() {   class ColoredPoint(x: Int, y: Int, val colorIndex: Int) : Point(x, y)   val stack = Stack<ColoredPoint>() val points: List<Point> val colors = listOf(Color.red, Color.green, Color.blue) val r = Random()   init { val dim = Dimension(640, 640) preferredSize = dim background = Color.white val margin = 60 val size = dim.width - 2 * margin points = listOf( Point(dim.width / 2, margin), Point(margin, size), Point(margin + size, size) ) stack.push(ColoredPoint(-1, -1, 0))   Timer(10) { if (stack.size < 50_000) { for (i in 0 until 1000) addPoint() repaint() } }.start() }   private fun addPoint() { val colorIndex = r.nextInt(3) val p1 = stack.peek() val p2 = points[colorIndex] stack.add(halfwayPoint(p1, p2, colorIndex)) }   fun drawPoints(g: Graphics2D) { for (cp in stack) { g.color = colors[cp.colorIndex] g.fillOval(cp.x, cp.y, 1, 1) } }   fun halfwayPoint(a: Point, b: Point, idx: Int) = ColoredPoint((a.x + b.x) / 2, (a.y + b.y) / 2, idx)   override fun paintComponent(gg: Graphics) { super.paintComponent(gg) val g = gg as Graphics2D g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) drawPoints(g) } }   fun main(args: Array<String>) { SwingUtilities.invokeLater { val f = JFrame() with (f) { defaultCloseOperation = JFrame.EXIT_ON_CLOSE title = "Chaos Game" isResizable = false add(ChaosGame(), BorderLayout.CENTER) pack() setLocationRelativeTo(null) isVisible = 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.
#PicoLisp
PicoLisp
#!/usr/bin/picolisp /usr/lib/picolisp/lib.l   (de chat Lst (out *Sock (mapc prin Lst) (prinl) ) )   (setq *Port (port 4004))   (loop (setq *Sock (listen *Port)) (NIL (fork) (close *Port)) (close *Sock) )   (out *Sock (prin "Please enter your name: ") (flush) ) (in *Sock (setq *Name (line T)))   (tell 'chat "+++ " *Name " arrived +++")   (task *Sock (in @ (ifn (eof) (tell 'chat *Name "> " (line T)) (tell 'chat "--- " *Name " left ---") (bye) ) ) ) (wait)
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.
#Wren
Wren
import "/big" for BigRat import "/fmt" for Fmt   /** represents a term of the form: c * atan(n / d) */ class Term { construct new(c, n, d) { _c = c _n = n _d = d }   c { _c } n { _n } d { _d }   toString { var a = "atan(%(n)/%(d))" return ((_c == 1) ? " + " : (_c == -1) ? " - " : (_c < 0) ? " - %(-c)*" : " + %(c)*") + a } }   var tanEval // recursive function tanEval = Fn.new { |c, f| if (c == 1) return f if (c < 0) return -tanEval.call(-c, f) var ca = (c/2).truncate var cb = c - ca var a = tanEval.call(ca, f) var b = tanEval.call(cb, f) return (a + b) / (BigRat.one - (a * b)) }   var tanSum // recursive function tanSum = Fn.new { |terms| if (terms.count == 1) return tanEval.call(terms[0].c, BigRat.new(terms[0].n, terms[0].d)) var half = (terms.count/2).floor var a = tanSum.call(terms.take(half).toList) var b = tanSum.call(terms.skip(half).toList) return (a + b) / (BigRat.one - (a * b)) }   var T = Term // type alias   var termsList = [ [T.new(1, 1, 2), T.new(1, 1, 3)], [T.new(2, 1, 3), T.new(1, 1, 7)], [T.new(4, 1, 5), T.new(-1, 1, 239)], [T.new(5, 1, 7), T.new(2, 3, 79)], [T.new(5, 29, 278), T.new(7, 3, 79)], [T.new(1, 1, 2), T.new(1, 1, 5), T.new(1, 1, 8)], [T.new(4, 1, 5), T.new(-1, 1, 70), T.new(1, 1, 99)], [T.new(5, 1, 7), T.new(4, 1, 53), T.new(2, 1, 4443)], [T.new(6, 1, 8), T.new(2, 1, 57), T.new(1, 1, 239)], [T.new(8, 1, 10), T.new(-1, 1, 239), T.new(-4, 1, 515)], [T.new(12, 1, 18), T.new(8, 1, 57), T.new(-5, 1, 239)], [T.new(16, 1, 21), T.new(3, 1, 239), T.new(4, 3, 1042)], [T.new(22, 1, 28), T.new(2, 1, 443), T.new(-5, 1, 1393), T.new(-10, 1, 11018)], [T.new(22, 1, 38), T.new(17, 7, 601), T.new(10, 7, 8149)], [T.new(44, 1, 57), T.new(7, 1, 239), T.new(-12, 1, 682), T.new(24, 1, 12943)], [T.new(88, 1, 172), T.new(51, 1, 239), T.new(32, 1, 682), T.new(44, 1, 5357), T.new(68, 1, 12943)], [T.new(88, 1, 172), T.new(51, 1, 239), T.new(32, 1, 682), T.new(44, 1, 5357), T.new(68, 1, 12944)] ]   for (terms in termsList) { var f = Fmt.swrite("$-5s: 1 == tan(", tanSum.call(terms) == BigRat.one) System.write(f) System.write(terms[0].toString.skip(3).join()) for (i in 1...terms.count) System.write(terms[i]) System.print(")") }
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.
#Dyalect
Dyalect
print('a'.Order()) print(Char(97))
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.
#DWScript
DWScript
PrintLn(Ord('a')); PrintLn(Chr(97));
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.
#Pascal
Pascal
program CholeskyApp;   type D2Array = array of array of double;   function cholesky(const A: D2Array): D2Array; var i, j, k: integer; s: double; begin setlength(Result, length(A), length(A)); for i := low(Result) to high(Result) do for j := 0 to i do begin s := 0; for k := 0 to j - 1 do s := s + Result[i][k] * Result[j][k]; if i = j then Result[i][j] := sqrt(A[i][i] - s) else Result[i][j] := (A[i][j] - s) / Result[j][j]; // save one multiplication compared to the original end; end;   procedure printM(const A: D2Array); var i, j: integer; begin for i := low(A) to high(A) do begin for j := low(A) to high(A) do write(A[i, j]: 8: 5); writeln; end; end;   const m1: array[0..2, 0..2] of double = ((25, 15, -5), (15, 18, 0), (-5, 0, 11)); m2: array[0..3, 0..3] of double = ((18, 22, 54, 42), (22, 70, 86, 62), (54, 86, 174, 134), (42, 62, 134, 106));   var index, i: integer; cIn, cOut: D2Array;   begin setlength(cIn, length(m1), length(m1)); for index := low(m1) to high(m1) do begin SetLength(cIn[index], length(m1[index])); for i := 0 to High(m1[Index]) do cIn[index][i] := m1[index][i]; end; cOut := cholesky(cIn); printM(cOut);   writeln;   setlength(cIn, length(m2), length(m2)); for index := low(m2) to high(m2) do begin SetLength(cIn[index], length(m2[Index])); for i := 0 to High(m2[Index]) do cIn[index][i] := m2[index][i]; end; cOut := cholesky(cIn); printM(cOut); end.
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
#Rust
Rust
  // This version is based on the Go version on Rosettacode   #[derive(PartialEq, Debug, Copy, Clone)] enum Month { May, June, July, August, }   #[derive(PartialEq, Debug, Copy, Clone)] struct Birthday { month: Month, day: u8, }   impl Birthday { fn month_unique_in(&self, birthdays: &[Birthday]) -> bool { birthdays .iter() .filter(|birthday| birthday.month == self.month) .count() == 1 }   fn day_unique_in(&self, birthdays: &[Birthday]) -> bool { birthdays .iter() .filter(|birthday| birthday.day == self.day) .count() == 1 }   fn month_with_unique_day_in(&self, birthdays: &[Birthday]) -> bool { birthdays .iter() .any(|birthday| self.month == birthday.month && birthday.day_unique_in(birthdays)) } }   fn solution() -> Option<Birthday> { let mut choices: Vec<Birthday> = vec![ Birthday { month: Month::May, day: 15, }, Birthday { month: Month::May, day: 16, }, Birthday { month: Month::May, day: 19, }, Birthday { month: Month::June, day: 17, }, Birthday { month: Month::June, day: 18, }, Birthday { month: Month::July, day: 14, }, Birthday { month: Month::July, day: 16, }, Birthday { month: Month::August, day: 14, }, Birthday { month: Month::August, day: 15, }, Birthday { month: Month::August, day: 17, }, ];   // Albert knows the month but doesn't know the day. // So the month can't be unique within the choices. let choices_copy = choices.clone(); choices.retain(|birthday| !(&birthday.month_unique_in(&choices_copy)));   // Albert also knows that Bernard doesn't know the answer. // So the month can't have a unique day. let choices_copy = choices.clone(); choices.retain(|birthday| !(birthday.month_with_unique_day_in(&choices_copy)));   // Bernard now knows the answer. // So the day must be unique within the remaining choices. let choices_copy = choices.clone(); choices.retain(|birthday| birthday.day_unique_in(&choices_copy));   // Albert now knows the answer too. // So the month must be unique within the remaining choices. let choices_copy = choices.clone(); choices.retain(|birthday| birthday.month_unique_in(&choices_copy));   if choices.len() == 1 { Some(choices[0]) } else { None } }   fn main() { match solution() { Some(solution) => println!("Cheryl's birthday is {:?}", solution), None => panic!("Didn't work!"), } }    
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
#Scala
Scala
import java.time.format.DateTimeFormatter import java.time.{LocalDate, Month}   object Cheryl { def main(args: Array[String]): Unit = { val choices = List( LocalDate.of(2019, Month.MAY, 15), LocalDate.of(2019, Month.MAY, 16), LocalDate.of(2019, Month.MAY, 19),   LocalDate.of(2019, Month.JUNE, 17), LocalDate.of(2019, Month.JUNE, 18),   LocalDate.of(2019, Month.JULY, 14), LocalDate.of(2019, Month.JULY, 16),   LocalDate.of(2019, Month.AUGUST, 14), LocalDate.of(2019, Month.AUGUST, 15), LocalDate.of(2019, Month.AUGUST, 17) )   // The month cannot have a unique day because Albert knows the month, and knows that Bernard does not know the answer val uniqueMonths = choices.groupBy(_.getDayOfMonth) .filter(a => a._2.length == 1) .flatMap(a => a._2) .map(a => a.getMonth) val filter1 = choices.filterNot(a => uniqueMonths.exists(b => a.getMonth == b))   // Bernard now knows the answer, so the day must be unique within the remaining choices val uniqueDays = filter1.groupBy(_.getDayOfMonth) .filter(a => a._2.length == 1) .flatMap(a => a._2) .map(a => a.getDayOfMonth) val filter2 = filter1.filter(a => uniqueDays.exists(b => a.getDayOfMonth == b))   // Albert knows the answer too, so the month must be unique within the remaining choices val birthDay = filter2.groupBy(_.getMonth) .filter(a => a._2.length == 1) .flatMap(a => a._2) .head   // print the result printf(birthDay.format(DateTimeFormatter.ofPattern("MMMM dd"))) } }
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
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   myVals = [ 'zero', 'one', 'two', 'three', 'four', 'five' ] mySet = Set mySet = HashSet()   loop val over myVals mySet.add(val) end val   loop val over mySet say val end val   return  
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
#PureBasic
PureBasic
Procedure.s Combinations(amount, choose) NewList comb.s() ; all possible combinations with {amount} Bits For a = 0 To 1 << amount count = 0 ; count set bits For x = 0 To amount If (1 << x)&a count + 1 EndIf Next ; if set bits are equal to combination length ; we generate a String representing our combination and add it to list If count = choose string$ = "" For x = 0 To amount If (a >> x)&1 ; replace x by x+1 to start counting with 1 String$ + Str(x) + " " EndIf Next AddElement(comb()) comb() = string$ EndIf Next ; now we sort our list and format it for output as string SortList(comb(), #PB_Sort_Ascending) ForEach comb() out$ + ", [ " + comb() + "]" Next ProcedureReturn Mid(out$, 3) EndProcedure   Debug Combinations(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.
#Sparkling
Sparkling
var odd = 13; if odd % 2 != 0 { print("odd"); }
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}}} .
#Modula-2
Modula-2
MODULE CRT; FROM FormatString IMPORT FormatString; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   PROCEDURE WriteInt(n : INTEGER); VAR buf : ARRAY[0..15] OF CHAR; BEGIN FormatString("%i", buf, n); WriteString(buf) END WriteInt;   PROCEDURE MulInv(a,b : INTEGER) : INTEGER; VAR b0,x0,x1,q,amb,xqx : INTEGER; BEGIN b0 := b; x0 := 0; x1 := 1;   IF b=1 THEN RETURN 1 END;   WHILE a>1 DO q := a DIV b; amb := a MOD b; a := b; b := amb; xqx := x1 - q * x0; x1 := x0; x0 := xqx END;   IF x1<0 THEN x1 := x1 + b0 END;   RETURN x1 END MulInv;   PROCEDURE ChineseRemainder(n,a : ARRAY OF INTEGER) : INTEGER; VAR i : CARDINAL; prod,p,sm : INTEGER; BEGIN prod := n[0]; FOR i:=1 TO HIGH(n) DO prod := prod * n[i] END;   sm := 0; FOR i:=0 TO HIGH(n) DO p := prod DIV n[i]; sm := sm + a[i] * MulInv(p, n[i]) * p END;   RETURN sm MOD prod END ChineseRemainder;   TYPE TA = ARRAY[0..2] OF INTEGER; VAR n,a : TA; BEGIN n := TA{3, 5, 7}; a := TA{2, 3, 2}; WriteInt(ChineseRemainder(n, a)); WriteLn;   ReadChar END CRT.
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.
#OCaml
OCaml
class my_class = object (self) val mutable variable = 0 method some_method = variable <- 1 end
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.
#Oforth
Oforth
Object Class new: MyClass(att) MyClass method: initialize(v) v := att ;
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)
#Python
Python
""" Compute nearest pair of points using two algorithms   First algorithm is 'brute force' comparison of every possible pair. Second, 'divide and conquer', is based on: www.cs.iupui.edu/~xkzou/teaching/CS580/Divide-and-conquer-closestPair.ppt """   from random import randint, randrange from operator import itemgetter, attrgetter   infinity = float('inf')   # Note the use of complex numbers to represent 2D points making distance == abs(P1-P2)   def bruteForceClosestPair(point): numPoints = len(point) if numPoints < 2: return infinity, (None, None) return min( ((abs(point[i] - point[j]), (point[i], point[j])) for i in range(numPoints-1) for j in range(i+1,numPoints)), key=itemgetter(0))   def closestPair(point): xP = sorted(point, key= attrgetter('real')) yP = sorted(point, key= attrgetter('imag')) return _closestPair(xP, yP)   def _closestPair(xP, yP): numPoints = len(xP) if numPoints <= 3: return bruteForceClosestPair(xP) Pl = xP[:numPoints/2] Pr = xP[numPoints/2:] Yl, Yr = [], [] xDivider = Pl[-1].real for p in yP: if p.real <= xDivider: Yl.append(p) else: Yr.append(p) dl, pairl = _closestPair(Pl, Yl) dr, pairr = _closestPair(Pr, Yr) dm, pairm = (dl, pairl) if dl < dr else (dr, pairr) # Points within dm of xDivider sorted by Y coord closeY = [p for p in yP if abs(p.real - xDivider) < dm] numCloseY = len(closeY) if numCloseY > 1: # There is a proof that you only need compare a max of 7 next points closestY = min( ((abs(closeY[i] - closeY[j]), (closeY[i], closeY[j])) for i in range(numCloseY-1) for j in range(i+1,min(i+8, numCloseY))), key=itemgetter(0)) return (dm, pairm) if dm <= closestY[0] else closestY else: return dm, pairm   def times(): ''' Time the different functions ''' import timeit   functions = [bruteForceClosestPair, closestPair] for f in functions: print 'Time for', f.__name__, timeit.Timer( '%s(pointList)' % f.__name__, 'from closestpair import %s, pointList' % f.__name__).timeit(number=1)       pointList = [randint(0,1000)+1j*randint(0,1000) for i in range(2000)]   if __name__ == '__main__': pointList = [(5+9j), (9+3j), (2+0j), (8+4j), (7+4j), (9+10j), (1+9j), (8+2j), 10j, (9+6j)] print pointList print ' bruteForceClosestPair:', bruteForceClosestPair(pointList) print ' closestPair:', closestPair(pointList) for i in range(10): pointList = [randrange(11)+1j*randrange(11) for i in range(10)] print '\n', pointList print ' bruteForceClosestPair:', bruteForceClosestPair(pointList) print ' closestPair:', closestPair(pointList) print '\n' times() times() times()
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
#.D0.9C.D0.9A-61.2F52
МК-61/52
П0 С/П П1 С/П П2 С/П П3 С/П П4 ИП2 ИП0 - x^2 ИП3 ИП1 - x^2 + КвКор П5 ИП0 ИП2 + 2 / П6 ИП1 ИП3 + 2 / П7 ИП4 x^2 ИП5 2 / x^2 - КвКор ИП5 / П8 ИП6 ИП1 ИП3 - ИП8 * П9 + ПA ИП6 ИП9 - ПC ИП7 ИП2 ИП0 - ИП8 * П9 + ПB ИП7 ИП9 - ПD ИП5 x#0 97 8 4 ИНВ С/П ИП4 2 * ИП5 - ПE x#0 97 ИПB ИПA 8 5 ИНВ С/П ИПE x>=0 97 8 3 ИНВ С/П ИПD ИПC ИПB ИПA С/П
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).
#Phix
Phix
with javascript_semantics constant animals = {"Rat","Ox","Tiger","Rabbit","Dragon","Snake","Horse","Goat","Monkey","Rooster","Dog","Pig"}, elements = {"Wood","Fire","Earth","Metal","Water"}, yinyang = {"yang","yin"}, years = {1935,1938,1968,1972,1976,2018} for i=1 to length(years) do integer year = years[i], cycle = mod(year-4,60) string element = elements[floor(mod(cycle,10)/2)+1], animal = animals[mod(cycle,12)+1], yy = yinyang[mod(cycle,2)+1] printf(1,"%d: %s %s; %s, year %d of the cycle.\n", {year,element,animal,yy,cycle+1}) end for
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
#Frink
Frink
  checkFile[filename] := { file = newJava["java.io.File", [filename]] if file.exists[] and file.isFile[] println["$filename is a file"] else println["$filename is not a file"] }   checkDir[filename] := { file = newJava["java.io.File", [filename]] if file.exists[] and file.isDirectory[] println["$filename is a directory"] else println["$filename is not a directory"] }   checkFile["input.txt"] checkFile["/input.txt"] checkDir["docs"] checkDir["/docs"]   // This tests the "unusual" filename with various Unicode // normalizations that would look identical to a human // For example, the á character could be written as either // the Unicode sequences // \u00e1 ('LATIN SMALL LETTER A WITH ACUTE') // or // \u0061\u0301 ('LATIN SMALL LETTER A' 'COMBINING ACUTE ACCENT') unusual = "`Abdu'l-Bahá.txt" checkFile[unusual] checkFile[normalizeUnicode[unusual, "NFC"]] checkFile[normalizeUnicode[unusual, "NFD"]]  
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
#Gambas
Gambas
Public Sub Main()   If Exist(User.Home &/ "input.txt") Then Print "'input.txt' does exist in the Home folder" If Not Exist("/input.txt") Then Print "'input.txt' does NOT exist in Root" 'Not messing With my Root files   If Exist(User.home &/ "docs/") Then Print "The folder '~/docs' does exist" If Not Exist("/docs/") Then Print "The folder '/docs' does NOT exist" 'Not messing With my Root files   File.Save(User.Home &/ "`Abdu'l-Bahá.txt", "") If Exist(User.Home &/ "`Abdu'l-Bahá.txt") Then Print "'`Abdu'l-Bahá.txt' does exist (zero length and unusual name)"   End
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
#Logo
Logo
to chaosgame :sidelength :iterations make "width :sidelength make "height (:sidelength/2 * sqrt 3) make "x (random :width) make "y (random :height) repeat :iterations [ make "vertex (random 3) if :vertex = 0 [ make "x (:x / 2) make "y (:y / 2) setpencolor "green ] if :vertex = 1 [ make "x (:width / 2 + ((:width / 2 - :x) / 2)) make "y (:height - ((:height - :y) / 2)) setpencolor "red ] if :vertex = 2 [ make "x (:width - ((:width - :x) / 2)) make "y (:y / 2) setpencolor "blue ] penup setxy (:x - :width / 2) (:y - :height / 2) pendown forward 1 ] hideturtle end
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
#Lua
Lua
  math.randomseed( os.time() ) colors, orig = { { 255, 0, 0 }, { 0, 255, 0 }, { 0, 0, 255 } }, {}   function love.load() wid, hei = love.graphics.getWidth(), love.graphics.getHeight()   orig[1] = { wid / 2, 3 } orig[2] = { 3, hei - 3 } orig[3] = { wid - 3, hei - 3 } local w, h = math.random( 10, 40 ), math.random( 10, 40 ) if math.random() < .5 then w = -w end if math.random() < .5 then h = -h end orig[4] = { wid / 2 + w, hei / 2 + h }   canvas = love.graphics.newCanvas( wid, hei ) love.graphics.setCanvas( canvas ); love.graphics.clear() love.graphics.setColor( 255, 255, 255 ) love.graphics.points( orig ) love.graphics.setCanvas() end function love.draw() local iter = 100 --> make this number bigger to speed up rendering for rp = 1, iter do local r, pts = math.random( 6 ), {} if r == 1 or r == 4 then pt = 1 elseif r == 2 or r == 5 then pt = 2 else pt = 3 end local x, y = ( orig[4][1] + orig[pt][1] ) / 2, ( orig[4][2] + orig[pt][2] ) / 2 orig[4][1] = x; orig[4][2] = y pts[1] = { x, y, colors[pt][1], colors[pt][2], colors[pt][3], 255 } love.graphics.setCanvas( canvas ) love.graphics.points( pts ) end love.graphics.setCanvas() love.graphics.draw( canvas ) end  
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.
#Prolog
Prolog
:- initialization chat_server(5000).   chat_server(Port) :- tcp_socket(Socket), tcp_bind(Socket, Port), tcp_listen(Socket, 5), tcp_open_socket(Socket, AcceptFd, _), dispatch(AcceptFd).   dispatch(AcceptFd) :- tcp_accept(AcceptFd, Socket, _), thread_create(process_client(Socket, _), _, [detached(true)]), dispatch(AcceptFd).   process_client(Socket, _) :- setup_call_cleanup( tcp_open_socket(Socket, Str), handle_connection(Str), close(Str)).   % a connection was made, get the username and add the streams so the % client can be broadcast to. handle_connection(Str) :- send_msg(Str, msg_welcome, []), repeat, send_msg(Str, msg_username, []), read_line_to_string(Str, Name), connect_user(Name, Str), !.   % connections are stored here :- dynamic(connected/2).   connect_user(Name, Str) :- connected(Name, _), send_msg(Str, msg_username_taken, []), fail. connect_user(Name, Str) :- \+ connected(Name, _), send_msg(Str, msg_welcome_name, Name),   % make sure that the connection is removed when the client leaves. setup_call_cleanup( assert(connected(Name, Str)), ( broadcast(Name, msg_joined, Name), chat_loop(Name, Str), !, broadcast(Name, msg_left, Name) ), retractall(connected(Name, _)) ).   % wait for a line to be sent then broadcast to the rest of the clients % finish this goal when the client disconnects (end of stream) chat_loop(Name, Str) :- read_line_to_string(Str, S), dif(S, end_of_file), broadcast(Name, msg_by_user, [Name, S]), chat_loop(Name, Str). chat_loop(_, Str) :- at_end_of_stream(Str).   % send a message to all connected clients except Name (the sender) broadcast(Name, Msg, Params) :- forall( (connected(N, Str), dif(N, Name)), (send_msg(Str, Msg, Params), send_msg(Str, msg_new_line, [])) ).   send_msg(St, MsgConst, Params) :- call(MsgConst, Msg), format(St, Msg, Params), flush_output(St).   % constants for the various message types that are sent msg_welcome('Welcome to Chatalot\n\r'). msg_username('Please enter your nickname: '). msg_welcome_name('Welcome ~p\n\r'). msg_joined(' -- "~w" has joined the chat --'). msg_left(' -- "~w" has left the chat. --'). msg_username_taken('That username is already taken, choose another\n\r'). msg_new_line('\n\r'). msg_by_user('~w> ~w').
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.
#XPL0
XPL0
code ChOut=8, Text=12; \intrinsic routines int Number(18); \numbers from equations def LF=$0A; \ASCII line feed (end-of-line character)   func Parse(S); \Convert numbers in string S to binary in Number array char S; int I, Neg;   proc GetNum; \Get number from string S int N; [while S(0)<^0 ! S(0)>^9 do S:= S+1; N:= S(0)-^0; S:= S+1; while S(0)>=^0 & S(0)<=^9 do [N:= N*10 + S(0) - ^0; S:= S+1]; Number(I):= N; I:= I+1; ];   [while S(0)#^= do S:= S+1; \skip to "=" I:= 0; loop [Neg:= false; \assume positive term loop [S:= S+1; \next char case S(0) of LF: [Number(I):= 0; return S+1]; \mark end of array ^-: Neg:= true; \term is negative ^a: [Number(I):= 1; I:= I+1; quit] \no coefficient so use 1 other if S(0)>=^0 & S(0)<=^9 then \if digit [S:= S-1; GetNum; quit]; \backup and get number ]; GetNum; \numerator if Neg then Number(I-1):= -Number(I-1); \tan(-a) = -tan(a) GetNum; \denominator ]; ];     func GCD(U, V); \Return the greatest common divisor of U and V int U, V; int T; [while V do \Euclid's method [T:= U; U:= V; V:= rem(T/V)]; return abs(U); ];   proc Verify; \Verify that tangent of equation = 1 (i.e: E = F) int E, F, I, J;   proc Machin(A, B, C, D); int A, B, C, D; int Div; \tan(a+b) = (tan(a) + tan(b)) / (1 - tan(a)*tan(b)) \tan(arctan(A/B) + arctan(C/D)) \ = (tan(arctan(A/B)) + tan(arctan(C/D))) / (1 - tan(arctan(A/B))*tan(arctan(C/D))) \ = (A/B + C/D) / (1 - A/B*C/D) \ = (A*D/B*D + B*C/B*D) / (B*D/B*D - A*C/B*D) \ = (A*D + B*C) / (B*D - A*C) [E:= A*D + B*C; F:= B*D - A*C; Div:= GCD(E, F); \keep integers from getting too big E:= E/Div; F:= F/Div; ];   [E:= 0; F:= 1; I:= 0; while Number(I) do [for J:= 1 to Number(I) do Machin(E, F, Number(I+1), Number(I+2)); I:= I+3; ]; Text(0, if E=F then "Yes " else "No "); ];     char S, SS; int I; [S:= "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) "; \Python version of equations (thanks!) for I:= 1 to 17 do [SS:= S; \save start of string line S:= Parse(S); \returns start of next line Verify; \correct Machin equation? Yes or No repeat ChOut(0, SS(0)); SS:= SS+1 until SS(0)=LF; ChOut(0, LF); \show equation ]; ]
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.
#E
E
? 'a'.asInteger() # value: 97   ? <import:java.lang.makeCharacter>.asChar(97) # value: '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.
#EasyLang
EasyLang
print strcode "a" print strchar 97
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.
#Perl
Perl
sub cholesky { my $matrix = shift; my $chol = [ map { [(0) x @$matrix ] } @$matrix ]; for my $row (0..@$matrix-1) { for my $col (0..$row) { my $x = $$matrix[$row][$col]; $x -= $$chol[$row][$_]*$$chol[$col][$_] for 0..$col; $$chol[$row][$col] = $row == $col ? sqrt $x : $x/$$chol[$col][$col]; } } return $chol; }   my $example1 = [ [ 25, 15, -5 ], [ 15, 18, 0 ], [ -5, 0, 11 ] ]; print "Example 1:\n"; print +(map { sprintf "%7.4f\t", $_ } @$_), "\n" for @{ cholesky $example1 };   my $example2 = [ [ 18, 22, 54, 42], [ 22, 70, 86, 62], [ 54, 86, 174, 134], [ 42, 62, 134, 106] ]; print "\nExample 2:\n"; print +(map { sprintf "%7.4f\t", $_ } @$_), "\n" for @{ cholesky $example2 };  
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
#Sidef
Sidef
func f(day, month) { Date.parse("#{day} #{month}", "%d %B") }   var dates = [ f(15, "May"), f(16, "May"), f(19, "May"), f(17, "June"), f(18, "June"), f(14, "July"), f(16, "July"), f(14, "August"), f(15, "August"), f(17, "August") ]   var filtered = dates.grep { dates.grep { dates.map{ .day }.count(.day) == 1 }.map{ .month }.count(.month) != 1 }   var birthday = filtered.grep { filtered.map{ .day }.count(.day) == 1 }.group_by{ .month }.values.first_by { .len == 1 }[0]   say "Cheryl's birthday is #{birthday.fullmonth} #{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
#Nim
Nim
var a = [1,2,3,4,5,6,7,8,9] var b: array[128, int] b[9] = 10 b[0..8] = a var c: array['a'..'d', float] = [1.0, 1.1, 1.2, 1.3] c['b'] = 10000
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
#Pyret
Pyret
    fun combos<a>(lst :: List<a>, size :: Number) -> List<List<a>>: # return all subsets of lst of a certain size, # maintaining the original ordering of the list   # Let's handle a bunch of degenerate cases up front # to be defensive... if lst.length() < size: # return an empty list if size is too big [list:] else if lst.length() == size: # combos([list: 1,2,3,4]) == list[list: 1,2,3,4]] [list: lst] else if size == 1: # combos(list: 5, 9]) == list[[list: 5], [list: 9]] lst.map(lam(elem): [list: elem] end) else: # The main resursive step here is to consider # all the combinations of the list that have the # first element (aka head) and then those that don't # don't. cases(List) lst: | empty => [list:] | link(head, rest) => # All the subsets of our list either include the # first element of the list (aka head) or they don't. with-head-combos = combos(rest, size - 1).map( lam(combo): link(head, combo) end ) without-head-combos = combos(rest, size) with-head-combos._plus(without-head-combos) end end where: # define semantics for the degenerate cases, although # maybe we should just make some of these raise errors combos([list:], 0) is [list: [list:]] combos([list:], 1) is [list:] combos([list: "foo"], 1) is [list: [list: "foo"]] combos([list: "foo"], 2) is [list:]   # test the normal stuff lst = [list: 1, 2, 3] combos(lst, 1) is [list: [list: 1], [list: 2], [list: 3] ] combos(lst, 2) is [list: [list: 1, 2], [list: 1, 3], [list: 2, 3] ] combos(lst, 3) is [list: [list: 1, 2, 3] ]   # remember the 10th row of Pascal's Triangle? :) lst10 = [list: 1,2,3,4,5,6,7,8,9,10] combos(lst10, 3).length() is 120 combos(lst10, 4).length() is 210 combos(lst10, 5).length() is 252 combos(lst10, 6).length() is 210 combos(lst10, 7).length() is 120   # more sanity checks... for each(sublst from combos(lst10, 6)): sublst.length() is 6 end   for each(sublst from combos(lst10, 9)): sublst.length() is 9 end end   fun int-combos(n :: Number, m :: Number) -> List<List<Number>>: doc: "return all lists of size m containing distinct, ordered nonnegative ints < n" lst = range(0, n) combos(lst, m) where: int-combos(5, 5) is [list: [list: 0,1,2,3,4]] int-combos(3, 2) is [list: [list: 0, 1], [list: 0, 2], [list: 1, 2] ] end   fun display-3-comb-5-for-rosetta-code(): # The very concrete nature of this function is driven # by the web page from Rosetta Code. We want to display # output similar to the top of this page: # # https://rosettacode.org/wiki/Combinations results = int-combos(5, 3) for each(lst from results): print(lst.join-str(" ")) end end   display-3-comb-5-for-rosetta-code()        
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.
#SQL
SQL
CASE WHEN a THEN b ELSE c END   DECLARE @n INT SET @n=124 print CASE WHEN @n=123 THEN 'equal' ELSE 'not equal' END   --If/ElseIf expression SET @n=5 print CASE WHEN @n=3 THEN 'Three' WHEN @n=4 THEN 'Four' ELSE 'Other' END
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}}} .
#Nim
Nim
proc mulInv(a0, b0: int): int = var (a, b, x0) = (a0, b0, 0) result = 1 if b == 1: return while a > 1: let q = a div b a = a mod b swap a, b result = result - q * x0 swap x0, result if result < 0: result += b0   proc chineseRemainder[T](n, a: T): int = var prod = 1 var sum = 0 for x in n: prod *= x   for i in 0..<n.len: let p = prod div n[i] sum += a[i] * mulInv(p, n[i]) * p   sum mod prod   echo chineseRemainder([3,5,7], [2,3,2])
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}}} .
#OCaml
OCaml
  exception Modular_inverse let inverse_mod a = function | 1 -> 1 | b -> let rec inner a b x0 x1 = if a <= 1 then x1 else if b = 0 then raise Modular_inverse else inner b (a mod b) (x1 - (a / b) * x0) x0 in let x = inner a b 0 1 in if x < 0 then x + b else x   let chinese_remainder_exn congruences = let mtot = congruences |> List.map (fun (_, x) -> x) |> List.fold_left ( *) 1 in (List.fold_left (fun acc (r, n) -> acc + r * inverse_mod (mtot / n) n * (mtot / n) ) 0 congruences) mod mtot   let chinese_remainder congruences = try Some (chinese_remainder_exn congruences) with modular_inverse -> None    
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.
#Ol
Ol
p = .point~new c = .circle~new   p~print c~print   ::class point ::method init expose x y use strict arg x = 0, y = 0 -- defaults to 0 for any non-specified coordinates   ::attribute x ::attribute y   ::method print expose x y say "A point at location ("||x","y")"   ::class circle subclass point ::method init expose radius use strict arg x = 0, y = 0, radius = 0 self~init:super(x, y) -- call superclass constructor   ::attribute radius   ::method print expose radius say "A circle of radius" radius "centered at location ("||self~x","self~y")"
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)
#R
R
closest_pair_brute <-function(x,y,plotxy=F) { xy = cbind(x,y) cp = bruteforce(xy) cat("\n\nShortest path found = \n From:\t\t(",cp[1],',',cp[2],")\n To:\t\t(",cp[3],',',cp[4],")\n Distance:\t",cp[5],"\n\n",sep="") if(plotxy) { plot(x,y,pch=19,col='black',main="Closest Pair", asp=1) points(cp[1],cp[2],pch=19,col='red') points(cp[3],cp[4],pch=19,col='red') } distance <- function(p1,p2) { x1 = (p1[1]) y1 = (p1[2]) x2 = (p2[1]) y2 = (p2[2]) sqrt((x2-x1)^2 + (y2-y1)^2) } bf_iter <- function(m,p,idx=NA,d=NA,n=1) { dd = distance(p,m[n,]) if((is.na(d) || dd<=d) && p!=m[n,]){d = dd; idx=n;} if(n == length(m[,1])) { c(m[idx,],d) } else bf_iter(m,p,idx,d,n+1) } bruteforce <- function(pmatrix,n=1,pd=c(NA,NA,NA,NA,NA)) { p = pmatrix[n,] ppd = c(p,bf_iter(pmatrix,p)) if(ppd[5]<pd[5] || is.na(pd[5])) pd = ppd if(n==length(pmatrix[,1])) pd else bruteforce(pmatrix,n+1,pd) } }
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
#Modula-2
Modula-2
MODULE Circles; FROM EXCEPTIONS IMPORT AllocateSource,ExceptionSource,GetMessage,RAISE; FROM FormatString IMPORT FormatString; FROM LongMath IMPORT sqrt; FROM LongStr IMPORT RealToStr; FROM Terminal IMPORT WriteString,WriteLn,ReadChar;   VAR TextWinExSrc : ExceptionSource;   TYPE Point = RECORD x,y : LONGREAL; END; Pair = RECORD a,b : Point; END;   PROCEDURE Distance(p1,p2 : Point) : LONGREAL; VAR dx,dy : LONGREAL; BEGIN dx := p1.x - p2.x; dy := p1.y - p2.y; RETURN sqrt(dx*dx + dy*dy) END Distance;   PROCEDURE Equal(p1,p2 : Point) : BOOLEAN; BEGIN RETURN (p1.x=p2.x) AND (p1.y=p2.y) END Equal;   PROCEDURE WritePoint(p : Point); VAR buf : ARRAY[0..63] OF CHAR; BEGIN WriteString("("); RealToStr(p.x, buf); WriteString(buf); WriteString(", "); RealToStr(p.y, buf); WriteString(buf); WriteString(")"); END WritePoint;   PROCEDURE FindCircles(p1,p2 : Point; r : LONGREAL) : Pair; VAR distance,diameter,mirrorDistance,dx,dy : LONGREAL; center : Point; BEGIN IF r < 0.0 THEN RAISE(TextWinExSrc, 0, "the radius can't be negative") END; IF (r = 0.0) AND NOT Equal(p1,p2) THEN RAISE(TextWinExSrc, 0, "No circles can ever be drawn") END; IF r = 0.0 THEN RETURN Pair{p1,p1} END; IF Equal(p1,p2) THEN RAISE(TextWinExSrc, 0, "an infinite number of circles can be drawn") END; distance := Distance(p1,p2); diameter := 2.0 * r; IF distance > diameter THEN RAISE(TextWinExSrc, 0, "the points are too far apart to draw a circle") END; center := Point{(p1.x + p2.x) / 2.0, (p1.y + p2.y) / 2.0}; IF distance = diameter THEN RETURN Pair{center, center} END; mirrorDistance := sqrt(r * r - distance * distance / 4.0); dx := (p2.x - p1.x) * mirrorDistance / distance; dy := (p2.y - p1.y) * mirrorDistance / distance; RETURN Pair{ {center.x - dy, center.y + dx}, {center.x + dy, center.y - dx} } END FindCircles;   PROCEDURE Print(p1,p2 : Point; r : LONGREAL) : BOOLEAN; VAR buf : ARRAY[0..63] OF CHAR; result : Pair; BEGIN WriteString("For points "); WritePoint(p1); WriteString(" and "); WritePoint(p2); WriteString(" with radius "); RealToStr(r, buf); WriteString(buf); WriteLn;   result := FindCircles(p1,p2,r); IF Equal(result.a, result.b) THEN WriteString("there is just one circle with the center at "); WritePoint(result.a); WriteLn; ELSE WriteString("there are two circles with centers at "); WritePoint(result.a); WriteString(" and "); WritePoint(result.b); WriteLn; END; WriteLn; RETURN TRUE EXCEPT GetMessage(buf); WriteString(buf); WriteLn; WriteLn; RETURN FALSE END Print;   VAR p0,p1,p2,p3 : Point; BEGIN AllocateSource(TextWinExSrc); p0 := Point{0.1234,0.9876}; p1 := Point{0.8765,0.2345}; p2 := Point{0.0000,2.0000}; p3 := Point{0.0000,0.0000};   Print(p0,p1,2.0); Print(p2,p3,1.0); Print(p0,p0,2.0); Print(p0,p1,0.5); Print(p0,p0,0.0);   ReadChar END Circles.
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).
#Picat
Picat
  animals({"Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"}).   elements({"Wood", "Fire", "Earth", "Metal", "Water"}).   animal_chars({"子","丑","寅","卯","辰","巳","午","未","申","酉","戌","亥"}).   element_chars({{"甲", "丙", "戊", "庚", "壬"}, {"乙", "丁", "己", "辛", "癸"}}).   years({1935, 1938, 1968, 1972, 1976, 1984, 1985, 2017}).   year_animal(Year) = Animal => I = ((Year - 4) mod 12) + 1, animals(Animals), Animal = Animals[I].   year_element(Year) = Element => I = ((Year - 4) mod 10) div 2 + 1, elements(Elements), Element = Elements[I].   year_animal_char(Year) = AnimalChar => I = (Year - 4) mod 12 + 1, animal_chars(AnimalChars), AnimalChar = AnimalChars[I].   year_element_char(Year) = ElementChar => I1 = Year mod 2 + 1, element_chars(ElementChars), ElementChars1 = ElementChars[I1], I2 = (Year - 4) mod 10 div 2 + 1, ElementChar = ElementChars1[I2].   year_yin_yang(Year) = YinYang => Year mod 2 == 0 -> YinYang = "yang" ; YinYang = "yin".   main :- years(Years), foreach (Year in Years) Element = year_element(Year), Animal = year_animal(Year), YinYang = year_yin_yang(Year), ElementChar = year_element_char(Year), AnimalChar = year_animal_char(Year), printf("%d is the year of the %w %w (%w). %w%w\n", Year, Element, Animal, YinYang, ElementChar, AnimalChar) end.  
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
#GAP
GAP
IsExistingFile("input.txt"); IsDirectoryPath("docs"); IsExistingFile("/input.txt"); IsDirectoryPath("/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
#Genie
Genie
[indent=4] /* Check file exists, in Genie valac --pkg=gio-2.0 checkFile.gs */   init Intl.setlocale()   files:array of string[] = {"input.txt", "docs", Path.DIR_SEPARATOR_S + "input.txt", Path.DIR_SEPARATOR_S + "docs", "`Abdu'l-Bahá.txt"} for f:string in files var file = File.new_for_path(f) var exists = file.query_exists() var dir = false if exists dir = file.query_file_type(0) == FileType.DIRECTORY print("%s %sexist%s%s", f, exists ? "" : "does not ", exists ? "s" : "", dir ? " and is 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
#Maple
Maple
chaosGame := proc(numPoints) local points, i; randomize(); use geometry in RegularPolygon(triSideways, 3, point(cent, [0, 0]), 1); rotation(tri, triSideways, Pi/2, counterclockwise); randpoint(currentP, -1/2*sqrt(3)..1/2*sqrt(3), -1/2..1/2); points := [coordinates(currentP)]; for i to numPoints do midpoint(mid, currentP, parse(cat("rotate_triSideways_", rand(1..3)(), "_tri"))); points := [op(points), coordinates(mid)]; point(currentP, coordinates(mid)); end do: end use; use plottools in plots:-display( seq([plots:-display([seq(point(points[i]), i = 1..j)])], j = 1..numelems(points) ), insequence=true); end use; end proc:
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.
#Python
Python
#!/usr/bin/env python   import socket import thread import time   HOST = "" PORT = 4004   def accept(conn): """ Call the inner func in a thread so as not to block. Wait for a name to be entered from the given connection. Once a name is entered, set the connection to non-blocking and add the user to the users dict. """ def threaded(): while True: conn.send("Please enter your name: ") try: name = conn.recv(1024).strip() except socket.error: continue if name in users: conn.send("Name entered is already in use.\n") elif name: conn.setblocking(False) users[name] = conn broadcast(name, "+++ %s arrived +++" % name) break thread.start_new_thread(threaded, ())   def broadcast(name, message): """ Send a message to all users from the given name. """ print message for to_name, conn in users.items(): if to_name != name: try: conn.send(message + "\n") except socket.error: pass   # Set up the server socket. server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.setblocking(False) server.bind((HOST, PORT)) server.listen(1) print "Listening on %s" % ("%s:%s" % server.getsockname())   # Main event loop. users = {} while True: try: # Accept new connections. while True: try: conn, addr = server.accept() except socket.error: break accept(conn) # Read from connections. for name, conn in users.items(): try: message = conn.recv(1024) except socket.error: continue if not message: # Empty string is given on disconnect. del users[name] broadcast(name, "--- %s leaves ---" % name) else: broadcast(name, "%s> %s" % (name, message.strip())) time.sleep(.1) except (SystemExit, KeyboardInterrupt): break
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.
#Eiffel
Eiffel
  class APPLICATION inherit ARGUMENTS create make   feature {NONE} -- Initialization   make -- Run application. local c8: CHARACTER_8 c32: CHARACTER_32 do c8 := '%/97/' -- using code value notation c8 := '%/0x61/' -- same as above, but using hexadecimal literal print(c8.natural_32_code) -- prints "97" print(c8) -- prints the character "a"   c32 := 'a' -- using character literal print(c32.natural_32_code) -- prints "97" print(c32) -- prints "U+00000061"   --c8 := 'π' -- compile-time error (c8 does not have enough range) c32 := 'π' -- assigns Unicode value 960 end end  
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.
#Phix
Phix
with javascript_semantics function cholesky(sequence matrix) integer l = length(matrix) sequence chol = repeat(repeat(0,l),l) for row=1 to l do for col=1 to row do atom x = matrix[row][col] for i=1 to col do x -= chol[row][i] * chol[col][i] end for chol[row][col] = iff(row == col ? sqrt(x) : x/chol[col][col]) end for end for return chol end function ppOpt({pp_Nest,1}) pp(cholesky({{ 25, 15, -5 }, { 15, 18, 0 }, { -5, 0, 11 }})) pp(cholesky({{ 18, 22, 54, 42}, { 22, 70, 86, 62}, { 54, 86, 174, 134}, { 42, 62, 134, 106}}))
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
#Swift
Swift
struct MonthDay: CustomStringConvertible { static let months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]   var month: Int var day: Int   var description: String { "\(MonthDay.months[month - 1]) \(day)" }   private func isUniqueIn(months: [MonthDay], by prop: KeyPath<MonthDay, Int>) -> Bool { return months.lazy.filter({ $0[keyPath: prop] == self[keyPath: prop] }).count == 1 }   func monthIsUniqueIn(months: [MonthDay]) -> Bool { return isUniqueIn(months: months, by: \.month) }   func dayIsUniqueIn(months: [MonthDay]) -> Bool { return isUniqueIn(months: months, by: \.day) }   func monthWithUniqueDayIn(months: [MonthDay]) -> Bool { return months.firstIndex(where: { $0.month == month && $0.dayIsUniqueIn(months: months) }) != nil } }   let choices = [ MonthDay(month: 5, day: 15), MonthDay(month: 5, day: 16), MonthDay(month: 5, day: 19), MonthDay(month: 6, day: 17), MonthDay(month: 6, day: 18), MonthDay(month: 7, day: 14), MonthDay(month: 7, day: 16), MonthDay(month: 8, day: 14), MonthDay(month: 8, day: 15), MonthDay(month: 8, day: 17) ]   // Albert knows the month, but not the day, so he doesn't have a gimmie month let albertKnows = choices.filter({ !$0.monthIsUniqueIn(months: choices) })   // Albert also knows that Bernard doesn't know, so it can't be a gimmie day let bernardKnows = albertKnows.filter({ !$0.monthWithUniqueDayIn(months: albertKnows) })   // Bernard now knows the birthday, so it must be a unique day within the remaining choices let bernardKnowsMore = bernardKnows.filter({ $0.dayIsUniqueIn(months: bernardKnows) })   // Albert knows the birthday now, so it must be a unique month within the remaining choices guard let birthday = bernardKnowsMore.filter({ $0.monthIsUniqueIn(months: bernardKnowsMore) }).first else { fatalError() }   print("Cheryl's birthday is \(birthday)")
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
#VBA
VBA
Private Sub exclude_unique_days(w As Collection) Dim number_of_dates(31) As Integer Dim months_to_exclude As New Collection For Each v In w number_of_dates(v(1)) = number_of_dates(v(1)) + 1 Next v For i = w.Count To 1 Step -1 If number_of_dates(w(i)(1)) = 1 Then months_to_exclude.Add w(i)(0) w.Remove i End If Next i For Each m In months_to_exclude exclude_month w, m Next m End Sub Private Sub exclude_month(x As Collection, v As Variant) For i = x.Count To 1 Step -1 If x(i)(0) = v Then x.Remove i Next i End Sub Private Sub exclude_non_unique_days(w As Collection) Dim number_of_dates(31) As Integer For Each v In w number_of_dates(v(1)) = number_of_dates(v(1)) + 1 Next v For i = w.Count To 1 Step -1 If number_of_dates(w(i)(1)) > 1 Then w.Remove i End If Next i End Sub Private Sub exclude_non_unique_months(w As Collection) Dim months As New Collection For Each v In w On Error GoTo 1 months.Add v(0), v(0) Next v 1: For i = w.Count To 1 Step -1 If w(i)(0) = v(0) Then w.Remove i End If Next i End Sub Public Sub cherylsbirthday() Dim v As New Collection s = "May 15, May 16, May 19, June 17, June 18, July 14, July 16, August 14, August 15, August 17" t = Split(s, ",") For Each u In t v.Add Split(Trim(u), " ") Next u '1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too. exclude_unique_days v '2) Bernard: At first I don't know when Cheryl's birthday is, but I know now. exclude_non_unique_days v '3) Albert: Then I also know when Cheryl's birthday is. exclude_non_unique_months v Debug.Print v(1)(0); " "; v(1)(1) End Sub
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
#Objeck
Objeck
  values := IntVector->New(); values->AddBack(7); values->AddBack(3); values->AddBack(10);  
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
#Python
Python
>>> from itertools import combinations >>> list(combinations(range(5),3)) [(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)]
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.
#SSEM
SSEM
01010000000000100000000000000000 -10 to c 00000000000000110000000000000000 Test 01110000000000000000000000000000 14 to CI
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.
#Stata
Stata
clear set obs 4 gen a = cond(mod(_n, 2)==1, "A", "B") list, noobs noheader   +---+ | A | | B | | A | | B | +---+
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}}} .
#PARI.2FGP
PARI/GP
chivec(residues, moduli)={ my(m=Mod(0,1)); for(i=1,#residues, m=chinese(Mod(residues[i],moduli[i]),m) ); lift(m) }; chivec([2,3,2], [3,5,7])
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}}} .
#Pascal
Pascal
  // Rosetta Code task "Chinese remainder theorem". program ChineseRemThm; uses SysUtils; type TIntArray = array of integer;   // Defining EXTRA adds optional explanatory code {$DEFINE EXTRA}   // Return (if possible) a residue res_out that satifies // res_out = res1 modulo mod1, res_out = res2 modulo mod2. // Return mod_out = LCM( mod1, mod2), or mod_out = 0 if there's no solution. procedure Solve2( const res1, res2, mod1, mod2 : integer; out res_out, mod_out : integer); var a, c, d, k, m, m1, m2, r, temp : integer; p, p_prev : integer; {$IFDEF EXTRA} q, q_prev : integer; {$ENDIF} begin if (mod1 = 0) or (mod2 = 0) then raise SysUtils.Exception.Create( 'Solve2: Modulus cannot be 0'); m1 := Abs( mod1); m2 := Abs( mod2); // Extended Euclid's algorithm for HCF( m1, m2), except that only one // of the Bezout coefficients is needed (here p, could have used q) c := m1; d := m2; p :=0; p_prev := 1; {$IFDEF EXTRA} q := 1; q_prev := 0; {$ENDIF} a := 0; while (d > 0) do begin temp := p_prev - a*p; p_prev := p; p := temp; {$IFDEF EXTRA} temp := q_prev - a*q; q_prev := q; q := temp; {$ENDIF} a := c div d; temp := c - a*d; c := d; d := temp; end; // Here with c = HCF( m1, m2) {$IFDEF EXTRA} Assert( c = p*m2 + q*m1); // p and q are the Bezout coefficients {$ENDIF} // A soution exists iff c divides (res2 - res1) k := (res2 - res1) div c; if res2 - res1 <> k*c then begin res_out := 0; mod_out := 0; // indicate that there's no xolution end else begin m := (m1 div c) * m2; // m := LCM( m1, m2) r:= res2 - k*p*m2; // r := a solution modulo m {$IFDEF EXTRA} Assert( r = res1 + k*q*m1); // alternative formula in terms of q {$ENDIF} // Return the solution in the range 0..(m - 1) // Don't trust the compiler with a negative argument to mod if (r >= 0) then r := r mod m else begin r := (-r) mod m; if (r > 0) then r := m - r; end; res_out := r; mod_out := m; end; end;   // Return (if possible) a residue res_out that satifies // res_out = res_array[j] modulo mod_array[j], for j = 0..High(res_array). // Return mod_out = LCM of the moduli, or mod_out = 0 if there's no solution. procedure SolveMulti( const res_array, mod_array : TIntArray; out res_out, mod_out : integer); var count, k, m, r : integer; begin count := Length( mod_array); if count <> Length( res_array) then raise SysUtils.Exception.Create( 'Arrays are different sizes') else if count = 0 then raise SysUtils.Exception.Create( 'Arrays are empty'); k := 1; m := mod_array[0]; r := res_array[0]; while (k < count) and (m > 0) do begin Solve2( r, res_array[k], m, mod_array[k], r, m); inc(k); end; res_out := r; mod_out := m; end;   // Cosmetic to turn an integer array into a string for printout. function ArrayToString( a : TIntArray) : string; var j : integer; begin result := '['; for j := 0 to High(a) do begin result := result + SysUtils.IntToStr(a[j]); if j < High(a) then result := result + ', ' else result := result + ']'; end; end;   // For the passed-in res_array and mod_array, show the solution // found by SolveMulti (above), or state that there's no solution. procedure ShowSolution( const res_array, mod_array : TIntArray); var mod_out, res_out : integer; begin SolveMulti( res_array, mod_array, res_out, mod_out); Write( ArrayToString( res_array) + ' mod ' + ArrayToString( mod_array) + ' --> '); if mod_out = 0 then WriteLn( 'No solution') else WriteLn( SysUtils.Format( '%d mod %d', [res_out, mod_out])); end;   // Main routine. Examples for Rosetta Code task. begin ShowSolution([2, 3, 2], [3, 5, 7]); ShowSolution([3, 5, 7], [2, 3, 2]); ShowSolution([10, 4, 12], [11, 12, 13]); ShowSolution([1, 2, 3, 4], [5, 7, 9, 11]); ShowSolution([11, 22, 19], [10, 4, 9]); ShowSolution([2328, 410], [16256, 5418]); ShowSolution([19, 0], [100, 23]); end.  
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.
#ooRexx
ooRexx
p = .point~new c = .circle~new   p~print c~print   ::class point ::method init expose x y use strict arg x = 0, y = 0 -- defaults to 0 for any non-specified coordinates   ::attribute x ::attribute y   ::method print expose x y say "A point at location ("||x","y")"   ::class circle subclass point ::method init expose radius use strict arg x = 0, y = 0, radius = 0 self~init:super(x, y) -- call superclass constructor   ::attribute radius   ::method print expose radius say "A circle of radius" radius "centered at location ("||self~x","self~y")"
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.
#OxygenBasic
OxygenBasic
    Class MyObject   static int count 'statics are private   int a,b,c bstring s   method constructor(int pa,pb,pc) s="constructed" a=pa : b=pb : c=pc count++ end method   method destructor() del s end method   method sum() as int return a+b+c end method   end class   new MyObject v(2,4,6)   print "Sum: " v.sum   del v  
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)
#Racket
Racket
  #lang racket (define (dist z0 z1) (magnitude (- z1 z0))) (define (dist* zs) (apply dist zs))   (define (closest-pair zs) (if (< (length zs) 2) -inf.0 (first (sort (for/list ([z0 zs]) (list z0 (argmin (λ(z) (if (= z z0) +inf.0 (dist z z0))) zs))) < #:key dist*))))   (define result (closest-pair '(0+1i 1+2i 3+4i))) (displayln (~a "Closest points: " result)) (displayln (~a "Distance: " (dist* result)))  
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
#Nim
Nim
import math   type Point = tuple[x, y: float] Circle = tuple[x, y, r: float]   proc circles(p1, p2: Point, r: float): tuple[c1, c2: Circle] = if r == 0: raise newException(ValueError, "radius of zero") if p1 == p2: raise newException(ValueError, "coincident points gives infinite number of Circles")   # delta x, delta y between points let (dx, dy) = (p2.x - p1.x, p2.y - p1.y) # dist between points let q = sqrt(dx*dx + dy*dy) if q > 2.0*r: raise newException(ValueError, "separation of points > diameter")   # halfway point let p3: Point = ((p1.x+p2.x)/2, (p1.y+p2.y)/2) # distance along the mirror line let d = sqrt(r*r - (q/2)*(q/2)) # One answer result.c1 = (p3.x - d*dy/q, p3.y + d*dx/q, abs(r)) # The other answer result.c2 = (p3.x + d*dy/q, p3.y - d*dx/q, abs(r))   const tries: seq[tuple[p1, p2: Point, r: float]] = @[((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)]   for p1, p2, r in tries.items: echo "Through points:" echo " ", p1 echo " ", p2 echo " and radius ", r echo "You can construct the following circles:" try: let (c1, c2) = circles(p1, p2, r) echo " ", c1 echo " ", c2 except ValueError: echo " ERROR: ", getCurrentExceptionMsg() echo ""
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).
#PowerShell
PowerShell
  function Get-ChineseZodiac { [CmdletBinding()] [OutputType([PSCustomObject])] Param ( [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [ValidateRange(1,9999)] [int] $Year = (Get-Date).Year )   Begin { $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' }   $celestial = '甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸' $terrestrial = '子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥' $animals = 'Rat', 'Ox', 'Tiger', 'Rabbit', 'Dragon', 'Snake', 'Horse', 'Goat', 'Monkey', 'Rooster', 'Dog', 'Pig' $elements = 'Wood', 'Fire', 'Earth', 'Metal', 'Water' $aspects = 'yang', 'yin'   $base = 4 } Process { foreach ($ce_year in $Year) { $cycle_year = $ce_year - $base   $stem_number = $cycle_year % 10 $stem_han = $celestial[$stem_number] $stem_pinyin = $pinyin[$stem_han]   $element_number = [Math]::Floor($stem_number / 2) $element = $elements[$element_number]   $branch_number = $cycle_year % 12 $branch_han = $terrestrial[$branch_number] $branch_pinyin = $pinyin[$branch_han] $animal = $animals[$branch_number]   $aspect_number = $cycle_year % 2 $aspect = $aspects[$aspect_number]   $index = $cycle_year % 60 + 1   [PSCustomObject]@{ Year = $Year Element = $element Animal = $animal Aspect = $aspect YearOfCycle = $index ASCII = "$stem_pinyin-$branch_pinyin" Chinese = "$stem_han$branch_han" } } } }  
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
#Go
Go
package main   import ( "fmt" "os" )   func printStat(p string) { switch i, err := os.Stat(p); { case err != nil: fmt.Println(err) case i.IsDir(): fmt.Println(p, "is a directory") default: fmt.Println(p, "is a file") } }   func main() { printStat("input.txt") printStat("/input.txt") printStat("docs") printStat("/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
#Groovy
Groovy
println new File('input.txt').exists() println new File('/input.txt').exists() println new File('docs').exists() println new File('/docs').exists()
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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
points = 5000; a = {0, 0}; b = {1, 0}; c = {0.5, 1}; d = {.7, .3}; S = {}; For[i = 1, i < points, i++, t = RandomInteger[2]; If[t == 0, d = Mean[{a, d}], If[t == 1, d = Mean[{b, d}], d = Mean[{c, d}]]]; AppendTo[S, d]] Graphics[Point[S]]
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
#Nim
Nim
import random   import rapid/gfx   var window = initRWindow() .title("Rosetta Code - Chaos Game") .open() surface = window.openGfx() sierpinski = window.newRCanvas() points: array[3, Vec2[float]]   for i in 0..<3: points[i] = vec2(cos(PI * 2 / 3 * i.float), sin(PI * 2 / 3 * i.float)) * 300   var point = vec2(rand(0.0..surface.width), rand(0.0..surface.height))   surface.vsync = false surface.loop: draw ctx, step: let vertex = sample(points) point = (point + vertex) / 2 ctx.renderTo(sierpinski): ctx.transform(): ctx.translate(surface.width / 2, surface.height / 2) ctx.rotate(-PI / 2) ctx.begin() ctx.point((point.x, point.y)) ctx.draw(prPoints) ctx.clear(gray(0)) ctx.begin() ctx.texture = sierpinski ctx.rect(0, 0, surface.width, surface.height) ctx.draw() ctx.noTexture() update step: discard
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.
#R
R
  chat_loop <- function(server, sockets, delay = 0.5) { repeat { Sys.sleep(delay) # Saves CPU resources   ## Exhausts queue each iteration while (in_queue(server)) sockets <- new_socket_entry(server, sockets)   ## Update which sockets have sent messages sockets <- check_messages(sockets)   ## No sockets, nothing to do if (nrow(sockets) == 0) next   ## No new messages, nothing to do if (all(!sockets$message_ready)) next     sockets <- read_messages(sockets) # Messages are stored until sent sockets <- drop_dead(sockets) # Dead = ready to read, but no data   ## In case all sockets were dropped if (nrow(sockets) == 0) next   sockets <- update_nicknames(sockets) sockets <- send_messages(sockets) # Only to users with nicknames } }   check_messages <- function(sockets) { if (nrow(sockets) != 0) sockets$message_ready <- socketSelect(sockets$conn, timeout = 0)   sockets }   drop_dead <- function(sockets) { lapply(with(sockets, conn[!alive]), close) dropped <- with(sockets, nickname[nickname_exists(sockets) & !alive]) sockets <- sockets[sockets$alive, ]   if (length(dropped) != 0) { send_named(sockets, paste0(dropped, " has disconnected.")) }   sockets }   in_queue <- function(server) socketSelect(list(server), timeout = 0) is_valid_name <- function(nicks) gsub("[A-Za-z0-9]*", "", nicks) == "" message_exists <- function(sockets) !is.na(sockets$message)   new_row <- function(df) { df[nrow(df) + 1, ] <- NA df }   new_socket_entry <- function(server, sockets) { sockets <- new_row(sockets) n <- nrow(sockets) within(sockets, { conn[[n]] <- new_user(server) alive[n] <- TRUE message_ready[n] <- FALSE }) }   new_user <- function(server) { conn <- socketAccept(server) writeLines("Hello! Please enter a nickname.", conn) conn }   nickname_exists <- function(sockets) !is.na(sockets$nickname)   read_messages <- function(sockets) { if (all(!sockets$message_ready)) return(sockets)   msgs <- lapply(with(sockets, conn[message_ready]), readLines, n = 1) empty_msgs <- sapply(msgs, identical, character(0)) sockets <- within(sockets, alive[message_ready & empty_msgs] <- FALSE) msgs <- unlist(ifelse(empty_msgs, NA, msgs)) within(sockets, message[message_ready] <- msgs) }   send_messages <- function(sockets) { named_message <- message_exists(sockets) & nickname_exists(sockets)   if (all(!named_message)) return(sockets)   rows <- which(named_message) socksub <- sockets[rows, ] time <- format(Sys.time(), "[%H:%M:%S] ") with(socksub, send_named(sockets, paste0(time, nickname, ": ", message))) within(sockets, message[rows] <- NA) }   send_named <- function(sockets, msg) { has_nickname <- nickname_exists(sockets) invisible(lapply(sockets$conn[has_nickname], writeLines, text = msg)) }   start_chat_server <- function(port = 50525) { server <- serverSocket(port) # Start listening on.exit(closeAllConnections()) # Cleanup connections   ## All socket data is stored and passed using this object sockets <- data.frame(conn = I(list()), nickname = character(), message = character(), alive = logical(), message_ready = logical())   ## Main event loop chat_loop(server, sockets) }   update_nicknames <- function(sockets) { sent_nickname <- message_exists(sockets) & !nickname_exists(sockets) nickname_valid <- is_valid_name(sockets$message)   if (all(!sent_nickname)) return(sockets)   is_taken <- with(sockets, (tolower(message) %in% tolower(sockets$nickname)) &  !is.na(message)) sent_ok <- sent_nickname & nickname_valid & !is_taken sockets <- within(sockets, { nickname[sent_ok] <- message[sent_ok] message[sent_nickname] <- NA lapply(conn[sent_nickname & !nickname_valid], writeLines, text = "Alphanumeric characters only. Try again.") lapply(conn[is_taken], writeLines, text = "Name already taken. Try again.") })   if (any(sent_ok)) send_named(sockets, paste0(sockets$nickname[sent_ok], " has connected."))   sockets }   start_chat_server()
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.
#Elena
Elena
import extensions;   public program() { var ch := $97;   console.printLine:ch; console.printLine(ch.toInt()) }
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.
#PicoLisp
PicoLisp
(scl 9) (load "@lib/math.l")   (de cholesky (A) (let L (mapcar '(() (need (length A) 0)) A) (for (I . R) A (for J I (let S (get R J) (for K (inc J) (dec 'S (*/ (get L I K) (get L J K) 1.0)) ) (set (nth L I J) (if (= I J) (sqrt S 1.0) (*/ S 1.0 (get L J J)) ) ) ) ) ) (for R L (for N R (prin (align 9 (round N 5)))) (prinl) ) ) )
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
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Structure MonDay Dim month As String Dim day As Integer   Sub New(m As String, d As Integer) month = m day = d End Sub   Public Overrides Function ToString() As String Return String.Format("({0}, {1})", month, day) End Function End Structure   Sub Main() Dim dates = New HashSet(Of MonDay) From { New MonDay("May", 15), New MonDay("May", 16), New MonDay("May", 19), New MonDay("June", 17), New MonDay("June", 18), New MonDay("July", 14), New MonDay("July", 16), New MonDay("August", 14), New MonDay("August", 15), New MonDay("August", 17) } Console.WriteLine("{0} remaining.", dates.Count)   ' The month cannot have a unique day. Dim monthsWithUniqueDays = dates.GroupBy(Function(d) d.day).Where(Function(g) g.Count() = 1).Select(Function(g) g.First().month).ToHashSet() dates.RemoveWhere(Function(d) monthsWithUniqueDays.Contains(d.month)) Console.WriteLine("{0} remaining.", dates.Count)   ' The day must now be unique. dates.IntersectWith(dates.GroupBy(Function(d) d.day).Where(Function(g) g.Count() = 1).Select(Function(g) g.First())) Console.WriteLine("{0} remaining.", dates.Count)   ' The month must now be unique. dates.IntersectWith(dates.GroupBy(Function(d) d.month).Where(Function(g) g.Count() = 1).Select(Function(g) g.First())) Console.WriteLine(dates.Single()) End Sub   End Module
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
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   void show_collection(id coll) { for ( id el in coll ) { if ( [coll isKindOfClass: [NSCountedSet class]] ) { NSLog(@"%@ appears %lu times", el, [coll countForObject: el]); } else if ( [coll isKindOfClass: [NSDictionary class]] ) { NSLog(@"%@ -> %@", el, coll[el]); } else { NSLog(@"%@", el); } } printf("\n"); }   int main() { @autoreleasepool {   // create an empty set NSMutableSet *set = [[NSMutableSet alloc] init]; // populate it [set addObject: @"one"]; [set addObject: @10]; [set addObjectsFromArray: @[@"one", @20, @10, @"two"] ]; // let's show it show_collection(set);   // create an empty counted set (a bag) NSCountedSet *cset = [[NSCountedSet alloc] init]; // populate it [cset addObject: @"one"]; [cset addObject: @"one"]; [cset addObject: @"two"]; // show it show_collection(cset);   // create a dictionary NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; // populate it dict[@"four"] = @4; dict[@"eight"] = @8; // show it show_collection(dict);   } return EXIT_SUCCESS; }
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
#Quackery
Quackery
[ 0 swap [ dup 0 != while dup 1 & if [ dip 1+ ] 1 >> again ] drop ] is bits ( n --> n )   [ [] unrot bit times [ i bits over = if [ dip [ i join ] ] ] drop ] is combnums ( n n --> [ )   [ [] 0 rot [ dup 0 != while dup 1 & if [ dip [ dup dip join ] ] dip 1+ 1 >> again ] 2drop ] is makecomb ( n --> [ )   [ over 0 = iff [ 2drop [] ] done combnums [] swap witheach [ makecomb nested join ] ] is comb ( n n --> [ )   [ behead swap witheach max ] is largest ( [ --> n )   [ 0 rot witheach [ [ dip [ over * ] ] + ] nip ] is comborder ( [ n --> n )   [ dup [] != while sortwith [ 2dup join largest 1+ dup dip [ comborder swap ] comborder < ] ] is sortcombs ( [ --> [ )   3 5 comb sortcombs witheach [ witheach [ echo sp ] cr ]
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.
#Swahili
Swahili
kama (kweli) { andika("statement") } au (kweli /* condition */) { andika("statement") } au (kweli /* condition */) { andika("statement") } sivyo { andika("statement") }
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}}} .
#Perl
Perl
use ntheory qw/chinese/; say chinese([2,3], [3,5], [2,7]);
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}}} .
#Phix
Phix
function mul_inv(integer a, n) if n<0 then n = -n end if if a<0 then a = n - mod(-a,n) end if integer t = 0, nt = 1, r = n, nr = a; while nr!=0 do integer q = floor(r/nr) {t, nt} = {nt, t-q*nt} {r, nr} = {nr, r-q*nr} end while if r>1 then return "a is not invertible" end if if t<0 then t += n end if return t end function function chinese_remainder(sequence n, a) integer p, prod = 1, tot = 0; for i=1 to length(n) do prod *= n[i] end for for i=1 to length(n) do p = prod / n[i]; object m = mul_inv(p, n[i]) if string(m) then return "fail" end if tot += a[i] * m * p; end for return mod(tot,prod) end function ?chinese_remainder({3,5,7},{2,3,2}) ?chinese_remainder({11,12,13},{10,4,12}) ?chinese_remainder({11,22,19},{10,4,9}) ?chinese_remainder({100,23},{19,0})