task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, as a type, has the values and operations of its own. The operations of are usually called methods of the root type. Both operations and values are called polymorphic. A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument. The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual. Operations with multiple arguments and/or the results of the class are called multi-methods. A further generalization of is the operation with arguments and/or results from different classes. single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x). multiple-dispatch languages allow many arguments and/or results to control the dispatch. A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type. This type is sometimes called the most specific type of a [polymorphic] value. The type tag of the value is used in order to resolve the dispatch. The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class. In many OO languages the type of the class of T and T itself are considered equivalent. In some languages they are distinct (like in Ada). When class T and T are equivalent, there is no way to distinguish polymorphic and specific values. Task Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
#Oz
Oz
declare class Something feat name %% immutable, public attribute (called a "feature") attr count %% mutable, private attribute   %% public method which is used as an initializer meth init(N) self.name = N count := 0 end   %% public method meth increase count := @count + 1 end end in %% create an instance Object = {New Something init("object")}   %% call a method {Object increase}
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)
#Raku
Raku
sub MAIN ($N = 5000) { my @points = (^$N).map: { [rand × 20 - 10, rand × 20 - 10] } printf "%.8f between (%.5f, %.5f), (%.5f, %.5f)\n", $_[2], @($_[1]), @($_[0]) for closest-pair(@points), closest-pair-simple(@points) }   sub dist-squared(@a, @b) { (@a[0] - @b[0])² + (@a[1] - @b[1])² }   sub closest-pair-simple(@points is copy) { return ∞ if @points < 2; my ($a, $b, $d) = |@points[0,1], dist-squared(|@points[0,1]); while @points { my \p = pop @points; for @points -> \l { ($a, $b, $d) = p, l, $_ if $_ < $d given dist-squared(p, l); } } $a, $b, $d.sqrt }   sub closest-pair(@r) { closest-pair-real (@r.sort: *.[0]), (@r.sort: *.[1]) }   sub closest-pair-real(@rx, @ry) { return closest-pair-simple(@rx) if @rx ≤ 3;   my \N = @rx; my \midx = ceiling(N/2) - 1; my @PL := @rx[ 0 .. midx]; my @PR := @rx[midx+1 ..^ N ]; my \xm = @rx[midx;0]; (.[0] ≤ xm ?? my @yR !! my @yL).push: @$_ for @ry; my (\al, \bl, \dL) = closest-pair-real(@PL, @yR); my (\ar, \br, \dR) = closest-pair-real(@PR, @yL); my ($w1, $w2, $closest) = dR < dL ?? (ar, br, dR) !! (al, bl, dL); my @yS = @ry.grep: { (xm - .[0]).abs < $closest }   for 0 ..^ @yS -> \i { for i+1 ..^ @yS -> \k { next unless @yS[k;1] - @yS[i;1] < $closest; ($w1, $w2, $closest) = |@yS[k, i], $_ if $_ < $closest given dist-squared(|@yS[k, i]).sqrt; } } $w1, $w2, $closest }
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points
Circles of given radius through two points
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. Exceptions r==0.0 should be treated as never describing circles (except in the case where the points are coincident). If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point. If the points form a diameter then return two identical circles or return a single circle, according to which is the most natural mechanism for the implementation language. If the points are too far apart then no circles can be drawn. Task detail Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, or some indication of special cases where two, possibly equal, circles cannot be returned. Show here the output for the following inputs: p1 p2 r 0.1234, 0.9876 0.8765, 0.2345 2.0 0.0000, 2.0000 0.0000, 0.0000 1.0 0.1234, 0.9876 0.1234, 0.9876 2.0 0.1234, 0.9876 0.8765, 0.2345 0.5 0.1234, 0.9876 0.1234, 0.9876 0.0 Related task   Total circles area. See also   Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
#OCaml
OCaml
  (* Task : Circles of given radius through two points *)   (* Types to make code even more readable *) type point = float * float type radius = float type circle = Circle of radius * point type circ_output = NoSolution | OneSolution of circle | TwoSolutions of circle * circle | InfiniteSolutions ;;   (* Actual function *) let circles_2points_radius (x1, y1 : point) (x2, y2 : point) (r : radius) = let (dx, dy) = (x2 -. x1, y2 -. y1) in let dist_sq = dx *. dx +. dy *. dy in match dist_sq, r with (* Edge case - point circles *) | 0., 0. -> OneSolution (Circle (r, (x1, y1))) (* Edge case - coinciding points *) | 0., _ -> InfiniteSolutions | _ -> let side_len_sq = r *. r -. dist_sq /. 4. in let midp = ((x1 +. x2) *. 0.5, (y1 +. y2) *. 0.5) in (* Points are too far apart; same whether r = 0 or not *) if side_len_sq < 0. then NoSolution (* Points are on diameter *) else if side_len_sq = 0. then OneSolution (Circle (r, midp)) else (* A right-angle triangle is made with the radius as hyp, dist/2 as one side *) let side_len = sqrt (r *. r -. dist_sq /. 4.) in let dist = sqrt dist_sq in (* A 90-deg rotation of a vector (x, y) is obtained by either (y, -x) or (-y, x) We need both, so pick one and the other is its negative. *) let (vx, vy) = (-. dy *. side_len /. dist, dx *. side_len /. dist) in let c1 = Circle (r, (fst midp +. vx, snd midp +. vy)) in let c2 = Circle (r, (fst midp -. vx, snd midp -. vy)) in TwoSolutions (c1, c2) ;;   (* Relevant tests and printing *) let tests = [ (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; ] ;;   let format_output (out : circ_output) = match out with | NoSolution -> print_endline "No solution" | OneSolution (Circle (_, (x, y))) -> Printf.printf "One solution: (%.6f, %.6f)\n" x y | TwoSolutions (Circle (_, (x1, y1)), Circle (_, (x2, y2))) -> Printf.printf "Two solutions: (%.6f, %.6f) and (%.6f, %.6f)\n" x1 y1 x2 y2 | InfiniteSolutions -> print_endline "Infinite solutions" ;;   let _ = List.iter (fun (a, b, c) -> circles_2points_radius a b c |> format_output) tests ;;  
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).
#Prolog
Prolog
  :- initialization(main).   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 is ((Year - 4) mod 12) + 1, animals(Animals), nth(I, Animals, Animal).   year_element(Year, Element) :- I is ((Year - 4) mod 10) div 2 + 1, elements(Elements), nth(I, Elements, Element).   year_animal_char(Year, AnimalChar) :- I is (Year - 4) mod 12 + 1, animal_chars(AnimalChars), nth(I, AnimalChars, AnimalChar).   year_element_char(Year, ElementChar) :- I1 is Year mod 2 + 1, element_chars(ElementChars), nth(I1, ElementChars, ElementChars1), I2 is (Year - 4) mod 10 div 2 + 1, nth(I2, ElementChars1, ElementChar).   year_yin_yang(Year, YinYang) :- Year mod 2 =:= 0 -> YinYang = 'yang' ; YinYang = 'yin'.   main :- years(Years), forall(member(Year, Years), ( write(Year), write(' is the year of the '), year_element(Year, Element), write(Element), write(' '), year_animal(Year, Animal), write(Animal), write(' '), year_yin_yang(Year, YinYang), write('('), write(YinYang), write('). '), year_element_char(Year, ElementChar), write(ElementChar), year_animal_char(Year, AnimalChar), write(AnimalChar), nl )).  
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
#Haskell
Haskell
import System.Directory (doesFileExist, doesDirectoryExist)   check :: (FilePath -> IO Bool) -> FilePath -> IO () check p s = do result <- p s putStrLn $ s ++ if result then " does exist" else " does not exist"   main :: IO () main = do check doesFileExist "input.txt" check doesDirectoryExist "docs" check doesFileExist "/input.txt" check doesDirectoryExist "/docs"
http://rosettacode.org/wiki/Chaos_game
Chaos game
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a starting point at random (preferably inside the triangle).   Then add the next point halfway between the starting point and one of the reference points.   This reference point is chosen at random. After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge. See also The Game of Chaos
#PARI.2FGP
PARI/GP
  \\ Chaos Game (Sierpinski triangle) 2/15/17 aev pChaosGameS3(size,lim)={ my(sz1=size\2,sz2=sz1*sqrt(3),M=matrix(size,size),x,y,xf,yf,v); x=random(size); y=random(sz2); for(i=1,lim, v=random(3); if(v==0, x/=2; y/=2;); if(v==1, x=sz1+(sz1-x)/2; y=sz2-(sz2-y)/2;); if(v==2, x=size-(size-x)/2; y/=2;); xf=floor(x); yf=floor(y); if(xf<1||xf>size||yf<1||yf>size, next); M[xf,yf]=1; );\\fend plotmat(M); } \\ Test: pChaosGameS3(600,30000); \\ SierpTri1.png  
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.
#Racket
Racket
  #lang racket   (define outs (list (current-output-port))) (define ((tell-all who o) line) (for ([c outs] #:unless (eq? o c)) (displayln (~a who ": " line) c)))   (define ((client i o)) (define nick (begin (display "Nick: " o) (read-line i))) (define tell (tell-all nick o)) (let loop ([line "(joined)"]) (if (eof-object? line) (begin (tell "(left)") (set! outs (remq o outs)) (close-output-port o)) (begin (tell line) (loop (read-line i))))))   (define (chat-server listener) (define-values [i o] (tcp-accept listener)) (for ([p (list i o)]) (file-stream-buffer-mode p 'none)) (thread (client i o)) (set! outs (cons o outs)) (chat-server listener))   (void (thread (λ() (chat-server (tcp-listen 12321))))) ((client (current-input-port) (current-output-port)))  
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.
#Elixir
Elixir
iex(1)> code = ?a 97 iex(2)> to_string([code]) "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.
#Emacs_Lisp
Emacs Lisp
(string-to-char "a") ;=> 97 (format "%c" 97) ;=> "a"
http://rosettacode.org/wiki/Cholesky_decomposition
Cholesky decomposition
Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interpreted as a generalized square root of A {\displaystyle A} , as described in Cholesky decomposition. In a 3x3 example, we have to solve the following system of equations: A = ( a 11 a 21 a 31 a 21 a 22 a 32 a 31 a 32 a 33 ) = ( l 11 0 0 l 21 l 22 0 l 31 l 32 l 33 ) ( l 11 l 21 l 31 0 l 22 l 32 0 0 l 33 ) ≡ L L T = ( l 11 2 l 21 l 11 l 31 l 11 l 21 l 11 l 21 2 + l 22 2 l 31 l 21 + l 32 l 22 l 31 l 11 l 31 l 21 + l 32 l 22 l 31 2 + l 32 2 + l 33 2 ) {\displaystyle {\begin{aligned}A&={\begin{pmatrix}a_{11}&a_{21}&a_{31}\\a_{21}&a_{22}&a_{32}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}\\&={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}l_{11}&l_{21}&l_{31}\\0&l_{22}&l_{32}\\0&0&l_{33}\end{pmatrix}}\equiv LL^{T}\\&={\begin{pmatrix}l_{11}^{2}&l_{21}l_{11}&l_{31}l_{11}\\l_{21}l_{11}&l_{21}^{2}+l_{22}^{2}&l_{31}l_{21}+l_{32}l_{22}\\l_{31}l_{11}&l_{31}l_{21}+l_{32}l_{22}&l_{31}^{2}+l_{32}^{2}+l_{33}^{2}\end{pmatrix}}\end{aligned}}} We can see that for the diagonal elements ( l k k {\displaystyle l_{kk}} ) of L {\displaystyle L} there is a calculation pattern: l 11 = a 11 {\displaystyle l_{11}={\sqrt {a_{11}}}} l 22 = a 22 − l 21 2 {\displaystyle l_{22}={\sqrt {a_{22}-l_{21}^{2}}}} l 33 = a 33 − ( l 31 2 + l 32 2 ) {\displaystyle l_{33}={\sqrt {a_{33}-(l_{31}^{2}+l_{32}^{2})}}} or in general: l k k = a k k − ∑ j = 1 k − 1 l k j 2 {\displaystyle l_{kk}={\sqrt {a_{kk}-\sum _{j=1}^{k-1}l_{kj}^{2}}}} For the elements below the diagonal ( l i k {\displaystyle l_{ik}} , where i > k {\displaystyle i>k} ) there is also a calculation pattern: l 21 = 1 l 11 a 21 {\displaystyle l_{21}={\frac {1}{l_{11}}}a_{21}} l 31 = 1 l 11 a 31 {\displaystyle l_{31}={\frac {1}{l_{11}}}a_{31}} l 32 = 1 l 22 ( a 32 − l 31 l 21 ) {\displaystyle l_{32}={\frac {1}{l_{22}}}(a_{32}-l_{31}l_{21})} which can also be expressed in a general formula: l i k = 1 l k k ( a i k − ∑ j = 1 k − 1 l i j l k j ) {\displaystyle l_{ik}={\frac {1}{l_{kk}}}\left(a_{ik}-\sum _{j=1}^{k-1}l_{ij}l_{kj}\right)} Task description The task is to implement a routine which will return a lower Cholesky factor L {\displaystyle L} for every given symmetric, positive definite nxn matrix A {\displaystyle A} . You should then test it on the following two examples and include your output. Example 1: 25 15 -5 5 0 0 15 18 0 --> 3 3 0 -5 0 11 -1 1 3 Example 2: 18 22 54 42 4.24264 0.00000 0.00000 0.00000 22 70 86 62 --> 5.18545 6.56591 0.00000 0.00000 54 86 174 134 12.72792 3.04604 1.64974 0.00000 42 62 134 106 9.89949 1.62455 1.84971 1.39262 Note The Cholesky decomposition of a Pascal upper-triangle matrix is the Identity matrix of the same size. The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
#PL.2FI
PL/I
(subscriptrange): decompose: procedure options (main); /* 31 October 2013 */ declare a(*,*) float controlled;   allocate a(3,3) initial (25, 15, -5, 15, 18, 0, -5, 0, 11); put skip list ('Original matrix:'); put edit (a) (skip, 3 f(4));   call cholesky(a); put skip list ('Decomposed matrix'); put edit (a) (skip, 3 f(4)); free a; allocate a(4,4) initial (18, 22, 54, 42, 22, 70, 86, 62, 54, 86, 174, 134, 42, 62, 134, 106); put skip list ('Original matrix:'); put edit (a) (skip, (hbound(a,1)) f(12) ); call cholesky(a); put skip list ('Decomposed matrix'); put edit (a) (skip, (hbound(a,1)) f(12,5) );   cholesky: procedure(a); declare a(*,*) float; declare L(hbound(a,1), hbound(a,2)) float; declare s float; declare (i, j, k) fixed binary;   L = 0; do i = lbound(a,1) to hbound(a,1); do j = lbound(a,2) to i; s = 0; do k = lbound(a,2) to j-1; s = s + L(i,k) * L(j,k); end; if i = j then L(i,j) = sqrt(a(i,i) - s); else L(i,j) = (a(i,j) - s) / L(j,j); end; end; a = L; end cholesky;   end decompose;
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
#Vlang
Vlang
import time   struct Birthday { month int day int }   fn (b Birthday) str() string { return "${time.long_months[b.month-1]} $b.day" }   fn (b Birthday) month_uniquie_in(bds []Birthday) bool { mut count := 0 for bd in bds { if bd.month == b.month { count++ } } if count == 1 { return true } return false }   fn (b Birthday) day_unique_in(bds []Birthday) bool { mut count := 0 for bd in bds { if bd.day == b.day { count++ } } if count == 1 { return true } return false }   fn (b Birthday) month_with_unique_day_in(bds []Birthday) bool { for bd in bds { if bd.month == b.month && bd.day_unique_in(bds) { return true } } return false }   fn main() { choices := [ Birthday{5, 15}, Birthday{5, 16}, Birthday{5, 19}, Birthday{6, 17}, Birthday{6, 18}, Birthday{7, 14}, Birthday{7, 16}, Birthday{8, 14}, Birthday{8, 15}, Birthday{8, 17}, ]   // Albert knows the month but doesn't know the day. // So the month can't be unique within the choices. mut filtered := []Birthday{} for bd in choices { if !bd.month_uniquie_in(choices) { filtered << bd } }   // Albert also knows that Bernard doesn't know the answer. // So the month can't have a unique day. mut filtered2 := []Birthday{} for bd in filtered { if !bd.month_with_unique_day_in(filtered) { filtered2 << bd } }   // Bernard now knows the answer. // So the day must be unique within the remaining choices. mut filtered3 := []Birthday{} for bd in filtered2 { if bd.day_unique_in(filtered2) { filtered3 << bd } }   // Albert now knows the answer too. // So the month must be unique within the remaining choices. mut filtered4 := []Birthday{} for bd in filtered3 { if bd.month_uniquie_in(filtered3) { filtered4 << bd } }   if filtered4.len == 1 { println("Cheryl's Birthday is ${filtered4[0]}") } else { println("Something went wrong!") } }
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
#Wren
Wren
var Months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]   class Birthday { construct new(month, day) { _month = month _day = day }   month { _month } day { _day }   toString { "%(Months[_month-1]) %(day)" }   monthUniqueIn(bds) { bds.count { |bd| _month == bd.month } == 1 }   dayUniqueIn(bds) { bds.count { |bd| _day == bd.day } == 1 }   monthWithUniqueDayIn(bds) { bds.any { |bd| (_month == bd.month) && bd.dayUniqueIn(bds) } } }   var choices = [ Birthday.new(5, 15), Birthday.new(5, 16), Birthday.new(5, 19), Birthday.new(6, 17), Birthday.new(6, 18), Birthday.new(7, 14), Birthday.new(7, 16), Birthday.new(8, 14), Birthday.new(8, 15), Birthday.new(8, 17) ]   // Albert knows the month but doesn't know the day. // So the month can't be unique within the choices. var filtered = choices.where { |bd| !bd.monthUniqueIn(choices) }.toList   // Albert also knows that Bernard doesn't know the answer. // So the month can't have a unique day. filtered = filtered.where { |bd| !bd.monthWithUniqueDayIn(filtered) }.toList   // Bernard now knows the answer. // So the day must be unique within the remaining choices. filtered = filtered.where { |bd| bd.dayUniqueIn(filtered) }.toList   // Albert now knows the answer too. // So the month must be unique within the remaining choices. filtered = filtered.where { |bd| bd.monthUniqueIn(filtered) }.toList   if (filtered.count == 1) { System.print("Cheryl's birthday is %(filtered[0])") } else { System.print("Something went wrong!") }
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
#OCaml
OCaml
[1; 2; 3; 4; 5]
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
#R
R
print(combn(0:4, 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.
#Tailspin
Tailspin
  templates foo when <=0> do 'zero' -> !OUT::write when <..0> do 'negative ' -> !OUT::write -$ -> # when <?($ mod 2 <=0>)> do 'even' -> !OUT::write otherwise 'odd' -> !OUT::write end foo  
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.
#Tcl
Tcl
if {$foo == 3} { puts "foo is three" } elseif {$foo == 4} { puts "foo is four" } else { puts "foo is neither three nor four" }
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}}} .
#PicoLisp
PicoLisp
(de modinv (A B) (let (B0 B X0 0 X1 1 Q 0 T1 0) (while (< 1 A) (setq Q (/ A B) T1 B B (% A B) A T1 T1 X0 X0 (- X1 (* Q X0)) X1 T1 ) ) (if (lt0 X1) (+ X1 B0) X1) ) )   (de chinrem (N A) (let P (apply * N) (% (sum '((N A) (setq T1 (/ P N)) (* A (modinv T1 N) T1) ) N A ) P ) ) )   (println (chinrem (3 5 7) (2 3 2)) (chinrem (11 12 13) (10 4 12)) )   (bye)
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}}} .
#Prolog
Prolog
  product(A, B, C) :- C is A*B.   pair(X, Y, X-Y).   egcd(_, 0, 1, 0) :- !. egcd(A, B, X, Y) :- divmod(A, B, Q, R), egcd(B, R, S, X), Y is S - Q*X.   modinv(A, B, X) :- egcd(A, B, X, Y), A*X + B*Y =:= 1.   crt_fold(A, M, P, R0, R1) :- % system of equations of (x = a) (mod m); p = M/m modinv(P, M, Inv), R1 is R0 + A*Inv*P.   crt(Pairs, N) :- maplist(pair, As, Ms, Pairs), foldl(product, Ms, 1, M), maplist(divmod(M), Ms, Ps, _), % p(n) <- M/m(n) foldl(crt_fold, As, Ms, Ps, 0, N0), N is N0 mod M.  
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, as a type, has the values and operations of its own. The operations of are usually called methods of the root type. Both operations and values are called polymorphic. A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument. The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual. Operations with multiple arguments and/or the results of the class are called multi-methods. A further generalization of is the operation with arguments and/or results from different classes. single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x). multiple-dispatch languages allow many arguments and/or results to control the dispatch. A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type. This type is sometimes called the most specific type of a [polymorphic] value. The type tag of the value is used in order to resolve the dispatch. The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class. In many OO languages the type of the class of T and T itself are considered equivalent. In some languages they are distinct (like in Ada). When class T and T are equivalent, there is no way to distinguish polymorphic and specific values. Task Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
#Pascal
Pascal
{ # a class is a package (i.e. a namespace) with methods in it package MyClass;   # a constructor is a function that returns a blessed reference sub new { my $class = shift; bless {variable => 0}, $class; # the instance object is a hashref in disguise. # (it can be a ref to anything.) }   # an instance method is a function that takes an object as first argument. # the -> invocation syntax takes care of that nicely, see Usage paragraph below. sub some_method { my $self = shift; $self->{variable} = 1; } }
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.
#Perl
Perl
{ # a class is a package (i.e. a namespace) with methods in it package MyClass;   # a constructor is a function that returns a blessed reference sub new { my $class = shift; bless {variable => 0}, $class; # the instance object is a hashref in disguise. # (it can be a ref to anything.) }   # an instance method is a function that takes an object as first argument. # the -> invocation syntax takes care of that nicely, see Usage paragraph below. sub some_method { my $self = shift; $self->{variable} = 1; } }
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)
#REXX
REXX
/*REXX program solves the closest pair of points problem (in two dimensions). */ parse arg N LO HI seed . /*obtain optional arguments from the CL*/ if N=='' | N=="," then N= 100 /*Not specified? Then use the default.*/ if LO=='' | LO=="," then LO= 0 /* " " " " " " */ if HI=='' | HI=="," then HI= 20000 /* " " " " " " */ if datatype(seed, 'W') then call random ,,seed /*seed for RANDOM (BIF) repeatability.*/ w= length(HI); w= w + (w//2==0) /*W: for aligning the output columns.*/   /*╔══════════════════════╗*/ do j=1 for N /*generate N random points*/ /*║ generate N points. ║*/ @x.j= random(LO, HI) /* " a " X */ /*╚══════════════════════╝*/ @y.j= random(LO, HI) /* " a " Y */ end /*j*/ /*X & Y make the point.*/ A= 1; B= 2 /* [↓] MIND is actually the squared */ minD= (@x.A - @x.B)**2 + (@y.A - @y.B)**2 /* distance between the 1st two points.*/ /* [↓] use of XJ & YJ speed things up.*/ do j=1 for N-1; xj= @x.j; yj= @y.j /*find min distance between a point ···*/ do k=j+1 for N-j-1 /* ··· and all other (higher) points. */ sd= (xj - @x.k)**2 + (yj - @y.k)**2 /*compute squared distance from points.*/ if sd<minD then parse value sd j k with minD A B end /*k*/ /* [↑] needn't take SQRT of SD (yet).*/ end /*j*/ /* [↑] when done, A & B are the points*/ $= 'For ' N " points, the minimum distance between the two points: " say $ center("x", w, '═')" " center('y', w, "═") ' is: ' sqrt( abs(minD)) / 1 say left('', length($) - 1) "["right(@x.A, w)',' right(@y.A, w)"]" say left('', length($) - 1) "["right(@x.B, w)',' right(@y.B, w)"]" exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); m.=9; numeric form; h=d+6 numeric digits; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g= g *.5'e'_ % 2 do j=0 while h>9; m.j= h; h= h % 2 + 1; end /*j*/ do k=j+5 to 0 by -1; numeric digits m.k; g= (g+x/g)*.5; end /*k*/; return g
http://rosettacode.org/wiki/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
#Oforth
Oforth
: circleCenter(x1, y1, x2, y2, r) | d xmid ymid r1 md | x2 x1 - sq y2 y1 - sq + sqrt -> d x1 x2 + 2 / -> xmid y1 y2 + 2 / -> ymid 2 r * -> r1   d 0.0 == ifTrue: [ "Infinite number of circles" . return ] d r1 == ifTrue: [ System.Out "One circle: (" << xmid << ", " << ymid << ")" << cr return ] d r1 > ifTrue: [ "No circle" . return ]   r sq d 2 / sq - sqrt ->md   System.Out "C1 : (" << xmid y1 y2 - md * d / + << ", " << ymid x2 x1 - md * d / + << ")" << cr System.Out "C2 : (" << xmid y1 y2 - md * d / - << ", " << ymid x2 x1 - md * d / - << ")" << cr ;
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).
#PureBasic
PureBasic
EnableExplicit #BASE=4 #SPC=Chr(32)   Procedure.s ChineseZodiac(n.i) Define cycle_year.i=n-#BASE, stem_number.i = cycle_year%10+1, element_number.i = Round(stem_number/2,#PB_Round_Nearest), branch_number.i = cycle_year%12+1, aspect_number.i = cycle_year%2+1, index.i = cycle_year%60+1, celestial$ = Chr(PeekU(?Celestial_stem+SizeOf(Character)*(stem_number-1))), c_pinyin$ = StringField(PeekS(?Stem),stem_number,"\"), element$ = StringField(PeekS(?Element),element_number,"\"), branch_han$ = Chr(PeekU(?Terrestrial_branch+SizeOf(Character)*(branch_number-1))), b_pinyin$ = StringField(PeekS(?Branch),branch_number,"\"), animal$ = StringField(PeekS(?Zodiac_animal),branch_number,"\"), aspect$ = StringField(PeekS(?Aspect),aspect_number,"\"), YearOfCycle$ = Str(index) ProcedureReturn Str(n)+#SPC+ LSet(element$,7,#SPC)+#SPC+ LSet(animal$,7,#SPC)+#SPC+ LSet(aspect$,6,#SPC)+#SPC+ RSet(YearOfCycle$,11)+#SPC+ LSet(c_pinyin$+"-"+b_pinyin$,9,#SPC)+#SPC+ celestial$+branch_han$ EndProcedure   LoadFont(0,"Consolas",12) If OpenWindow(0,#PB_Ignore,#PB_Ignore,600,400,"Chinese Zodiac",#PB_Window_ScreenCentered|#PB_Window_SystemMenu) EditorGadget(0, 8, 8, 600-16, 400-16) : SetGadgetFont(0,FontID(0)) Define header$="Year Element Animal Aspect YearOfCycle ASCII Chinese" AddGadgetItem(0,-1,header$) AddGadgetItem(0,-1,ChineseZodiac(1935)) AddGadgetItem(0,-1,ChineseZodiac(1938)) AddGadgetItem(0,-1,ChineseZodiac(1968)) AddGadgetItem(0,-1,ChineseZodiac(1972)) AddGadgetItem(0,-1,ChineseZodiac(1976)) AddGadgetItem(0,-1,ChineseZodiac(1984)) AddGadgetItem(0,-1,ChineseZodiac(Year(Date()))) Repeat : Until WaitWindowEvent() = #PB_Event_CloseWindow EndIf   DataSection Celestial_stem: : Data.u $7532, $4E59, $4E19, $4E01, $620A, $5DF1, $5E9A, $8F9B, $58EC, $7678 Terrestrial_branch: : Data.u $5B50, $4E11, $5BC5, $536F, $8FB0, $5DF3, $5348, $672A, $7533, $9149, $620C, $4EA5 Zodiac_animal: : Data.s "Rat\Ox\Tiger\Rabbit\Dragon\Snake\Horse\Goat\Monkey\Rooster\Dog\Pig" Element: : Data.s "Wood\Fire\Earth\Metal\Water" Aspect: : Data.s "yang\yin" Stem: : Data.s "jiă\yĭ\bĭng\dīng\wù\jĭ\gēng\xīn\rén\gŭi" Branch: : Data.s "zĭ\chŏu\yín\măo\chén\sì\wŭ\wèi\shēn\yŏu\xū\hài" EndDataSection
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
#hexiscript
hexiscript
println "File \"input.txt\"? " + (exists "input.txt") println "Dir \"docs\"? " + (exists "docs/") println "File \"/input.txt\"? " + (exists "/input.txt") println "Dir \"/docs\"? " + (exists "/docs/")
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an unusual filename:   `Abdu'l-Bahá.txt
#HicEst
HicEst
OPEN(FIle= 'input.txt', OLD, IOStat=ios, ERror=99) OPEN(FIle='C:\input.txt', OLD, IOStat=ios, ERror=99) ! ... 99 WRITE(Messagebox='!') 'File does not exist. Error message ', ios
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
#Pascal
Pascal
  program ChaosGame;   // FPC 3.0.2 uses Graph, windows, math;   // Return a point on a circle defined by angle and the circles radius // Angle 0 = Radius points to the left // Angle 90 = Radius points upwards Function PointOfCircle(Angle: SmallInt; Radius: integer): TPoint; var Ia: Double; begin Ia:=DegToRad(-Angle); result.x:=round(cos(Ia)*Radius); result.y:=round(sin(Ia)*Radius); end;   { Main }   var GraphDev,GraphMode: smallint; Triangle: array[0..2] of Tpoint; // Corners of the triangle TriPnt: Byte; // Point in ^^^^ Origin: TPoint; // Defines center of triangle Itterations: integer; // Number of Itterations Radius: Integer; View: viewPorttype; CurPnt: TPoint; Rect: TRect; Counter: integer; begin   Repeat {forever}   // Get the Itteration count 0=exit Write('Itterations: '); ReadLn(Itterations);   if Itterations=0 then halt;   // Set Up Graphics screen (everythings Auto detect) GraphDev:=Detect; GraphMode:=0; InitGraph(GraphDev,GraphMode,''); if GraphResult<>grok then begin Writeln('Graphics doesn''t work'); Halt; end;   // set Origin to center of the _Triangle_ (Not the creen) GetViewSettings(View); Rect.Create(View.x1,View.y1+10,View.x2,View.y2-10); Origin:=Rect.CenterPoint; Origin.Offset(0,Rect.Height div 6); // Center Triangle on screen   // Define Equilateral triangle, Radius:=Origin.y; // Radius of Circumscribed circle for Counter:=0 to 2 do Triangle[Counter]:=PointOfCircle((Counter*120)+90,Radius)+Origin;   // Choose random starting point, in the incsribed circle of the triangle Radius:=Radius div 2; // Radius of inscribed circle CurPnt:=PointOfCircle(random(360),random(Radius div 2))+Origin;   // Play the Chaos Game for Counter:=0 to Itterations do begin TriPnt:=Random(3); // Select Triangle Point Rect.Create(Triangle[TriPnt],CurPnt);; // Def. rect. between TriPnt and CurPnt CurPnt:=Rect.CenterPoint; // New CurPnt is center of rectangle putPixel(CurPnt.x,CurPnt.y,cyan); // Plot the new CurPnt end;   until False; 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.
#Raku
Raku
react { my %connections;   whenever IO::Socket::Async.listen('localhost', 4004) -> $conn { my $name;   $conn.print: "Please enter your name: ";   whenever $conn.Supply.lines -> $message { if !$name { if %connections{$message} { $conn.print: "Name already taken, choose another one: "; } else { $name = $message; %connections{$name} = $conn; broadcast "+++ %s arrived +++", $name; } } else { broadcast "%s> %s", $name, $message; } LAST { broadcast "--- %s left ---", $name; %connections{$name}:delete; $conn.close ; } QUIT { default { say "oh no, $_"; } } } }   sub broadcast ($format, $from, *@message) { my $text = sprintf $format, $from, |@message; say $text; for %connections.kv -> $name, $conn { $conn.print: "$text\n" if $name ne $from; } } }
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.
#Erlang
Erlang
1> F = fun([X]) -> X end. #Fun<erl_eval.6.13229925> 2> F("a"). 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.
#Euphoria
Euphoria
printf(1,"%d\n", 'a') -- prints "97" printf(1,"%s\n", 97) -- prints "a"
http://rosettacode.org/wiki/Cholesky_decomposition
Cholesky decomposition
Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interpreted as a generalized square root of A {\displaystyle A} , as described in Cholesky decomposition. In a 3x3 example, we have to solve the following system of equations: A = ( a 11 a 21 a 31 a 21 a 22 a 32 a 31 a 32 a 33 ) = ( l 11 0 0 l 21 l 22 0 l 31 l 32 l 33 ) ( l 11 l 21 l 31 0 l 22 l 32 0 0 l 33 ) ≡ L L T = ( l 11 2 l 21 l 11 l 31 l 11 l 21 l 11 l 21 2 + l 22 2 l 31 l 21 + l 32 l 22 l 31 l 11 l 31 l 21 + l 32 l 22 l 31 2 + l 32 2 + l 33 2 ) {\displaystyle {\begin{aligned}A&={\begin{pmatrix}a_{11}&a_{21}&a_{31}\\a_{21}&a_{22}&a_{32}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}\\&={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}l_{11}&l_{21}&l_{31}\\0&l_{22}&l_{32}\\0&0&l_{33}\end{pmatrix}}\equiv LL^{T}\\&={\begin{pmatrix}l_{11}^{2}&l_{21}l_{11}&l_{31}l_{11}\\l_{21}l_{11}&l_{21}^{2}+l_{22}^{2}&l_{31}l_{21}+l_{32}l_{22}\\l_{31}l_{11}&l_{31}l_{21}+l_{32}l_{22}&l_{31}^{2}+l_{32}^{2}+l_{33}^{2}\end{pmatrix}}\end{aligned}}} We can see that for the diagonal elements ( l k k {\displaystyle l_{kk}} ) of L {\displaystyle L} there is a calculation pattern: l 11 = a 11 {\displaystyle l_{11}={\sqrt {a_{11}}}} l 22 = a 22 − l 21 2 {\displaystyle l_{22}={\sqrt {a_{22}-l_{21}^{2}}}} l 33 = a 33 − ( l 31 2 + l 32 2 ) {\displaystyle l_{33}={\sqrt {a_{33}-(l_{31}^{2}+l_{32}^{2})}}} or in general: l k k = a k k − ∑ j = 1 k − 1 l k j 2 {\displaystyle l_{kk}={\sqrt {a_{kk}-\sum _{j=1}^{k-1}l_{kj}^{2}}}} For the elements below the diagonal ( l i k {\displaystyle l_{ik}} , where i > k {\displaystyle i>k} ) there is also a calculation pattern: l 21 = 1 l 11 a 21 {\displaystyle l_{21}={\frac {1}{l_{11}}}a_{21}} l 31 = 1 l 11 a 31 {\displaystyle l_{31}={\frac {1}{l_{11}}}a_{31}} l 32 = 1 l 22 ( a 32 − l 31 l 21 ) {\displaystyle l_{32}={\frac {1}{l_{22}}}(a_{32}-l_{31}l_{21})} which can also be expressed in a general formula: l i k = 1 l k k ( a i k − ∑ j = 1 k − 1 l i j l k j ) {\displaystyle l_{ik}={\frac {1}{l_{kk}}}\left(a_{ik}-\sum _{j=1}^{k-1}l_{ij}l_{kj}\right)} Task description The task is to implement a routine which will return a lower Cholesky factor L {\displaystyle L} for every given symmetric, positive definite nxn matrix A {\displaystyle A} . You should then test it on the following two examples and include your output. Example 1: 25 15 -5 5 0 0 15 18 0 --> 3 3 0 -5 0 11 -1 1 3 Example 2: 18 22 54 42 4.24264 0.00000 0.00000 0.00000 22 70 86 62 --> 5.18545 6.56591 0.00000 0.00000 54 86 174 134 12.72792 3.04604 1.64974 0.00000 42 62 134 106 9.89949 1.62455 1.84971 1.39262 Note The Cholesky decomposition of a Pascal upper-triangle matrix is the Identity matrix of the same size. The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
#PowerShell
PowerShell
  function cholesky ($a) { $l = @() if ($a) { $n = $a.count $end = $n - 1 $l = 1..$n | foreach {$row = @(0) * $n; ,$row} foreach ($k in 0..$end) { $m = $k - 1 $sum = 0 if(0 -lt $k) { foreach ($j in 0..$m) {$sum += $l[$k][$j]*$l[$k][$j]} } $l[$k][$k] = [Math]::Sqrt($a[$k][$k] - $sum) if ($k -lt $end) { foreach ($i in ($k+1)..$end) { $sum = 0 if (0 -lt $k) { foreach ($j in 0..$m) {$sum += $l[$i][$j]*$l[$k][$j]} } $l[$i][$k] = ($a[$i][$k] - $sum)/$l[$k][$k] } } } } $l }   function show($a) {$a | foreach {"$_"}}   $a1 = @( @(25, 15, -5), @(15, 18, 0), @(-5, 0, 11) ) "a1 =" show $a1 "" "l1 =" show (cholesky $a1) "" $a2 = @( @(18, 22, 54, 42), @(22, 70, 86, 62), @(54, 86, 174, 134), @(42, 62, 134, 106) ) "a2 =" show $a2 "" "l2 =" show (cholesky $a2)  
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
#zkl
zkl
dates:=T(T("May", 15), T("May", 16), T("May", 19), T("June", 17), T("June", 18), T("July", 14), T("July", 16), T("August",14), T("August",15), T("August",17) ); mDs:=dates.pump(Dictionary().appendKV); // "June":(15,16,19), ... dMs:=dates.pump(Dictionary().appendKV,"reverse"); // 15:"May", 16:"May", 19:"May", ...   // remove unique days (18,19) --> "July":(14,16),"August":(14,15,17) dMs.values.apply2('wrap(ms){ if(ms.len()==1) mDs.del(ms[0]) });   // find intersection of above days --> (14) fcn intersection(l1,l2){ l1.pump(List,l2.holds,'==(True),Void.Filter) } badDs:=mDs.values.reduce(intersection);   // --> July:(16),August:(15,17) --> ( ("July",(16)) ) theDay:=mDs.filter('wrap([(m,ds)]){ ds.removeEach(badDs).len()==1 });   // print birthday such that muliples are shown, if any println("Cheryl's birthday is ",theDay.flatten().flatten().concat(" "));
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
#Oforth
Oforth
Buffer A collection of bytes Mem A mutable collection of bytes Interval A first value, a last value and a step. Pair A collection of 2 elements (with key/value features). List A collection of n elements ListBuffer A mutable collection of n elements that can grow when necessary String A collection of n characters Symbol A collection of n characters that are identity (if they are equal, they are the same object). StringBuffer A mutable collection of n charaters that can grow when necessary
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
#Racket
Racket
  (define sublists (match-lambda** [(0 _) '(())] [(_ '()) '()] [(m (cons x xs)) (append (map (curry cons x) (sublists (- m 1) xs)) (sublists m xs))]))   (define (combinations n m) (sublists n (range m)))  
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.
#Tern
Tern
if(a > b) println(a);
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}}} .
#PureBasic
PureBasic
EnableExplicit DisableDebugger DataSection LBL_n1: Data.i 3,5,7 LBL_a1: Data.i 2,3,2 LBL_n2: Data.i 11,12,13 LBL_a2: Data.i 10,4,12 LBL_n3: Data.i 10,4,9 LBL_a3: Data.i 11,22,19 EndDataSection   Procedure ErrorHdl() Print(ErrorMessage()) Input() EndProcedure   Macro PrintData(n,a) Define Idx.i=0 Print("[") While n+SizeOf(Integer)*Idx<a Print("( ") Print(Str(PeekI(a+SizeOf(Integer)*Idx))) Print(" . ") Print(Str(PeekI(n+SizeOf(Integer)*Idx))) Print(" )") Idx+1 Wend Print(~"]\nx = ") EndMacro   Procedure.i Produkt_n(n_Adr.i,a_Adr.i) Define p.i=1 While n_Adr<a_Adr p*PeekI(n_Adr) n_Adr+SizeOf(Integer) Wend ProcedureReturn p EndProcedure   Procedure.i Eval_x1(a.i,b.i) Define b0.i=b, x0.i=0, x1.i=1, q.i, t.i If b=1 : ProcedureReturn x1 : EndIf While a>1 q=Int(a/b) t=b : b=a%b : a=t t=x0 : x0=x1-q*x0 : x1=t Wend If x1<0 : ProcedureReturn x1+b0 : EndIf ProcedureReturn x1 EndProcedure   Procedure.i ChineseRem(n_Adr.i,a_Adr.i) Define prod.i=Produkt_n(n_Adr,a_Adr), a.i, b.i, p.i, Idx.i=0, sum.i While n_Adr+SizeOf(Integer)*Idx<a_Adr b=PeekI(n_Adr+SizeOf(Integer)*Idx) p=Int(prod/b) : a=p sum+PeekI(a_Adr+SizeOf(Integer)*Idx)*Eval_x1(a,b)*p Idx+1 Wend ProcedureReturn sum%prod EndProcedure   OnErrorCall(@ErrorHdl()) OpenConsole("Chinese remainder theorem") PrintData(?LBL_n1,?LBL_a1) PrintN(Str(ChineseRem(?LBL_n1,?LBL_a1))) PrintData(?LBL_n2,?LBL_a2) PrintN(Str(ChineseRem(?LBL_n2,?LBL_a2))) PrintData(?LBL_n3,?LBL_a3) PrintN(Str(ChineseRem(?LBL_n3,?LBL_a3))) Input()
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.
#Phix
Phix
without js -- (else cffi namespaces error, classes not supported by pwa/p2js anyway) requires ("1.0.2") -- (free up the temp used in the v.show() call) class five nullable private integer n = 3 function get_n() return n end function procedure set_n(integer n) this.n = n end procedure procedure show() printf(1,"show: n is %d\n",{n}) end procedure function five(integer n = 4) printf(1,"constructor five(%d) called\n",n) this.n = n return this end function procedure ~five() printf(1,"destructor ~five(%d) called\n",n) end procedure end class five v = new({5}) assert(v.n=5) v.n = 6 v.show() v=NULL
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)
#Ring
Ring
  decimals(10) x = list(10) y = list(10) x[1] = 0.654682 y[1] = 0.925557 x[2] = 0.409382 y[2] = 0.619391 x[3] = 0.891663 y[3] = 0.888594 x[4] = 0.716629 y[4] = 0.996200 x[5] = 0.477721 y[5] = 0.946355 x[6] = 0.925092 y[6] = 0.818220 x[7] = 0.624291 y[7] = 0.142924 x[8] = 0.211332 y[8] = 0.221507 x[9] = 0.293786 y[9] = 0.691701 x[10] = 0.839186 y[10] = 0.728260   min = 10000 for i = 1 to 9 for j = i+1 to 10 dsq = pow((x[i] - x[j]),2) + pow((y[i] - y[j]),2) if dsq < min min = dsq mini = i minj = j ok next next see "closest pair is : " + mini + " and " + minj + " at distance " + sqrt(min)  
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points
Circles of given radius through two points
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. Exceptions r==0.0 should be treated as never describing circles (except in the case where the points are coincident). If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point. If the points form a diameter then return two identical circles or return a single circle, according to which is the most natural mechanism for the implementation language. If the points are too far apart then no circles can be drawn. Task detail Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, or some indication of special cases where two, possibly equal, circles cannot be returned. Show here the output for the following inputs: p1 p2 r 0.1234, 0.9876 0.8765, 0.2345 2.0 0.0000, 2.0000 0.0000, 0.0000 1.0 0.1234, 0.9876 0.1234, 0.9876 2.0 0.1234, 0.9876 0.8765, 0.2345 0.5 0.1234, 0.9876 0.1234, 0.9876 0.0 Related task   Total circles area. See also   Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
#ooRexx
ooRexx
/*REXX pgm finds 2 circles with a specific radius given two (X,Y) points*/ a.='' a.1=0.1234 0.9876 0.8765 0.2345 2 a.2=0.0000 2.0000 0.0000 0.0000 1 a.3=0.1234 0.9876 0.1234 0.9876 2 a.4=0.1234 0.9876 0.8765 0.2345 0.5 a.5=0.1234 0.9876 0.1234 0.9876 0   Say ' x1 y1 x2 y2 radius cir1x cir1y cir2x cir2y' Say ' ------ ------ ------ ------ ------ ------ ------ ------ ------' Do j=1 By 1 While a.j<>'' Do k=1 For 4 w.k=f(word(a.j,k)) End Say w.1 w.2 w.3 w.4 format(word(a.j,5),5,1) twocircles(a.j) End Exit   twocircles: Procedure Parse Arg px py qx qy r . If r=0 Then Return ' radius of zero gives no circles.' x=(qx-px)/2 y=(qy-py)/2 bx=px+x by=py+y pb=rxCalcsqrt(x**2+y**2) If pb=0 Then Return ' coincident points give infinite circles' If pb>r Then Return ' points are too far apart for the given radius' cb=rxCalcsqrt(r**2-pb**2) x1=y*cb/pb y1=x*cb/pb Return f(bx-x1) f(by+y1) f(bx+x1) f(by-y1)   f: Return format(arg(1),2,4) /* format a number with 4 dec dig.*/   ::requires 'rxMath' library
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).
#Python
Python
  # coding: utf-8   from __future__ import print_function from datetime import datetime   pinyin = { '甲': 'jiă', '乙': 'yĭ', '丙': 'bĭng', '丁': 'dīng', '戊': 'wù', '己': 'jĭ', '庚': 'gēng', '辛': 'xīn', '壬': 'rén', '癸': 'gŭi',   '子': 'zĭ', '丑': 'chŏu', '寅': 'yín', '卯': 'măo', '辰': 'chén', '巳': 'sì', '午': 'wŭ', '未': 'wèi', '申': 'shēn', '酉': 'yŏu', '戌': 'xū', '亥': 'hài' }   animals = ['Rat', 'Ox', 'Tiger', 'Rabbit', 'Dragon', 'Snake', 'Horse', 'Goat', 'Monkey', 'Rooster', 'Dog', 'Pig'] elements = ['Wood', 'Fire', 'Earth', 'Metal', 'Water']   celestial = ['甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸'] terrestrial = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'] aspects = ['yang', 'yin']     def calculate(year): BASE = 4 year = int(year) cycle_year = year - BASE stem_number = cycle_year % 10 stem_han = celestial[stem_number] stem_pinyin = pinyin[stem_han] element_number = 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 print("{}: {}{} ({}-{}, {} {}; {} - year {} of the cycle)" .format(year, stem_han, branch_han, stem_pinyin, branch_pinyin, element, animal, aspect, index))     current_year = datetime.now().year years = [1935, 1938, 1968, 1972, 1976, current_year] for year in years: calculate(year)
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an unusual filename:   `Abdu'l-Bahá.txt
#HolyC
HolyC
U0 FileExists(U8 *f) { if (FileFind(f) && !IsDir(f)) { Print("'%s' file exists.\n", f); } else { Print("'%s' file does not exist.\n", f); } }   U0 DirExists(U8 *d) { if (IsDir(d)) { Print("'%s' directory exists.\n", d); } else { Print("'%s' directory does not exist.\n", d); } }   FileExists("input.txt"); FileExists("::/input.txt"); DirExists("docs"); DirExists("::/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
#i
i
concept exists(path) { open(path) errors { if error.DoesNotExist() print(path, " does not exist!") end return } print(path, " exists!") }   software { exists("input.txt") exists("/input.txt") exists("docs") exists("/docs") exists("docs/Abdu'l-Bahá.txt") }
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
#Perl
Perl
use Imager;   my $width = 1000; my $height = 1000;   my @points = ( [ $width/2, 0], [ 0, $height-1], [$height-1, $height-1], );   my $img = Imager->new( xsize => $width, ysize => $height, channels => 3, );   my $color = Imager::Color->new('#ff0000'); my $r = [int(rand($width)), int(rand($height))];   foreach my $i (1 .. 100000) { my $p = $points[rand @points];   my $h = [ int(($p->[0] + $r->[0]) / 2), int(($p->[1] + $r->[1]) / 2), ];   $img->setpixel( x => $h->[0], y => $h->[1], color => $color, );   $r = $h; }   $img->write(file => 'chaos_game_triangle.png');
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.
#Ruby
Ruby
require 'gserver'   class ChatServer < GServer def initialize *args super   #Keep a list for broadcasting messages @chatters = []   #We'll need this for thread safety @mutex = Mutex.new end   #Send message out to everyone but sender def broadcast message, sender = nil #Need to use \r\n for our Windows friends message = message.strip << "\r\n"   #Mutex for safety - GServer uses threads @mutex.synchronize do @chatters.each do |chatter| begin chatter.print message unless chatter == sender rescue @chatters.delete chatter end end end end   #Handle each connection def serve io io.print 'Name: ' name = io.gets   #They might disconnect return if name.nil?   name.strip!   broadcast "--+ #{name} has joined +--"   #Add to our list of connections @mutex.synchronize do @chatters << io end   #Get and broadcast input until connection returns nil loop do message = io.gets   if message broadcast "#{name}> #{message}", io else break end end   broadcast "--+ #{name} has left +--" end end   #Start up the server on port 7000 #Accept connections for any IP address #Allow up to 100 connections #Send information to stderr #Turn on informational messages ChatServer.new(7000, '0.0.0.0', 100, $stderr, true).start.join  
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.
#F.23
F#
let c = 'A' let n = 65 printfn "%d" (int c) printfn "%c" (char n)
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.
#Factor
Factor
CHAR: katakana-letter-a . "ア" first .   12450 1string print
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.
#Python
Python
from __future__ import print_function   from pprint import pprint from math import sqrt     def cholesky(A): L = [[0.0] * len(A) for _ in xrange(len(A))] for i in xrange(len(A)): for j in xrange(i+1): s = sum(L[i][k] * L[j][k] for k in xrange(j)) L[i][j] = sqrt(A[i][i] - s) if (i == j) else \ (1.0 / L[j][j] * (A[i][j] - s)) return L   if __name__ == "__main__": m1 = [[25, 15, -5], [15, 18, 0], [-5, 0, 11]] pprint(cholesky(m1)) print()   m2 = [[18, 22, 54, 42], [22, 70, 86, 62], [54, 86, 174, 134], [42, 62, 134, 106]] pprint(cholesky(m2), width=120)
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
#ooRexx
ooRexx
  a = .array~new(4) -- creates an array of 4 items, with all slots empty say a~size a~items -- size is 4, but there are 0 items a[1] = "Fred" -- assigns a value to the first item a[5] = "Mike" -- assigns a value to the fifth slot, expanding the size say a~size a~items -- size is now 5, with 2 items  
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
#Raku
Raku
.say for 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.
#TI-83_BASIC
TI-83 BASIC
If condition 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}}} .
#Python
Python
# Python 2.7 def chinese_remainder(n, a): sum = 0 prod = reduce(lambda a, b: a*b, n)   for n_i, a_i in zip(n, a): p = prod / n_i sum += a_i * mul_inv(p, n_i) * p return sum % prod     def mul_inv(a, b): b0 = b x0, x1 = 0, 1 if b == 1: return 1 while a > 1: q = a / b a, b = b, a%b x0, x1 = x1 - q * x0, x0 if x1 < 0: x1 += b0 return x1   if __name__ == '__main__': n = [3, 5, 7] a = [2, 3, 2] print chinese_remainder(n, a)
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.
#PHL
PHL
module classes;   extern printf;   class @MyClass { field @Integer myField { get:get_myField, set:set_myField };   new [ this.set_myField(2); ]   @Void method [ this.set_myField(this::get_myField + 1); ] };   @Integer main [ var obj = new @MyClass; printf("obj.myField: %i\n", obj::get_myField); obj::method; printf("obj.myField: %i\n", obj::get_myField); return 0; ]
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.
#PHP
PHP
class MyClass { public static $classVar; public $instanceVar; // can also initialize it here function __construct() { $this->instanceVar = 0; } function someMethod() { $this->instanceVar = 1; self::$classVar = 3; } } $myObj = new MyClass();
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)
#Ruby
Ruby
Point = Struct.new(:x, :y)   def distance(p1, p2) Math.hypot(p1.x - p2.x, p1.y - p2.y) end   def closest_bruteforce(points) mindist, minpts = Float::MAX, [] points.combination(2) do |pi,pj| dist = distance(pi, pj) if dist < mindist mindist = dist minpts = [pi, pj] end end [mindist, minpts] end   def closest_recursive(points) return closest_bruteforce(points) if points.length <= 3 xP = points.sort_by(&:x) mid = points.length / 2 xm = xP[mid].x dL, pairL = closest_recursive(xP[0,mid]) dR, pairR = closest_recursive(xP[mid..-1]) dmin, dpair = dL<dR ? [dL, pairL] : [dR, pairR] yP = xP.find_all {|p| (xm - p.x).abs < dmin}.sort_by(&:y) closest, closestPair = dmin, dpair 0.upto(yP.length - 2) do |i| (i+1).upto(yP.length - 1) do |k| break if (yP[k].y - yP[i].y) >= dmin dist = distance(yP[i], yP[k]) if dist < closest closest = dist closestPair = [yP[i], yP[k]] end end end [closest, closestPair] end   points = Array.new(100) {Point.new(rand, rand)} p ans1 = closest_bruteforce(points) p ans2 = closest_recursive(points) fail "bogus!" if ans1[0] != ans2[0]   require 'benchmark'   points = Array.new(10000) {Point.new(rand, rand)} Benchmark.bm(12) do |x| x.report("bruteforce") {ans1 = closest_bruteforce(points)} x.report("recursive") {ans2 = closest_recursive(points)} end
http://rosettacode.org/wiki/Circles_of_given_radius_through_two_points
Circles of given radius through two points
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points. Exceptions r==0.0 should be treated as never describing circles (except in the case where the points are coincident). If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point. If the points form a diameter then return two identical circles or return a single circle, according to which is the most natural mechanism for the implementation language. If the points are too far apart then no circles can be drawn. Task detail Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, or some indication of special cases where two, possibly equal, circles cannot be returned. Show here the output for the following inputs: p1 p2 r 0.1234, 0.9876 0.8765, 0.2345 2.0 0.0000, 2.0000 0.0000, 0.0000 1.0 0.1234, 0.9876 0.1234, 0.9876 2.0 0.1234, 0.9876 0.8765, 0.2345 0.5 0.1234, 0.9876 0.1234, 0.9876 0.0 Related task   Total circles area. See also   Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel
#PARI.2FGP
PARI/GP
circ(a, b, r)={ if(a==b, return("impossible")); my(h=(b-a)/2,t=sqrt(r^2-abs(h)^2)/abs(h)*h); [a+h+t*I,a+h-t*I] }; circ(0.1234 + 0.9876*I, 0.8765 + 0.2345*I, 2) circ(0.0000 + 2.0000*I, 0.0000 + 0.0000*I, 1) circ(0.1234 + 0.9876*I, 0.1234 + 0.9876*I, 2) circ(0.1234 + 0.9876*I, 0.8765 + 0.2345*I, .5) circ(0.1234 + 0.9876*I, 0.1234 + 0.9876*I, 0)
http://rosettacode.org/wiki/Chinese_zodiac
Chinese zodiac
Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Tuesday, February 1, 2022 CE (in the common Gregorian calendar) will begin the lunisolar Year of the Tiger. The celestial stems have no one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems each belong to one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element's governance is associated with yin, the other with yang. Thus, 2022 is also the yang year of Water. Note that since 12 is an even number, the association between animals and yin/yang doesn't change. Consecutive Years of the Rooster will cycle through the five elements, but will always be yin, despite the apparent conceptual mismatch between the specifically-male English animal name and the female aspect denoted by yin. Task Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year. You may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration). Requisite information The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig. The element cycle runs in this order: Wood, Fire, Earth, Metal, Water. The yang year precedes the yin year within each element. The current 60-year cycle began in 1984 CE; the first cycle of the Common Era began in 4 CE. Thus, 1984 was the year of the Wood Rat (yang), 1985 was the year of the Wood Ox (yin), and 1986 the year of the Fire Tiger (yang); 2022 - which, as already noted, is the year of the Water Tiger (yang) - is the 39th year of the current cycle. Information for optional task The ten celestial stems are 甲 jiă, 乙 yĭ, 丙 bĭng, 丁 dīng, 戊 wù, 己 jĭ, 庚 gēng, 辛 xīn, 壬 rén, and 癸 gŭi. With the ASCII version of Pinyin tones, the names are written "jia3", "yi3", "bing3", "ding1", "wu4", "ji3", "geng1", "xin1", "ren2", and "gui3". The twelve terrestrial branches are 子 zĭ, 丑 chŏu, 寅 yín, 卯 măo, 辰 chén, 巳 sì, 午 wŭ, 未 wèi, 申 shēn, 酉 yŏu, 戌 xū, 亥 hài. In ASCII Pinyin, those are "zi3", "chou3", "yin2", "mao3", "chen2", "si4", "wu3", "wei4", "shen1", "you3", "xu1", and "hai4". Therefore 1984 was 甲子 (jiă-zĭ, or jia3-zi3). 2022 is 壬寅 (rén-yín or ren2-yin2).
#Racket
Racket
#lang racket   (require racket/date)   ; Any CE Year that was the first of a 60-year cycle (define base-year 1984)   (define celestial-stems '("甲" "乙" "丙" "丁" "戊" "己" "庚" "辛" "壬" "癸"))   (define terrestrial-branches '("子" "丑" "寅" "卯" "辰" "巳" "午" "未" "申" "酉" "戌" "亥"))   (define zodiac-animals '("Rat" "Ox" "Tiger" "Rabbit" "Dragon" "Snake" "Horse" "Goat" "Monkey" "Rooster" "Dog" "Pig"))   (define elements '("Wood" "Fire" "Earth" "Metal" "Water"))   (define aspects '("yang" "yin"))   (define pinyin (map cons (append celestial-stems terrestrial-branches) (list "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")))   (define (this-year) (date-year (current-date)))   (define (pinyin-for han) (cdr (assoc han pinyin)))   (define (han/pinyin-nth n hans) (let ((han (list-ref hans n))) (values han (pinyin-for han))))   (define (chinese-zodiac ce-year) (let* ((cycle-year (- ce-year base-year)) (stem-number (modulo cycle-year (length celestial-stems))) (element-number (quotient stem-number 2)) (aspect-number (modulo cycle-year (length aspects))) (branch-number (modulo cycle-year (length terrestrial-branches))) (element (list-ref elements element-number)) (zodiac-animal (list-ref zodiac-animals branch-number)) (aspect (list-ref aspects aspect-number))) (let-values (([stem-han stem-pinyin] (han/pinyin-nth stem-number celestial-stems)) ([branch-han branch-pinyin] (han/pinyin-nth branch-number terrestrial-branches))) (list ce-year stem-han branch-han stem-pinyin branch-pinyin element zodiac-animal aspect))))   (module+ test (for ((ce-year (in-list '(1935 1938 1941 1947 1968 1972 1976)))) (apply printf "~a: ~a~a (~a-~a, ~a ~a; ~a)~%" (chinese-zodiac ce-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).
#Raku
Raku
sub Chinese-zodiac ( Int $year ) { my @heaven = <甲 jiă 乙 yĭ 丙 bĭng 丁 dīng 戊 wù 己 jĭ 庚 gēng 辛 xīn 壬 rén 癸 gŭi>.pairup; my @earth = <子 zĭ 丑 chŏu 寅 yín 卯 măo 辰 chén 巳 sì 午 wŭ 未 wèi 申 shēn 酉 yŏu 戌 xū 亥 hài>.pairup; my @animal = <Rat Ox Tiger Rabbit Dragon Snake Horse Goat Monkey Rooster Dog Pig>; my @element = <Wood Fire Earth Metal Water>; my @aspect = <yang yin>;   my $cycle_year = ($year - 4) % 60; my $i2 = $cycle_year % 2; my $i10 = $cycle_year % 10; my $i12 = $cycle_year % 12;   %( 'Han' => @heaven[$i10].key ~ @earth[$i12].key, 'pinyin' => @heaven[$i10].value ~ @earth[$i12].value, 'heaven' => @heaven[$i10], 'earth' => @earth[$i12], 'element' => @element[$i10 div 2], 'animal' => @animal[$i12], 'aspect' => @aspect[$i2], 'cycle' => $cycle_year + 1 ) }   # TESTING printf "%d: %s (%s, %s %s; %s - year %d in the cycle)\n", $_, .&Chinese-zodiac<Han pinyin element animal aspect cycle> for 1935, 1938, 1968, 1972, 1976, 1984, Date.today.year;
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an unusual filename:   `Abdu'l-Bahá.txt
#Icon_and_Unicon
Icon and Unicon
every dir := !["./","/"] do { write("file ", f := dir || "input.txt", if stat(f) then " exists." else " doesn't exist.") write("directory ", f := dir || "docs", if stat(f) then " exists." else " doesn't exist.") }
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
#Phix
Phix
-- -- demo\rosetta\Chaos_game.exw -- =========================== -- with javascript_semantics include pGUI.e Ihandle dlg, canvas cdCanvas cddbuffer, cdcanvas enum TRI,SQ1,SQ2,SQ3,PENT sequence descs = {"Sierpinsky Triangle", "Square 1", "Square 2", "Square 3", "Pentagon"} integer mode = TRI function redraw_cb(Ihandle /*ih*/, integer /*posx*/, /*posy*/) atom {w,h} = IupGetIntInt(canvas, "DRAWSIZE") atom {x,y} = {w*0.05,h*0.05} {w,h} = {w*0.9,h*0.9} sequence points = iff(mode<SQ1?{{x,y},{x+w/2,y+h},{x+w,y}}: iff(mode<PENT?{{x,y},{x,y+h},{x+w,y+h},{x+w,y}} :{{x+w/6,y},{x,y+h*2/3},{x+w/2,y+h},{x+w,y+h*2/3},{x+w*5/6,y}})) cdCanvasActivate(cddbuffer) integer last = 0 for i=1 to 1000 do integer r = rand(length(points)) if mode=TRI or r!=last then atom {nx,ny} = points[r] {x,y} = {(x+nx)/2,(y+ny)/2} cdCanvasPixel(cddbuffer, x, y, CD_GREY) if mode=SQ2 or mode=SQ3 then r = mod(r,length(points))+1 if mode=SQ3 then r = mod(r,length(points))+1 end if end if last = r end if end for cdCanvasFlush(cddbuffer) IupSetStrAttribute(dlg, "TITLE", "Chaos Game (%s)", {descs[mode]}) return IUP_DEFAULT end function function timer_cb(Ihandle /*ih*/) IupUpdate(canvas) return IUP_IGNORE end function function map_cb(Ihandle ih) cdcanvas = cdCreateCanvas(CD_IUP, ih) cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas) cdCanvasSetBackground(cddbuffer, CD_WHITE) cdCanvasSetForeground(cddbuffer, CD_GRAY) return IUP_DEFAULT end function function key_cb(Ihandle /*ih*/, atom c) if c=K_ESC then return IUP_CLOSE end if if c=' ' then mode += 1 if mode>PENT then mode = TRI end if cdCanvasClear(cddbuffer) IupRedraw(canvas) end if return IUP_CONTINUE end function procedure main() IupOpen() canvas = IupCanvas("RASTERSIZE=640x640") IupSetCallbacks(canvas, {"MAP_CB", Icallback("map_cb"), "ACTION", Icallback("redraw_cb")}) dlg = IupDialog(canvas, `TITLE="Chaos Game"`) IupSetCallback(dlg, "KEY_CB", Icallback("key_cb")) IupShow(dlg) IupSetAttribute(canvas, "RASTERSIZE", NULL) Ihandle timer = IupTimer(Icallback("timer_cb"), 40) if platform()!=JS then IupMainLoop() IupClose() end if end procedure main()
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.
#Rust
Rust
  use std::collections::HashMap; use std::io; use std::io::prelude::*; use std::io::BufReader; use std::net::{TcpListener, TcpStream}; use std::sync::{Arc, RwLock}; use std::thread;   type Username = String;   /// Sends a message to all clients except the sending client. fn broadcast_message( user: &str, clients: &mut HashMap<String, TcpStream>, message: &str, ) -> io::Result<()> { for (client, stream) in clients.iter_mut() { if client != user { writeln!(stream, "{}", message)?; } }   Ok(()) }   fn chat_loop(listener: &TcpListener) -> io::Result<()> { let local_clients: Arc<RwLock<HashMap<Username, TcpStream>>> = Arc::new(RwLock::new(HashMap::new()));   println!("Accepting connections on {}", listener.local_addr()?.port());   for stream in listener.incoming() { match stream { Ok(stream) => { let client_clients = Arc::clone(&local_clients); thread::spawn(move || -> io::Result<()> { let mut reader = BufReader::new(stream.try_clone()?); let mut writer = stream;   let mut name = String::new(); loop { write!(writer, "Please enter a username: ")?; reader.read_line(&mut name)?; name = name.trim().to_owned();   let clients = client_clients.read().unwrap(); if !clients.contains_key(&name) { writeln!(writer, "Welcome, {}!", &name)?; break; }   writeln!(writer, "That username is taken.")?; name.clear(); }   { let mut clients = client_clients.write().unwrap(); clients.insert(name.clone(), writer); broadcast_message( &name, &mut *clients, &format!("{} has joined the chat room.", &name), )?; }   for line in reader.lines() { let mut clients = client_clients.write().unwrap(); broadcast_message(&name, &mut *clients, &format!("{}: {}", &name, line?))?; }   { let mut clients = client_clients.write().unwrap(); clients.remove(&name); broadcast_message( &name, &mut *clients, &format!("{} has left the chat room.", &name), )?; }   Ok(()) }); } Err(e) => { println!("Connection failed: {}", e); } } }   Ok(()) }   fn main() { let listener = TcpListener::bind(("localhost", 7000)).unwrap(); chat_loop(&listener).unwrap(); }  
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.
#FALSE
FALSE
'A." "65,
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.
#Fantom
Fantom
fansh> 97.toChar a fansh> 'a'.toInt 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.
#q
q
solve:{[A;B] $[0h>type A;B%A;inv[A] mmu B]} ak:{[m;k] (),/:m[;k]til k:k-1} akk:{[m;k] m[k;k:k-1]} transpose:{$[0h=type x;flip x;enlist each x]} mult:{[A;B]$[0h=type A;A mmu B;A*B]} cholesky:{[A] {[A;L;n] l_k:solve[L;ak[A;n]]; l_kk:first over sqrt[akk[A;n] - mult[transpose l_k;l_k]]; ({$[0h<type x;enlist x;x]}L,'0f),enlist raze transpose[l_k],l_kk }[A]/[sqrt A[0;0];1_1+til count first A] }   show cholesky (25 15 -5f;15 18 0f;-5 0 11f) -1""; show cholesky (18 22 54 42f;22 70 86 62f;54 86 174 134f;42 62 134 106f)
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
#Oz
Oz
declare %% Lists (immutable, recursive) Xs = [1 2 3 4] %% Add element at the front (cons) Xs0 = 0|Xs {Show {Length Xs}} %% output: 4   %% Records (immutable maps with a label) Rec = label(1:2 symbol:3) {Show Rec} %% output: label(2 symbol:3) {Show Rec.1} %% output: 2 %% create a new record with an added field Rec2 = {AdjoinAt Rec 2 value} {Show Rec2} %% output: label(2 value symbol:3)   %% Dictionaries (mutable maps) Dict = {Dictionary.new} Dict.1 := 1 Dict.symbol := 3 {Show Dict.1} %% output: 1   %% Arrays (mutable with integer keys) Arr = {Array.new 1 10 initValue} Arr.1 := 3 {Show Arr.1} %% output: 3
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
#REXX
REXX
/*REXX program displays combination sets for X things taken Y at a time. */ parse arg x y $ . /*get optional arguments from the C.L. */ if x=='' | x=="," then x= 5 /*No X specified? Then use default.*/ if y=='' | y=="," then y= 3; oy= y; y= abs(y) /* " Y " " " " */ if $=='' | $=="," then $='123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', "~!@#$%^&*()_+`{}|[]\:;<>?,./█┌┐└┘±≥≤≈∙" /*some extended chars*/ /* [↑] No $ specified? Use default.*/ if y>x then do; say y " can't be greater than " x; exit 1; end say "────────────" x ' things taken ' y " at a time:" say "────────────" combN(x,y) ' combinations.' exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ combN: procedure expose $ oy; parse arg x,y; xp= x+1; xm= xp-y;  !.= 0 if x=0 | y=0 then return 'no' do i=1 for y;  !.i= i end /*i*/ do j=1; L= do d=1 for y; L= L substr($, !.d, 1) end /*d*/ if oy>0 then say L;  !.y= !.y + 1 /*don't show if OY<0 */ if !.y==xp then if .combN(y-1) then leave end /*j*/ return j /*──────────────────────────────────────────────────────────────────────────────────────*/ .combN: procedure expose !. y xm; parse arg d; if d==0 then return 1; p= !.d do u=d to y;  !.u= p+1; if !.u==xm+u then return .combN(u-1); p= !.u end /*u*/ /* ↑ */ return 0 /*recursive call──►──────┘ */
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.
#Toka
Toka
100 100 = [ ." True\n" ] ifTrue 100 200 = [ ." True\n" ] ifTrue
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}}} .
#R
R
mul_inv <- function(a, b) { b0 <- b x0 <- 0L x1 <- 1L   if (b == 1) return(1L) while(a > 1){ q <- as.integer(a/b)   t <- b b <- a %% b a <- t   t <- x0 x0 <- x1 - q*x0 x1 <- t }   if (x1 < 0) x1 <- x1 + b0 return(x1) }   chinese_remainder <- function(n, a) { len <- length(n)   prod <- 1L sum <- 0L   for (i in 1:len) prod <- prod * n[i]   for (i in 1:len){ p <- as.integer(prod / n[i]) sum <- sum + a[i] * mul_inv(p, n[i]) * p }   return(sum %% prod) }   n <- c(3L, 5L, 7L) a <- c(2L, 3L, 2L)   chinese_remainder(n, a)
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.
#PicoLisp
PicoLisp
(class +Rectangle) # dx dy   (dm area> () # Define a a method that calculates the rectangle's area (* (: dx) (: dy)) )   (println # Create a rectangle, and print its area (area> (new '(+Rectangle) 'dx 3 'dy 4)) )
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.
#Pop11
Pop11
uses objectclass; define :class MyClass; slot value = 1; enddefine;
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)
#Run_BASIC
Run BASIC
n =10 ' 10 data points input dim x(n) dim y(n)   pt1 = 0 ' 1st point pt2 = 0 ' 2nd point   for i =1 to n ' read in data read x(i) read y(i) next i   minDist = 1000000   for i =1 to n -1 for j =i +1 to n distXsq =(x(i) -x(j))^2 disYsq =(y(i) -y(j))^2 d =abs((dxSq +disYsq)^0.5) if d <minDist then minDist =d pt1 =i pt2 =j end if next j next i   print "Distance ="; minDist; " between ("; x(pt1); ", "; y(pt1); ") and ("; x(pt2); ", "; y(pt2); ")"   end   data 0.654682, 0.925557 data 0.409382, 0.619391 data 0.891663, 0.888594 data 0.716629, 0.996200 data 0.477721, 0.946355 data 0.925092, 0.818220 data 0.624291, 0.142924 data 0.211332, 0.221507 data 0.293786, 0.691701 data 0.839186, 0.72826
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
#Perl
Perl
use strict;   sub circles { my ($x1, $y1, $x2, $y2, $r) = @_;   return "Radius is zero" if $r == 0; return "Coincident points gives infinite number of circles" if $x1 == $x2 and $y1 == $y2;   # delta x, delta y between points my ($dx, $dy) = ($x2 - $x1, $y2 - $y1); my $q = sqrt($dx**2 + $dy**2); return "Separation of points greater than diameter" if $q > 2*$r;   # halfway point my ($x3, $y3) = (($x1 + $x2) / 2, ($y1 + $y2) / 2); # distance along the mirror line my $d = sqrt($r**2-($q/2)**2);   # pair of solutions sprintf '(%.4f, %.4f) and (%.4f, %.4f)', $x3 - $d*$dy/$q, $y3 + $d*$dx/$q, $x3 + $d*$dy/$q, $y3 - $d*$dx/$q; }   my @arr = ( [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] );   printf "(%.4f, %.4f) and (%.4f, %.4f) with radius %.1f: %s\n", @$_[0..4], circles @$_ for @arr;
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).
#Ring
Ring
  yinyang = ["yang", "yin"] elements = ["Wood", "Fire", "Earth", "Metal", "Water"] animals = ["Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"] years = [1801, 1861, 1984, 2020, 2186, 76543] output = ""   for year in years yy = year % 2 + 1 element = (year - 4) % 5 + 1 animal = (year - 4) % 12 + 1 output = string(year) + " is the year of the " output += elements[element] + " " + animals[animal] + " (" + yinyang[yy] + ")."  ? output next  
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).
#Ruby
Ruby
# encoding: utf-8 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 = %w(甲 乙 丙 丁 戊 己 庚 辛 壬 癸) terrestrial = %w(子 丑 寅 卯 辰 巳 午 未 申 酉 戌 亥) animals = %w(Rat Ox Tiger Rabbit Dragon Snake Horse Goat Monkey Rooster Dog Pig) elements = %w(Wood Fire Earth Metal Water) aspects = %w(yang yin)   BASE = 4   args = if !ARGV.empty? ARGV else [Time.new.year] end   args.each do |arg| ce_year = Integer(arg) print "#{ce_year}: " if ARGV.length > 1 cycle_year = ce_year - BASE   stem_number = cycle_year % 10 stem_han = celestial[stem_number] stem_pinyin = pinyin[stem_han]   element_number = 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   print stem_han, branch_han puts " (#{stem_pinyin}-#{branch_pinyin}, #{element} #{animal}; #{aspect} - year #{index} of the cycle)" 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
#IDL
IDL
  print, FILE_TEST('input.txt') print, FILE_TEST(PATH_SEP()+'input.txt') print, FILE_TEST('docs', /DIRECTORY) print, FILE_TEST(PATH_SEP()+'docs', /DIRECTORY)    
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
#J
J
require 'files' fexist 'input.txt' fexist '/input.txt' direxist=: 2 = ftype direxist 'docs' direxist '/docs'
http://rosettacode.org/wiki/Chaos_game
Chaos game
The Chaos Game is a method of generating the attractor of an iterated function system (IFS). One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random. Task Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a starting point at random (preferably inside the triangle).   Then add the next point halfway between the starting point and one of the reference points.   This reference point is chosen at random. After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge. See also The Game of Chaos
#Plain_English
Plain English
To run: Start up. Initialize our reference points. Clear the screen to the lightest gray color. Play the chaos game. Refresh the screen. Wait for the escape key. Shut down.   To play the chaos game: Pick a spot within 2 inches of the screen's center. Loop. Draw the spot. If a counter is past 20000, exit. Pick a reference spot. Find a middle spot of the spot and the reference spot. Put the middle spot into the spot. Repeat.   To find a middle spot of a spot and another spot: Put the spot's x coord plus the other spot's x coord divided by 2 into the middle spot's x coord. Put the spot's y coord plus the other spot's y coord divided by 2 into the middle spot's y coord.   The top spot is a spot. The left spot is a spot. The right spot is a spot.   To initialize our reference points: Move up 2-1/2 inches. Put the context's spot into the top spot. Turn right. Turn 1/6 of the way around. Move 5 inches. Put the context's spot into the right spot. Turn 1/3 of the way around. Move 5 inches. Put the context's spot into the left spot.   To pick a reference spot: Pick a number between 1 and 3. If the number is 1, put the top spot into the reference spot. If the number is 2, put the right spot into the reference spot. If the number is 3, put the left spot into the reference spot.
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
#Processing
Processing
size(300, 260);   background(#ffffff); // white   int x = floor(random(width)); int y = floor(random(height));   int colour = #ffffff;   for (int i=0; i<30000; i++) { int v = floor(random(3)); switch (v) { case 0: x = x / 2; y = y / 2; colour = #00ff00; // green break; case 1: x = width/2 + (width/2 - x)/2; y = height - (height - y)/2; colour = #ff0000; // red break; case 2: x = width - (width - x)/2; y = y / 2; colour = #0000ff; // blue } set(x, height-y, colour); }
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.
#Tcl
Tcl
package require Tcl 8.6   # Write a message to everyone except the sender of the message proc writeEveryoneElse {sender message} { dict for {who ch} $::cmap { if {$who ne $sender} { puts $ch $message } } }   # How to read a line (up to 256 chars long) in a coroutine proc cgets {ch var} { upvar 1 $var v while {[gets $ch v] < 0} { if {[eof $ch] || [chan pending input $ch] > 256} { return false } yield } return true }   # The chatting, as seen by one user proc chat {ch addr port} { ### CONNECTION CODE ### #Log "connection from ${addr}:${port} on channel $ch" fconfigure $ch -buffering none -blocking 0 -encoding utf-8 fileevent $ch readable [info coroutine] global cmap try {   ### GET THE NICKNAME OF THE USER ### puts -nonewline $ch "Please enter your name: " if {![cgets $ch name]} { return } #Log "Mapping ${addr}:${port} to ${name} on channel $ch" dict set cmap $name $ch writeEveryoneElse $name "+++ $name arrived +++"   ### MAIN CHAT LOOP ### while {[cgets $ch line]} { writeEveryoneElse $name "$name> $line" }   } finally { ### DISCONNECTION CODE ### if {[info exists name]} { writeEveryoneElse $name "--- $name left ---" dict unset cmap $name } close $ch #Log "disconnection from ${addr}:${port} on channel $ch" } }   # Service the socket by making corouines running [chat] socket -server {coroutine c[incr count] chat} 4004 set ::cmap {}; # Dictionary mapping nicks to channels vwait forever; # Run event loop
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.
#Forth
Forth
char a dup . \ 97 emit \ 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.
#Fortran
Fortran
WRITE(*,*) ACHAR(97), IACHAR("a") WRITE(*,*) CHAR(97), ICHAR("a")
http://rosettacode.org/wiki/Cholesky_decomposition
Cholesky decomposition
Every symmetric, positive definite matrix A can be decomposed into a product of a unique lower triangular matrix L and its transpose: A = L L T {\displaystyle A=LL^{T}} L {\displaystyle L} is called the Cholesky factor of A {\displaystyle A} , and can be interpreted as a generalized square root of A {\displaystyle A} , as described in Cholesky decomposition. In a 3x3 example, we have to solve the following system of equations: A = ( a 11 a 21 a 31 a 21 a 22 a 32 a 31 a 32 a 33 ) = ( l 11 0 0 l 21 l 22 0 l 31 l 32 l 33 ) ( l 11 l 21 l 31 0 l 22 l 32 0 0 l 33 ) ≡ L L T = ( l 11 2 l 21 l 11 l 31 l 11 l 21 l 11 l 21 2 + l 22 2 l 31 l 21 + l 32 l 22 l 31 l 11 l 31 l 21 + l 32 l 22 l 31 2 + l 32 2 + l 33 2 ) {\displaystyle {\begin{aligned}A&={\begin{pmatrix}a_{11}&a_{21}&a_{31}\\a_{21}&a_{22}&a_{32}\\a_{31}&a_{32}&a_{33}\\\end{pmatrix}}\\&={\begin{pmatrix}l_{11}&0&0\\l_{21}&l_{22}&0\\l_{31}&l_{32}&l_{33}\\\end{pmatrix}}{\begin{pmatrix}l_{11}&l_{21}&l_{31}\\0&l_{22}&l_{32}\\0&0&l_{33}\end{pmatrix}}\equiv LL^{T}\\&={\begin{pmatrix}l_{11}^{2}&l_{21}l_{11}&l_{31}l_{11}\\l_{21}l_{11}&l_{21}^{2}+l_{22}^{2}&l_{31}l_{21}+l_{32}l_{22}\\l_{31}l_{11}&l_{31}l_{21}+l_{32}l_{22}&l_{31}^{2}+l_{32}^{2}+l_{33}^{2}\end{pmatrix}}\end{aligned}}} We can see that for the diagonal elements ( l k k {\displaystyle l_{kk}} ) of L {\displaystyle L} there is a calculation pattern: l 11 = a 11 {\displaystyle l_{11}={\sqrt {a_{11}}}} l 22 = a 22 − l 21 2 {\displaystyle l_{22}={\sqrt {a_{22}-l_{21}^{2}}}} l 33 = a 33 − ( l 31 2 + l 32 2 ) {\displaystyle l_{33}={\sqrt {a_{33}-(l_{31}^{2}+l_{32}^{2})}}} or in general: l k k = a k k − ∑ j = 1 k − 1 l k j 2 {\displaystyle l_{kk}={\sqrt {a_{kk}-\sum _{j=1}^{k-1}l_{kj}^{2}}}} For the elements below the diagonal ( l i k {\displaystyle l_{ik}} , where i > k {\displaystyle i>k} ) there is also a calculation pattern: l 21 = 1 l 11 a 21 {\displaystyle l_{21}={\frac {1}{l_{11}}}a_{21}} l 31 = 1 l 11 a 31 {\displaystyle l_{31}={\frac {1}{l_{11}}}a_{31}} l 32 = 1 l 22 ( a 32 − l 31 l 21 ) {\displaystyle l_{32}={\frac {1}{l_{22}}}(a_{32}-l_{31}l_{21})} which can also be expressed in a general formula: l i k = 1 l k k ( a i k − ∑ j = 1 k − 1 l i j l k j ) {\displaystyle l_{ik}={\frac {1}{l_{kk}}}\left(a_{ik}-\sum _{j=1}^{k-1}l_{ij}l_{kj}\right)} Task description The task is to implement a routine which will return a lower Cholesky factor L {\displaystyle L} for every given symmetric, positive definite nxn matrix A {\displaystyle A} . You should then test it on the following two examples and include your output. Example 1: 25 15 -5 5 0 0 15 18 0 --> 3 3 0 -5 0 11 -1 1 3 Example 2: 18 22 54 42 4.24264 0.00000 0.00000 0.00000 22 70 86 62 --> 5.18545 6.56591 0.00000 0.00000 54 86 174 134 12.72792 3.04604 1.64974 0.00000 42 62 134 106 9.89949 1.62455 1.84971 1.39262 Note The Cholesky decomposition of a Pascal upper-triangle matrix is the Identity matrix of the same size. The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
#R
R
t(chol(matrix(c(25, 15, -5, 15, 18, 0, -5, 0, 11), nrow=3, ncol=3))) # [,1] [,2] [,3] # [1,] 5 0 0 # [2,] 3 3 0 # [3,] -1 1 3   t(chol(matrix(c(18, 22, 54, 42, 22, 70, 86, 62, 54, 86, 174, 134, 42, 62, 134, 106), nrow=4, ncol=4))) # [,1] [,2] [,3] [,4] # [1,] 4.242641 0.000000 0.000000 0.000000 # [2,] 5.185450 6.565905 0.000000 0.000000 # [3,] 12.727922 3.046038 1.649742 0.000000 # [4,] 9.899495 1.624554 1.849711 1.392621
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.
#Racket
Racket
  #lang racket (require math)   (define (cholesky A) (define mref matrix-ref) (define n (matrix-num-rows A)) (define L (for/vector ([_ n]) (for/vector ([_ n]) 0))) (define (set L i j x) (vector-set! (vector-ref L i) j x)) (define (ref L i j) (vector-ref (vector-ref L i) j)) (for* ([i n] [k n]) (set L i k (cond [(= i k) (sqrt (- (mref A i i) (for/sum ([j k]) (sqr (ref L k j)))))] [(> i k) (/ (- (mref A i k) (for/sum ([j k]) (* (ref L i j) (ref L k j)))) (ref L k k))] [else 0]))) L)   (cholesky (matrix [[25 15 -5] [15 18 0] [-5 0 11]]))   (cholesky (matrix [[18 22 54 42] [22 70 86 62] [54 86 174 134] [42 62 134 106]]))  
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
#PARI.2FGP
PARI/GP
v = vector(0); v = []; cv = vectorv(0); cv = []~; m = matrix(1,1); s = Set(v); l = List(v); vs = vectorsmall(0); M = Map()
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
#Ring
Ring
  # Project : Combinations   n = 5 k = 3 temp = [] comb = [] num = com(n, k) while true temp = [] for n = 1 to 3 tm = random(4) + 1 add(temp, tm) next bool1 = (temp[1] = temp[2]) and (temp[1] = temp[3]) and (temp[2] = temp[3]) bool2 = (temp[1] < temp[2]) and (temp[2] < temp[3]) if not bool1 and bool2 add(comb, temp) ok for p = 1 to len(comb) - 1 for q = p + 1 to len(comb) if (comb[p][1] = comb[q][1]) and (comb[p][2] = comb[q][2]) and (comb[p][3] = comb[q][3]) del(comb, p) ok next next if len(comb) = num exit ok end comb = sortfirst(comb, 1) see showarray(comb) + nl   func com(n, k) res1 = 1 for n1 = n - k + 1 to n res1 = res1 * n1 next res2 = 1 for n2 = 1 to k res2 = res2 * n2 next res3 = res1/res2 return res3   func showarray(vect) svect = "" for nrs = 1 to len(vect) svect = "[" + vect[nrs][1] + " " + vect[nrs][2] + " " + vect[nrs][3] + "]" + nl see svect next   Func sortfirst(alist, ind) aList = sort(aList,ind) for n = 1 to len(alist)-1 for m= n + 1 to len(aList) if alist[n][1] = alist[m][1] and alist[m][2] < alist[n][2] temp = alist[n] alist[n] = alist[m] alist[m] = temp ok next next for n = 1 to len(alist)-1 for m= n + 1 to len(aList) if alist[n][1] = alist[m][1] and alist[n][2] = alist[m][2] and alist[m][3] < alist[n][3] temp = alist[n] alist[n] = alist[m] alist[m] = temp ok next next return aList  
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.
#TorqueScript
TorqueScript
// numbers and objects if(%num == 1) { foo(); } else if(%obj == MyObject.getID()) { bar(); } else { deusEx(); }   // strings if(%str $= "Hello World") { foo(); } else if(%str $= "Bye World") { bar(); } else { deusEx(); }
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}}} .
#Racket
Racket
#lang racket (require (only-in math/number-theory solve-chinese)) (define as '(2 3 2)) (define ns '(3 5 7)) (solve-chinese as ns)
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}}} .
#Raku
Raku
# returns x where (a * x) % b == 1 sub mul-inv($a is copy, $b is copy) { return 1 if $b == 1; my ($b0, @x) = $b, 0, 1; ($a, $b, @x) = ( $b, $a % $b, @x[1] - ($a div $b)*@x[0], @x[0] ) while $a > 1; @x[1] += $b0 if @x[1] < 0; return @x[1]; }   sub chinese-remainder(*@n) { my \N = [*] @n; -> *@a { N R% [+] map { my \p = N div @n[$_]; @a[$_] * mul-inv(p, @n[$_]) * p }, ^@n } }   say chinese-remainder(3, 5, 7)(2, 3, 2);
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.
#Portugol
Portugol
  programa { inclua biblioteca Objetos --> obj   // "constructor" returns address of object funcao inteiro my_class_new(inteiro value) { inteiro this = obj.criar_objeto() obj.atribuir_propriedade(this, "variable", value) // add property to object retorne this }   // "method" takes the address returned by criar_objeto funcao my_class_some_method(inteiro this) { my_class_set_variable(this, 1) }   // "setter" funcao my_class_set_variable(inteiro this, inteiro value) { obj.atribuir_propriedade(this, "variable", value) }   // "getter" funcao inteiro my_class_get_variable(inteiro this) { retorne obj.obter_propriedade_tipo_inteiro(this, "variable") }   funcao inicio() { inteiro this = my_class_new(0)   escreva("variable = ", my_class_get_variable(this), "\n")   my_class_some_method(this)   escreva("variable = ", my_class_get_variable(this), "\n")   my_class_set_variable(this, 99)   escreva("variable = ", my_class_get_variable(this), "\n")   obj.liberar_objeto(this) } }    
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.
#PowerShell
PowerShell
  Add-Type -Language CSharp -TypeDefinition @' public class MyClass { public MyClass() { } public void SomeMethod() { } private int _variable; public int Variable { get { return _variable; } set { _variable = value; } } public static void Main() { // instantiate it MyClass instance = new MyClass(); // invoke the method instance.SomeMethod(); // set the variable instance.Variable = 99; // get the variable System.Console.WriteLine( "Variable=" + instance.Variable.ToString() ); } } '@  
http://rosettacode.org/wiki/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)
#Rust
Rust
  //! We interpret complex numbers as points in the Cartesian plane, here. We also use the //! [sweepline/plane sweep closest pairs algorithm][algorithm] instead of the divide-and-conquer //! algorithm, since it's (arguably) easier to implement, and an efficient implementation does not //! require use of unsafe. //! //! [algorithm]: http://www.cs.mcgill.ca/~cs251/ClosestPair/ClosestPairPS.html extern crate num;   use num::complex::Complex; use std::cmp::{Ordering, PartialOrd}; use std::collections::BTreeSet; type Point = Complex<f32>;   /// Wrapper around `Point` (i.e. `Complex<f32>`) so that we can use a `TreeSet` #[derive(PartialEq)] struct YSortedPoint { point: Point, }   impl PartialOrd for YSortedPoint { fn partial_cmp(&self, other: &YSortedPoint) -> Option<Ordering> { (self.point.im, self.point.re).partial_cmp(&(other.point.im, other.point.re)) } }   impl Ord for YSortedPoint { fn cmp(&self, other: &YSortedPoint) -> Ordering { self.partial_cmp(other).unwrap() } }   impl Eq for YSortedPoint {}   fn closest_pair(points: &mut [Point]) -> Option<(Point, Point)> { if points.len() < 2 { return None; }   points.sort_by(|a, b| (a.re, a.im).partial_cmp(&(b.re, b.im)).unwrap());   let mut closest_pair = (points[0], points[1]); let mut closest_distance_sqr = (points[0] - points[1]).norm_sqr(); let mut closest_distance = closest_distance_sqr.sqrt();   // the strip that we inspect for closest pairs as we sweep right let mut strip: BTreeSet<YSortedPoint> = BTreeSet::new(); strip.insert(YSortedPoint { point: points[0] }); strip.insert(YSortedPoint { point: points[1] });   // index of the leftmost point on the strip (on points) let mut leftmost_idx = 0;   // Start the sweep! for (idx, point) in points.iter().enumerate().skip(2) { // Remove all points farther than `closest_distance` away from `point` // along the x-axis while leftmost_idx < idx { let leftmost_point = &points[leftmost_idx]; if (leftmost_point.re - point.re).powi(2) < closest_distance_sqr { break; } strip.remove(&YSortedPoint { point: *leftmost_point, }); leftmost_idx += 1; }   // Compare to points in bounding box { let low_bound = YSortedPoint { point: Point { re: ::std::f32::INFINITY, im: point.im - closest_distance, }, }; let mut strip_iter = strip.iter().skip_while(|&p| p < &low_bound); loop { let point2 = match strip_iter.next() { None => break, Some(p) => p.point, }; if point2.im - point.im >= closest_distance { // we've reached the end of the box break; } let dist_sqr = (*point - point2).norm_sqr(); if dist_sqr < closest_distance_sqr { closest_pair = (point2, *point); closest_distance_sqr = dist_sqr; closest_distance = dist_sqr.sqrt(); } } }   // Insert point into strip strip.insert(YSortedPoint { point: *point }); }   Some(closest_pair) }   pub fn main() { let mut test_data = [ Complex::new(0.654682, 0.925557), Complex::new(0.409382, 0.619391), Complex::new(0.891663, 0.888594), Complex::new(0.716629, 0.996200), Complex::new(0.477721, 0.946355), Complex::new(0.925092, 0.818220), Complex::new(0.624291, 0.142924), Complex::new(0.211332, 0.221507), Complex::new(0.293786, 0.691701), Complex::new(0.839186, 0.728260), ]; let (p1, p2) = closest_pair(&mut test_data[..]).unwrap(); println!("Closest pair: {} and {}", p1, p2); println!("Distance: {}", (p1 - p2).norm_sqr().sqrt()); }  
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
#Phix
Phix
with javascript_semantics constant tests = {{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 i=1 to length(tests) do atom {x1,y1,x2,y2,r} = tests[i], xd = x2-x1, yd = y1-y2, s2 = xd*xd+yd*yd, sep = sqrt(s2), xh = (x1+x2)/2, yh = (y1+y2)/2 string txt if sep=0 then txt = "same points/"&iff(r=0?"radius is zero":"infinite solutions") elsif sep=2*r then txt = sprintf("opposite ends of diameter with centre {%.4f,%.4f}",{xh,yh}) elsif sep>2*r then txt = sprintf("too far apart (%.4f > %.4f)",{sep,2*r}) else atom md = sqrt(r*r-s2/4), xs = md*xd/sep, ys = md*yd/sep txt = sprintf("{%.4f,%.4f} and {%.4f,%.4f}",{xh+ys,yh+xs,xh-ys,yh-xs}) end if printf(1,"points {%.4f,%.4f}, {%.4f,%.4f} with radius %.1f ==> %s\n",{x1,y1,x2,y2,r,txt}) end for
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).
#Rust
Rust
fn chinese_zodiac(year: usize) -> String { static ANIMALS: [&str; 12] = [ "Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig", ]; static ASPECTS: [&str; 2] = ["Yang", "Yin"]; static ELEMENTS: [&str; 5] = ["Wood", "Fire", "Earth", "Metal", "Water"]; static STEMS: [char; 10] = [ '甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸', ]; static BRANCHES: [char; 12] = [ '子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥', ]; static S_NAMES: [&str; 10] = [ "jiă", "yĭ", "bĭng", "dīng", "wù", "jĭ", "gēng", "xīn", "rén", "gŭi", ]; static B_NAMES: [&str; 12] = [ "zĭ", "chŏu", "yín", "măo", "chén", "sì", "wŭ", "wèi", "shēn", "yŏu", "xū", "hài", ];   let y = year - 4; let s = y % 10; let b = y % 12;   let stem = STEMS[s]; let branch = BRANCHES[b]; let s_name = S_NAMES[s]; let b_name = B_NAMES[b]; let element = ELEMENTS[s / 2]; let animal = ANIMALS[b]; let aspect = ASPECTS[s % 2]; let cycle = y % 60 + 1;   format!( "{} {}{} {:9} {:7} {:7} {:6} {:02}/60", year, stem, branch, format!("{}-{}", s_name, b_name), element, animal, aspect, cycle ) }   fn main() { let years = [1935, 1938, 1968, 1972, 1976, 1984, 2017]; println!("Year Chinese Pinyin Element Animal Aspect Cycle"); println!("---- ------- --------- ------- ------- ------ -----"); for &year in &years { println!("{}", chinese_zodiac(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).
#Scala
Scala
object Zodiac extends App { val years = Seq(1935, 1938, 1968, 1972, 1976, 1984, 1985, 2017, 2018)   private def animals = Seq("Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig")   private def animalChars = Seq("子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥")   private def elements = Seq("Wood", "Fire", "Earth", "Metal", "Water")   private def elementChars = Seq(Array("甲", "丙", "戊", "庚", "壬"), Array("乙", "丁", "己", "辛", "癸"))   private def getYY(year: Int) = if (year % 2 == 0) "yang" else "yin"   for (year <- years) { println(year + " is the year of the " + elements(math.floor((year - 4) % 10 / 2).toInt) + " " + animals((year - 4) % 12) + " (" + getYY(year) + "). " + elementChars(year % 2)(math.floor((year - 4) % 10 / 2).toInt) + animalChars((year - 4) % 12)) } }
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
#Java
Java
import java.io.File; public class FileExistsTest { public static boolean isFileExists(String filename) { boolean exists = new File(filename).exists(); return exists; } public static void test(String type, String filename) { System.out.println("The following " + type + " called " + filename + (isFileExists(filename) ? " exists." : " not exists.") ); } public static void main(String args[]) { test("file", "input.txt"); test("file", File.separator + "input.txt"); test("directory", "docs"); test("directory", File.separator + "docs" + File.separator); } }
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
#Python
Python
  import argparse import random import shapely.geometry as geometry import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation     def main(args): # Styles plt.style.use("ggplot")   # Creating figure fig = plt.figure() line, = plt.plot([], [], ".")   # Limit axes plt.xlim(0, 1) plt.ylim(0, 1)   # Titles title = "Chaos Game" plt.title(title) fig.canvas.set_window_title(title)   # Getting data data = get_data(args.frames)   # Creating animation line_ani = animation.FuncAnimation( fig=fig, func=update_line, frames=args.frames, fargs=(data, line), interval=args.interval, repeat=False )   # To save the animation install ffmpeg and uncomment # line_ani.save("chaos_game.gif")   plt.show()     def get_data(n): """ Get data to plot """ leg = 1 triangle = get_triangle(leg) cur_point = gen_point_within_poly(triangle) data = [] for _ in range(n): data.append((cur_point.x, cur_point.y)) cur_point = next_point(triangle, cur_point) return data     def get_triangle(n): """ Create right triangle """ ax = ay = 0.0 a = ax, ay   bx = 0.5 * n by = 0.75 * (n ** 2) b = bx, by   cx = n cy = 0.0 c = cx, cy   triangle = geometry.Polygon([a, b, c]) return triangle     def gen_point_within_poly(poly): """ Generate random point inside given polygon """ minx, miny, maxx, maxy = poly.bounds while True: x = random.uniform(minx, maxx) y = random.uniform(miny, maxy) point = geometry.Point(x, y) if point.within(poly): return point     def next_point(poly, point): """ Generate next point according to chaos game rules """ vertices = poly.boundary.coords[:-1] # Last point is the same as the first one random_vertex = geometry.Point(random.choice(vertices)) line = geometry.linestring.LineString([point, random_vertex]) return line.centroid     def update_line(num, data, line): """ Update line with new points """ new_data = zip(*data[:num]) or [(), ()] line.set_data(new_data) return line,     if __name__ == "__main__": arg_parser = argparse.ArgumentParser(description="Chaos Game by Suenweek (c) 2017") arg_parser.add_argument("-f", dest="frames", type=int, default=1000) arg_parser.add_argument("-i", dest="interval", type=int, default=10)   main(arg_parser.parse_args())    
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.
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Net.Sockets Imports System.Text Imports System.Threading   Module Module1   Class State Private ReadOnly client As TcpClient Private ReadOnly sb As New StringBuilder   Public Sub New(name As String, client As TcpClient) Me.Name = name Me.client = client End Sub   Public ReadOnly Property Name As String   Public Sub Send(text As String) Dim bytes = Encoding.ASCII.GetBytes(String.Format("{0}" & vbCrLf, text)) client.GetStream().Write(bytes, 0, bytes.Length) End Sub End Class   ReadOnly connections As New Dictionary(Of Integer, State) Dim listen As TcpListener Dim serverThread As Thread   Sub Main() listen = New TcpListener(Net.IPAddress.Parse("127.0.0.1"), 4004) serverThread = New Thread(New ThreadStart(AddressOf DoListen)) serverThread.Start() End Sub   Private Sub DoListen() listen.Start() Console.WriteLine("Server: Started server")   Do Console.Write("Server: Waiting...") Dim client = listen.AcceptTcpClient() Console.WriteLine(" Connected")   ' New thread with client Dim clientThread As New Thread(New ParameterizedThreadStart(AddressOf DoClient))   clientThread.Start(client) Loop End Sub   Private Sub DoClient(client As TcpClient) Console.WriteLine("Client (Thread: {0}): Connected!", Thread.CurrentThread.ManagedThreadId) Dim bytes = Encoding.ASCII.GetBytes("Enter name: ") client.GetStream().Write(bytes, 0, bytes.Length)   Dim done As Boolean Dim name As String Do If Not client.Connected Then Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId) client.Close() Thread.CurrentThread.Abort() ' Kill thread End If   name = Receive(client) done = True   For Each cl In connections Dim state = cl.Value If state.Name = name Then bytes = Encoding.ASCII.GetBytes("Name already registered. Please enter your name: ") client.GetStream().Write(bytes, 0, bytes.Length) done = False End If Next Loop While Not done   connections.Add(Thread.CurrentThread.ManagedThreadId, New State(name, client)) Console.WriteLine(vbTab & "Total connections: {0}", connections.Count) Broadcast(String.Format("+++ {0} arrived +++", name))   Do Dim text = Receive(client) If text = "/quit" Then Broadcast(String.Format("Connection from {0} closed.", name)) connections.Remove(Thread.CurrentThread.ManagedThreadId) Console.WriteLine(vbTab & "Total connections: {0}", connections.Count) Exit Do End If   If Not client.Connected Then Exit Do End If   Broadcast(String.Format("{0}> {1}", name, text)) Loop   Console.WriteLine("Client (Thread: {0}): Terminated!", Thread.CurrentThread.ManagedThreadId) client.Close() Thread.CurrentThread.Abort() End Sub   Private Function Receive(client As TcpClient) As String Dim sb As New StringBuilder Do If client.Available > 0 Then While client.Available > 0 Dim ch = Chr(client.GetStream.ReadByte()) If ch = vbCr Then ' ignore Continue While End If If ch = vbLf Then Return sb.ToString() End If sb.Append(ch) End While   ' pause Thread.Sleep(100) End If Loop End Function   Private Sub Broadcast(text As String) Console.WriteLine(text) For Each client In connections If client.Key <> Thread.CurrentThread.ManagedThreadId Then Dim state = client.Value state.Send(text) End If 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.
#Free_Pascal
Free Pascal
  ' FreeBASIC v1.05.0 win64 Print "a - > "; Asc("a") Print "98 -> "; Chr(98) Print Print "Press any key to exit the program" Sleep End  
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.
#FreeBASIC
FreeBASIC
  ' FreeBASIC v1.05.0 win64 Print "a - > "; Asc("a") Print "98 -> "; Chr(98) Print Print "Press any key to exit the program" Sleep 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.
#Raku
Raku
sub cholesky(@A) { my @L = @A »*» 0; for ^@A -> $i { for 0..$i -> $j { @L[$i][$j] = ($i == $j ?? &sqrt !! 1/@L[$j][$j] * * )( @A[$i][$j] - [+] (@L[$i;*] Z* @L[$j;*])[^$j] ); } } return @L; } .say for cholesky [ [25], [15, 18], [-5, 0, 11], ];   .say for cholesky [ [18, 22, 54, 42], [22, 70, 86, 62], [54, 86, 174, 134], [42, 62, 134, 106], ];
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
#Pascal
Pascal
var MyArray: array[1..5] of real; begin MyArray[1] := 4.35; end;
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
#Ruby
Ruby
def comb(m, n) (0...n).to_a.combination(m).to_a end   comb(3, 5) # => [[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]]