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.
#E
E
def makeColor(name :String) { def color { to colorize(thing :String) { return `$name $thing` } } return color }
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.
#EchoLisp
EchoLisp
  (lib 'gloops) ; load oo library   (define-class Person null (name (age :initform 66))) (define-method tostring (Person) (lambda (p) ( format "🚶 %a " p.name))) (define-method mailto (Person Person) (lambda( p o) (printf "From %a to️  %a : ..." p o)))   ;; define a sub-class of Person with same methods (define-class Writer (Person) (books)) (define-method tostring (Writer) (lambda (w)( format "🎩 %a" w.name))) (define-method mailto (Person Writer) (lambda (p w) (printf " From %a (age %d). Dear writer of %a ..." p p.age w.books )))    
http://rosettacode.org/wiki/Cistercian_numerals
Cistercian numerals
Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999. How they work All Cistercian numerals begin with a vertical line segment, which by itself represents the number 0. Then, glyphs representing the digits 1 through 9 are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number: The upper-right quadrant represents the ones place. The upper-left quadrant represents the tens place. The lower-right quadrant represents the hundreds place. The lower-left quadrant represents the thousands place. Please consult the following image for examples of Cistercian numerals showing each glyph: [1] Task Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile). Use the routine to show the following Cistercian numerals: 0 1 20 300 4000 5555 6789 And a number of your choice! Notes Due to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed — especially for text output. See also Numberphile - The Forgotten Number System dcode.fr - Online Cistercian numeral converter
#Ruby
Ruby
def initN n = Array.new(15){Array.new(11, ' ')} for i in 1..15 n[i - 1][5] = 'x' end return n end   def horiz(n, c1, c2, r) for c in c1..c2 n[r][c] = 'x' end end   def verti(n, r1, r2, c) for r in r1..r2 n[r][c] = 'x' end end   def diagd(n, c1, c2, r) for c in c1..c2 n[r+c-c1][c] = 'x' end end   def diagu(n, c1, c2, r) for c in c1..c2 n[r-c+c1][c] = 'x' end end   def initDraw draw = []   draw[1] = lambda do |n| horiz(n, 6, 10, 0) end draw[2] = lambda do |n| horiz(n, 6, 10, 4) end draw[3] = lambda do |n| diagd(n, 6, 10, 0) end draw[4] = lambda do |n| diagu(n, 6, 10, 4) end draw[5] = lambda do |n| draw[1].call(n) draw[4].call(n) end draw[6] = lambda do |n| verti(n, 0, 4, 10) end draw[7] = lambda do |n| draw[1].call(n) draw[6].call(n) end draw[8] = lambda do |n| draw[2].call(n) draw[6].call(n) end draw[9] = lambda do |n| draw[1].call(n) draw[8].call(n) end   draw[10] = lambda do |n| horiz(n, 0, 4, 0) end draw[20] = lambda do |n| horiz(n, 0, 4, 4) end draw[30] = lambda do |n| diagu(n, 0, 4, 4) end draw[40] = lambda do |n| diagd(n, 0, 4, 0) end draw[50] = lambda do |n| draw[10].call(n) draw[40].call(n) end draw[60] = lambda do |n| verti(n, 0, 4, 0) end draw[70] = lambda do |n| draw[10].call(n) draw[60].call(n) end draw[80] = lambda do |n| draw[20].call(n) draw[60].call(n) end draw[90] = lambda do |n| draw[10].call(n) draw[80].call(n) end   draw[100] = lambda do |n| horiz(n, 6, 10, 14) end draw[200] = lambda do |n| horiz(n, 6, 10, 10) end draw[300] = lambda do |n| diagu(n, 6, 10, 14) end draw[400] = lambda do |n| diagd(n, 6, 10, 10) end draw[500] = lambda do |n| draw[100].call(n) draw[400].call(n) end draw[600] = lambda do |n| verti(n, 10, 14, 10) end draw[700] = lambda do |n| draw[100].call(n) draw[600].call(n) end draw[800] = lambda do |n| draw[200].call(n) draw[600].call(n) end draw[900] = lambda do |n| draw[100].call(n) draw[800].call(n) end   draw[1000] = lambda do |n| horiz(n, 0, 4, 14) end draw[2000] = lambda do |n| horiz(n, 0, 4, 10) end draw[3000] = lambda do |n| diagd(n, 0, 4, 10) end draw[4000] = lambda do |n| diagu(n, 0, 4, 14) end draw[5000] = lambda do |n| draw[1000].call(n) draw[4000].call(n) end draw[6000] = lambda do |n| verti(n, 10, 14, 0) end draw[7000] = lambda do |n| draw[1000].call(n) draw[6000].call(n) end draw[8000] = lambda do |n| draw[2000].call(n) draw[6000].call(n) end draw[9000] = lambda do |n| draw[1000].call(n) draw[8000].call(n) end   return draw end   def printNumeral(n) for a in n for b in a print b end print "\n" end print "\n" end   draw = initDraw() for number in [0, 1, 20, 300, 4000, 5555, 6789, 9999] n = initN() print number, ":\n"   thousands = (number / 1000).floor number = number % 1000   hundreds = (number / 100).floor number = number % 100   tens = (number / 10).floor ones = number % 10   if thousands > 0 then draw[thousands * 1000].call(n) end if hundreds > 0 then draw[hundreds * 100].call(n) end if tens > 0 then draw[tens * 10].call(n) end if ones > 0 then draw[ones].call(n) end printNumeral(n) end
http://rosettacode.org/wiki/Closest-pair_problem
Closest-pair problem
This page uses content from Wikipedia. The original article was at Closest pair of points problem. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Task Provide a function to find the closest two points among a set of given points in two dimensions,   i.e. to solve the   Closest pair of points problem   in the   planar   case. The straightforward solution is a   O(n2)   algorithm   (which we can call brute-force algorithm);   the pseudo-code (using indexes) could be simply: bruteForceClosestPair of P(1), P(2), ... P(N) if N < 2 then return ∞ else minDistance ← |P(1) - P(2)| minPoints ← { P(1), P(2) } foreach i ∈ [1, N-1] foreach j ∈ [i+1, N] if |P(i) - P(j)| < minDistance then minDistance ← |P(i) - P(j)| minPoints ← { P(i), P(j) } endif endfor endfor return minDistance, minPoints endif A better algorithm is based on the recursive divide&conquer approach,   as explained also at   Wikipedia's Closest pair of points problem,   which is   O(n log n);   a pseudo-code could be: closestPair of (xP, yP) where xP is P(1) .. P(N) sorted by x coordinate, and yP is P(1) .. P(N) sorted by y coordinate (ascending order) if N ≤ 3 then return closest points of xP using brute-force algorithm else xL ← points of xP from 1 to ⌈N/2⌉ xR ← points of xP from ⌈N/2⌉+1 to N xm ← xP(⌈N/2⌉)x yL ← { p ∈ yP : px ≤ xm } yR ← { p ∈ yP : px > xm } (dL, pairL) ← closestPair of (xL, yL) (dR, pairR) ← closestPair of (xR, yR) (dmin, pairMin) ← (dR, pairR) if dL < dR then (dmin, pairMin) ← (dL, pairL) endif yS ← { p ∈ yP : |xm - px| < dmin } nS ← number of points in yS (closest, closestPair) ← (dmin, pairMin) for i from 1 to nS - 1 k ← i + 1 while k ≤ nS and yS(k)y - yS(i)y < dmin if |yS(k) - yS(i)| < closest then (closest, closestPair) ← (|yS(k) - yS(i)|, {yS(k), yS(i)}) endif k ← k + 1 endwhile endfor return closest, closestPair endif References and further readings   Closest pair of points problem   Closest Pair (McGill)   Closest Pair (UCSB)   Closest pair (WUStL)   Closest pair (IUPUI)
#Haskell
Haskell
import Data.List (minimumBy, tails, unfoldr, foldl1') --'   import System.Random (newStdGen, randomRs)   import Control.Arrow ((&&&))   import Data.Ord (comparing)   vecLeng [[a, b], [p, q]] = sqrt $ (a - p) ^ 2 + (b - q) ^ 2   findClosestPair = foldl1'' ((minimumBy (comparing vecLeng) .) . (. return) . (:)) . concatMap (\(x:xs) -> map ((x :) . return) xs) . init . tails   testCP = do g <- newStdGen let pts :: [[Double]] pts = take 1000 . unfoldr (Just . splitAt 2) $ randomRs (-1, 1) g print . (id &&& vecLeng) . findClosestPair $ pts   main = testCP   foldl1'' = foldl1'
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of running any but the last function, to demonstrate that the function indeed remembers its value. Goal Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. In imperative languages, one would generally use a loop with a mutable counter variable. For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run. See also: Multiple distinct objects
#Objective-C
Objective-C
NSMutableArray *funcs = [[NSMutableArray alloc] init]; for (int i = 0; i < 10; i++) { [funcs addObject:[^ { return i * i; } copy]]; }   int (^foo)(void) = funcs[3]; NSLog(@"%d", foo()); // logs "9"  
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of running any but the last function, to demonstrate that the function indeed remembers its value. Goal Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. In imperative languages, one would generally use a loop with a mutable counter variable. For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run. See also: Multiple distinct objects
#OCaml
OCaml
let () = let cls = Array.init 10 (fun i -> (function () -> i * i)) in Random.self_init (); for i = 1 to 6 do let x = Random.int 9 in Printf.printf " fun.(%d) = %d\n" x (cls.(x) ()); done
http://rosettacode.org/wiki/Circular_primes
Circular primes
Definitions A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime. For example: 1193 is a circular prime, since 1931, 9311 and 3119 are all also prime. Note that a number which is a cyclic permutation of a smaller circular prime is not considered to be itself a circular prime. So 13 is a circular prime, but 31 is not. A repunit (denoted by R) is a number whose base 10 representation contains only the digit 1. For example: R(2) = 11 and R(5) = 11111 are repunits. Task Find the first 19 circular primes. If your language has access to arbitrary precision integer arithmetic, given that they are all repunits, find the next 4 circular primes. (Stretch) Determine which of the following repunits are probably circular primes: R(5003), R(9887), R(15073), R(25031), R(35317) and R(49081). The larger ones may take a long time to process so just do as many as you reasonably can. See also Wikipedia article - Circular primes. Wikipedia article - Repunit. OEIS sequence A016114 - Circular primes.
#Sidef
Sidef
func is_circular_prime(n) { n.is_prime || return false   var circular = n.digits circular.min < circular.tail && return false   for k in (1 ..^ circular.len) { with (circular.rotate(k).digits2num) {|p| (p.is_prime && (p >= n)) || return false } }   return true }   say "The first 19 circular primes are:" say 19.by(is_circular_prime)   say "\nThe next 4 circular primes, in repunit format, are:" {|n| (10**n - 1)/9 -> is_prob_prime }.first(4, 4..Inf).each {|n| say "R(#{n})" }   say "\nRepunit testing:" [5003, 9887, 15073, 25031, 35317, 49081].each {|n| var now = Time.micro say ("R(#{n}) -> ", is_prob_prime((10**n - 1)/9) ? 'probably prime' : 'composite', " (took: #{'%.3f' % Time.micro-now} sec)") }
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
#C.23
C#
using System; public class CirclesOfGivenRadiusThroughTwoPoints { public static void Main() { double[][] values = new double[][] { new [] { 0.1234, 0.9876, 0.8765, 0.2345, 2 }, new [] { 0.0, 2.0, 0.0, 0.0, 1 }, new [] { 0.1234, 0.9876, 0.1234, 0.9876, 2 }, new [] { 0.1234, 0.9876, 0.8765, 0.2345, 0.5 }, new [] { 0.1234, 0.9876, 0.1234, 0.9876, 0 } };   foreach (var a in values) { var p = new Point(a[0], a[1]); var q = new Point(a[2], a[3]); Console.WriteLine($"Points {p} and {q} with radius {a[4]}:"); try { var centers = FindCircles(p, q, a[4]); Console.WriteLine("\t" + string.Join(" and ", centers)); } catch (Exception ex) { Console.WriteLine("\t" + ex.Message); } } }   static Point[] FindCircles(Point p, Point q, double radius) { if(radius < 0) throw new ArgumentException("Negative radius."); if(radius == 0) { if(p == q) return new [] { p }; else throw new InvalidOperationException("No circles."); } if (p == q) throw new InvalidOperationException("Infinite number of circles.");   double sqDistance = Point.SquaredDistance(p, q); double sqDiameter = 4 * radius * radius; if (sqDistance > sqDiameter) throw new InvalidOperationException("Points are too far apart.");   Point midPoint = new Point((p.X + q.X) / 2, (p.Y + q.Y) / 2); if (sqDistance == sqDiameter) return new [] { midPoint };   double d = Math.Sqrt(radius * radius - sqDistance / 4); double distance = Math.Sqrt(sqDistance); double ox = d * (q.X - p.X) / distance, oy = d * (q.Y - p.Y) / distance; return new [] { new Point(midPoint.X - oy, midPoint.Y + ox), new Point(midPoint.X + oy, midPoint.Y - ox) }; }   public struct Point { public Point(double x, double y) : this() { X = x; Y = y; }   public double X { get; } public double Y { get; }   public static bool operator ==(Point p, Point q) => p.X == q.X && p.Y == q.Y; public static bool operator !=(Point p, Point q) => p.X != q.X || p.Y != q.Y;   public static double SquaredDistance(Point p, Point q) { double dx = q.X - p.X, dy = q.Y - p.Y; return dx * dx + dy * dy; }   public override string ToString() => $"({X}, {Y})";   } }
http://rosettacode.org/wiki/Chinese_zodiac
Chinese zodiac
Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Tuesday, February 1, 2022 CE (in the common Gregorian calendar) will begin the lunisolar Year of the Tiger. The celestial stems have no one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems each belong to one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element's governance is associated with yin, the other with yang. Thus, 2022 is also the yang year of Water. Note that since 12 is an even number, the association between animals and yin/yang doesn't change. Consecutive Years of the Rooster will cycle through the five elements, but will always be yin, despite the apparent conceptual mismatch between the specifically-male English animal name and the female aspect denoted by yin. Task Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year. You may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration). Requisite information The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig. The element cycle runs in this order: Wood, Fire, Earth, Metal, Water. The yang year precedes the yin year within each element. The current 60-year cycle began in 1984 CE; the first cycle of the Common Era began in 4 CE. Thus, 1984 was the year of the Wood Rat (yang), 1985 was the year of the Wood Ox (yin), and 1986 the year of the Fire Tiger (yang); 2022 - which, as already noted, is the year of the Water Tiger (yang) - is the 39th year of the current cycle. Information for optional task The ten celestial stems are 甲 jiă, 乙 yĭ, 丙 bĭng, 丁 dīng, 戊 wù, 己 jĭ, 庚 gēng, 辛 xīn, 壬 rén, and 癸 gŭi. With the ASCII version of Pinyin tones, the names are written "jia3", "yi3", "bing3", "ding1", "wu4", "ji3", "geng1", "xin1", "ren2", and "gui3". The twelve terrestrial branches are 子 zĭ, 丑 chŏu, 寅 yín, 卯 măo, 辰 chén, 巳 sì, 午 wŭ, 未 wèi, 申 shēn, 酉 yŏu, 戌 xū, 亥 hài. In ASCII Pinyin, those are "zi3", "chou3", "yin2", "mao3", "chen2", "si4", "wu3", "wei4", "shen1", "you3", "xu1", and "hai4". Therefore 1984 was 甲子 (jiă-zĭ, or jia3-zi3). 2022 is 壬寅 (rén-yín or ren2-yin2).
#BASIC256
BASIC256
  # Chinese zodiac   elementos = {"Wood", "Fire", "Earth", "Metal", "Water"} animales = {"Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"} aspectos = {"Yang","Yin"} tallo_celestial = {'甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸'} rama_terrestre = {'子','丑','寅','卯','辰','巳','午','未','申','酉','戌','亥'} tallos_pinyin = {"jiă","yĭ","bĭng","dīng","wù","jĭ","gēng","xīn","rén","gŭi"} ramas_pinyin = {"zĭ","chŏu","yín","măo","chén","sì","wŭ","wèi","shēn","yŏu","xū","hài"} years = {1935, 1938, 1968, 1972, 1976, 1984, 2017}   For i = 0 To years[?]-1 xYear = years[i] yElemento = elementos[((xYear - 4) % 10) \ 2] yAnimal = animales[ (xYear - 4) % 12 ] yAspectos = aspectos[ xYear  % 2 ] ytallo_celestial = tallo_celestial[((xYear - 4) % 10)] yrama_terrestre = rama_terrestre[ (xYear - 4) % 12 ] ytallos_pinyin = tallos_pinyin[ ((xYear - 4) % 10)] yramas_pinyin = ramas_pinyin[ (xYear - 4) % 12 ] ciclo = ((xYear - 4) % 60) + 1 Print xYear & ": " & ytallo_celestial & yrama_terrestre & " (" & ytallos_pinyin & "-" & yramas_pinyin & ", " & yElemento & " " & yAnimal & "; " & yAspectos & " - ciclo " &ciclo & "/60)" Next i End  
http://rosettacode.org/wiki/Chinese_zodiac
Chinese zodiac
Traditionally, the Chinese have counted years using two simultaneous cycles, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"); the combination results in a repeating 60-year pattern. Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Tuesday, February 1, 2022 CE (in the common Gregorian calendar) will begin the lunisolar Year of the Tiger. The celestial stems have no one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems each belong to one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element's governance is associated with yin, the other with yang. Thus, 2022 is also the yang year of Water. Note that since 12 is an even number, the association between animals and yin/yang doesn't change. Consecutive Years of the Rooster will cycle through the five elements, but will always be yin, despite the apparent conceptual mismatch between the specifically-male English animal name and the female aspect denoted by yin. Task Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year. You may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration). Requisite information The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig. The element cycle runs in this order: Wood, Fire, Earth, Metal, Water. The yang year precedes the yin year within each element. The current 60-year cycle began in 1984 CE; the first cycle of the Common Era began in 4 CE. Thus, 1984 was the year of the Wood Rat (yang), 1985 was the year of the Wood Ox (yin), and 1986 the year of the Fire Tiger (yang); 2022 - which, as already noted, is the year of the Water Tiger (yang) - is the 39th year of the current cycle. Information for optional task The ten celestial stems are 甲 jiă, 乙 yĭ, 丙 bĭng, 丁 dīng, 戊 wù, 己 jĭ, 庚 gēng, 辛 xīn, 壬 rén, and 癸 gŭi. With the ASCII version of Pinyin tones, the names are written "jia3", "yi3", "bing3", "ding1", "wu4", "ji3", "geng1", "xin1", "ren2", and "gui3". The twelve terrestrial branches are 子 zĭ, 丑 chŏu, 寅 yín, 卯 măo, 辰 chén, 巳 sì, 午 wŭ, 未 wèi, 申 shēn, 酉 yŏu, 戌 xū, 亥 hài. In ASCII Pinyin, those are "zi3", "chou3", "yin2", "mao3", "chen2", "si4", "wu3", "wei4", "shen1", "you3", "xu1", and "hai4". Therefore 1984 was 甲子 (jiă-zĭ, or jia3-zi3). 2022 is 壬寅 (rén-yín or ren2-yin2).
#Befunge
Befunge
0"  :raeY">:#,_55+"< /8"&>+:66+%00p:55+v v"Aspect: "0++88*5%2\0\+1%"<":p01++66/2%< >00g5g7-0"  :laminA"10g5g"<"+0" :tnemelE"v v!:,+55$_v#!-*84,:g+5/< >:#,_$.,,.,@ >0#< _>>:#,_$>>1+::"("%\"("^ ^"Cycle: " <<<< $'-4;AGLS[_ %*06yang yin Rat Ox Tiger R | abbit Dragon Snake Horse Goat Monkey Roo | ster Dog Pig Wood Fire Earth Metal Water |
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
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program verifFic64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc" .equ CHDIR, 49 .equ AT_FDCWD, -100   /*******************************************/ /* Initialized data */ /*******************************************/ .data szMessFound1: .asciz "File 1 found.\n" szMessFound2: .asciz "File 2 found.\n" szMessNotFound1: .asciz "File 1 not found.\n" szMessNotFound2: .asciz "File 2 not found.\n" szMessDir2: .asciz "File 2 is a directory.\n" szMessNotAuth2: .asciz "File 2 permission denied.\n" szCarriageReturn: .asciz "\n"   /* areas strings */ szPath2: .asciz "/" szFicName1: .asciz "test1.txt" szFicName2: .asciz "root"   /*******************************************/ /* UnInitialized data */ /*******************************************/ .bss /*******************************************/ /* code section */ /*******************************************/ .text .global main main: // entry of program   /************************************* open file 1 ************************************/ mov x0,AT_FDCWD // current directory ldr x1,qAdrszFicName1 // file name mov x2,#O_RDWR // flags mov x3,#0 // mode mov x8, #OPEN // call system OPEN svc 0 cmp x0,#0 // error ? ble 1f mov x1,x0 // FD ldr x0,qAdrszMessFound1 bl affichageMess // close file mov x0,x1 // Fd mov x8, #CLOSE svc 0 b 2f 1: ldr x0,qAdrszMessNotFound1 bl affichageMess 2: /************************************* open file 2 ************************************/ ldr x0,qAdrszPath2 mov x8,CHDIR // call system change directory svc 0 mov x0,AT_FDCWD // current directory ldr x1,qAdrszFicName2 // file name mov x2,O_RDWR // flags mov x3,0 // mode mov x8,OPEN // call system OPEN svc 0 cmp x0,-21 // is a directory ? beq 4f cmp x0,0 // error ? ble 3f mov x1,x0 // FD ldr x0,qAdrszMessFound2 bl affichageMess // close file mov x0,x1 // Fd mov x8, #CLOSE svc 0 b 100f 3: ldr x0,qAdrszMessNotFound2 bl affichageMess b 100f 4: ldr x0,qAdrszMessDir2 bl affichageMess 100: // standard end of the program mov x0,0 // return code mov x8,EXIT // request to exit program svc 0 // perform the system call qAdrszFicName1: .quad szFicName1 qAdrszFicName2: .quad szFicName2 qAdrszMessFound1: .quad szMessFound1 qAdrszMessFound2: .quad szMessFound2 qAdrszMessNotFound1: .quad szMessNotFound1 qAdrszMessNotFound2: .quad szMessNotFound2 qAdrszMessNotAuth2: .quad szMessNotAuth2 qAdrszPath2: .quad szPath2 qAdrszMessDir2: .quad szMessDir2 /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"  
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
#Action.21
Action!
BYTE lastError   PROC MyError(BYTE errCode) lastError=errCode RETURN   BYTE FUNC FileExists(CHAR ARRAY fname) DEFINE PTR="CARD" PTR old BYTE dev=[1]   lastError=0 old=Error Error=MyError ;replace error handling to capture I/O error   Close(dev) Open(dev,fname,4) Close(dev)   Error=old ;restore the original error handling   IF lastError=0 THEN RETURN (1) FI RETURN (0)   PROC Test(CHAR ARRAY fname) BYTE exists   exists=FileExists(fname) IF exists THEN PrintF("File ""%S"" exists.%E",fname) ELSE PrintF("File ""%S"" does not exist.%E",fname) FI RETURN   PROC Main() Test("D:INPUT.TXT") Test("D:DOS.SYS") RETURN
http://rosettacode.org/wiki/Check_output_device_is_a_terminal
Check output device is a terminal
Task Demonstrate how to check whether the output device is a terminal or not. Related task   Check input device is a terminal
#Factor
Factor
  IN: scratchpad USE: unix.ffi IN: scratchpad 1 isatty   --- Data stack: 1  
http://rosettacode.org/wiki/Check_output_device_is_a_terminal
Check output device is a terminal
Task Demonstrate how to check whether the output device is a terminal or not. Related task   Check input device is a terminal
#FreeBASIC
FreeBASIC
  Open Cons For Output As #1 ' Open Cons abre los flujos de entrada (stdin) o salida (stdout) estándar ' de la consola para leer o escribir.   If Err > 0 Then Print #1, "stdout is not a tty." Else Print #1, "stdout is a tty." End If Close #1 Sleep  
http://rosettacode.org/wiki/Check_output_device_is_a_terminal
Check output device is a terminal
Task Demonstrate how to check whether the output device is a terminal or not. Related task   Check input device is a terminal
#Go
Go
package main   import ( "os" "fmt" )   func main() { if fileInfo, _ := os.Stdout.Stat(); (fileInfo.Mode() & os.ModeCharDevice) != 0 { fmt.Println("Hello terminal") } else { fmt.Println("Who are you? You're not a terminal") } }
http://rosettacode.org/wiki/Check_output_device_is_a_terminal
Check output device is a terminal
Task Demonstrate how to check whether the output device is a terminal or not. Related task   Check input device is a terminal
#Haskell
Haskell
module Main where   -- requires the unix package -- https://hackage.haskell.org/package/unix import System.Posix.Terminal (queryTerminal) import System.Posix.IO (stdOutput)   main :: IO () main = do istty <- queryTerminal stdOutput putStrLn (if istty then "stdout is tty" else "stdout is not tty")
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.
#Clojure
Clojure
(defn cholesky [matrix] (let [n (count matrix) A (to-array-2d matrix) L (make-array Double/TYPE n n)] (doseq [i (range n) j (range (inc i))] (let [s (reduce + (for [k (range j)] (* (aget L i k) (aget L j k))))] (aset L i j (if (= i j) (Math/sqrt (- (aget A i i) s)) (* (/ 1.0 (aget L j j)) (- (aget A i j) s)))))) (vec (map vec L))))
http://rosettacode.org/wiki/Check_input_device_is_a_terminal
Check input device is a terminal
Task Demonstrate how to check whether the input device is a terminal or not. Related task   Check output device is a terminal
#FreeBASIC
FreeBASIC
  Open Cons For Input As #1 ' Open Cons abre los flujos de entrada (stdin) o salida (stdout) estándar ' de la consola para leer o escribir.   If Err Then Print "Input doesn't come from tt." Else Print "Input comes from tty." End If Close #1 Sleep  
http://rosettacode.org/wiki/Check_input_device_is_a_terminal
Check input device is a terminal
Task Demonstrate how to check whether the input device is a terminal or not. Related task   Check output device is a terminal
#Go
Go
package main   import ( "golang.org/x/crypto/ssh/terminal" "fmt" "os" )   func main() { if terminal.IsTerminal(int(os.Stdin.Fd())) { fmt.Println("Hello terminal") } else { fmt.Println("Who are you? You're not a terminal.") } }
http://rosettacode.org/wiki/Check_input_device_is_a_terminal
Check input device is a terminal
Task Demonstrate how to check whether the input device is a terminal or not. Related task   Check output device is a terminal
#Haskell
Haskell
module Main (main) where   import System.Posix.IO (stdInput) import System.Posix.Terminal (queryTerminal)   main :: IO () main = do isTTY <- queryTerminal stdInput putStrLn $ if isTTY then "stdin is TTY" else "stdin is not TTY"
http://rosettacode.org/wiki/Check_input_device_is_a_terminal
Check input device is a terminal
Task Demonstrate how to check whether the input device is a terminal or not. Related task   Check output device is a terminal
#Jsish
Jsish
/* Check input device is a terminal, in Jsish */ ;Interp.conf().subOpts.istty;   /* =!EXPECTSTART!= Interp.conf().subOpts.istty ==> false =!EXPECTEND!= */
http://rosettacode.org/wiki/Check_input_device_is_a_terminal
Check input device is a terminal
Task Demonstrate how to check whether the input device is a terminal or not. Related task   Check output device is a terminal
#Julia
Julia
  if isa(STDIN, Base.TTY) println("This program sees STDIN as a TTY.") else println("This program does not see STDIN as a TTY.") end  
http://rosettacode.org/wiki/Cheryl%27s_birthday
Cheryl's birthday
Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is. Cheryl gave them a list of ten possible dates: May 15, May 16, May 19 June 17, June 18 July 14, July 16 August 14, August 15, August 17 Cheryl then tells Albert the   month   of birth,   and Bernard the   day   (of the month)   of birth. 1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too. 2) Bernard: At first I don't know when Cheryl's birthday is, but I know now. 3) Albert: Then I also know when Cheryl's birthday is. Task Write a computer program to deduce, by successive elimination, Cheryl's birthday. Related task Sum and Product Puzzle References Wikipedia article of the same name. Tuple Relational Calculus
#AutoHotkey
AutoHotkey
oDates:= {"May" : [ 15, 16, 19] ,"Jun" : [ 17, 18] ,"Jul" : [14, 16] ,"Aug" : [14, 15, 17]}   filter1(oDates) filter2(oDates) filter3(oDates) MsgBox % result := checkAnswer(oDates) return   filter1(ByRef oDates){ ; remove months that has a unique day in it. for d, obj in MonthsOfDay(oDates) if (obj.count() = 1) for m, bool in obj oDates.Remove(m) }   filter2(ByRef oDates){ ; remove non-unique days from remaining months. for d, obj in MonthsOfDay(oDates) if (obj.count() > 1) for m, bool in obj for i, day in oDates[m] if (day=d) oDates[m].Remove(i) }   filter3(ByRef oDates){ ; remove months that has multiple days from remaining months. oRemove := [] for m, obj in oDates if obj.count() > 1 oRemove.Push(m) for i, m in oRemove oDates.Remove(m) }   MonthsOfDay(oDates){ ; create a list of months per day. MonthsOfDay := [] for m, obj in oDates for i, d in obj MonthsOfDay[d, m] := 1 return MonthsOfDay }   checkAnswer(oDates){ ; check unique answer if any. if oDates.count()>1 return false for m, obj in oDates if obj.count() > 1 return false else return m " " obj.1 }
http://rosettacode.org/wiki/Checkpoint_synchronization
Checkpoint synchronization
The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before starting another one. Putting details together is the checkpoint at which tasks synchronize themselves before going their paths apart. The task Implement checkpoint synchronization in your language. Make sure that the solution is race condition-free. Note that a straightforward solution based on events is exposed to race condition. Let two tasks A and B need to be synchronized at a checkpoint. Each signals its event (EA and EB correspondingly), then waits for the AND-combination of the events (EA&EB) and resets its event. Consider the following scenario: A signals EA first and gets blocked waiting for EA&EB. Then B signals EB and loses the processor. Then A is released (both events are signaled) and resets EA. Now if B returns and enters waiting for EA&EB, it gets lost. When a worker is ready it shall not continue before others finish. A typical implementation bug is when a worker is counted twice within one working cycle causing its premature completion. This happens when the quickest worker serves its cycle two times while the laziest one is lagging behind. If you can, implement workers joining and leaving.
#D
D
import std.stdio; import std.parallelism: taskPool, defaultPoolThreads, totalCPUs;   void buildMechanism(uint nparts) { auto details = new uint[nparts]; foreach (i, ref detail; taskPool.parallel(details)) { writeln("Build detail ", i); detail = i; }   // This could be written more concisely via std.parallelism.reduce, // but we want to see the checkpoint explicitly. writeln("Checkpoint reached. Assemble details ..."); uint sum = 0; foreach (immutable detail; details) sum += detail; writeln("Mechanism with ", nparts, " parts finished: ", sum); }   void main() { defaultPoolThreads = totalCPUs + 1; // totalCPUs - 1 on default. buildMechanism(42); buildMechanism(11); }
http://rosettacode.org/wiki/Checkpoint_synchronization
Checkpoint synchronization
The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before starting another one. Putting details together is the checkpoint at which tasks synchronize themselves before going their paths apart. The task Implement checkpoint synchronization in your language. Make sure that the solution is race condition-free. Note that a straightforward solution based on events is exposed to race condition. Let two tasks A and B need to be synchronized at a checkpoint. Each signals its event (EA and EB correspondingly), then waits for the AND-combination of the events (EA&EB) and resets its event. Consider the following scenario: A signals EA first and gets blocked waiting for EA&EB. Then B signals EB and loses the processor. Then A is released (both events are signaled) and resets EA. Now if B returns and enters waiting for EA&EB, it gets lost. When a worker is ready it shall not continue before others finish. A typical implementation bug is when a worker is counted twice within one working cycle causing its premature completion. This happens when the quickest worker serves its cycle two times while the laziest one is lagging behind. If you can, implement workers joining and leaving.
#E
E
/** A flagSet solves this problem: There are N things, each in a true or false * state, and we want to know whether they are all true (or all false), and be * able to bulk-change all of them, and all this without allowing double- * counting -- setting a flag twice is idempotent. */ def makeFlagSet() { # Each flag object is either in the true set or the false set. def trues := [].asSet().diverge() def falses := [].asSet().diverge() return def flagSet { /** Add a flag to the set. */ to join() { def flag { /** Get the value of this flag. */ to get() :boolean {   } /** Set the value of this flag. */ to put(v :boolean) { def [del,add] := if (v) { [falses,trues] } else { [trues,falses] } if (del.contains(flag)) { del.remove(flag) add.addElement(flag) } } /** Remove this flag from the set. */ to leave() :void { trues.remove(flag) falses.remove(flag) } } falses.addElement(flag) return flag } /** Are all the flags true (none false)? */ to allTrue() { return falses.size().isZero() } /** Are all the flags false (none true)? */ to allFalse() { return trues.size().isZero() } /** Set all the flags to the same value. */ to setAll(v :boolean) { def [del,add] := if (v) { [falses,trues] } else { [trues,falses] } add.addAll(del) del.removeAll(del) } } }   def makeCheckpoint() { def [var continueSignal, var continueRes] := Ref.promise() def readies := makeFlagSet()   /** Check whether all tasks have reached the checkpoint, and if so send the * signal and go to the next round. */ def check() { if (readies.allTrue()) { readies.setAll(false)   continueRes.resolve(null) # send the continue signal   def [p, r] := Ref.promise() # prepare a new continue signal continueSignal := p continueRes := r } }   return def checkpoint { to join() { def &flag := readies.join() return def membership { to leave() { (&flag).leave() check <- () } to deliver() { flag := true check <- () return continueSignal } } } } }   def makeWorker(piece, checkpoint) { def stops := timer.now() + 3000 + entropy.nextInt(2000) var count := 0 def checkpointMember := checkpoint <- join() def stopped def run() { # Pretend to do something lengthy; up to 1000 ms. timer.whenPast(timer.now() + entropy.nextInt(1000), fn { if (timer.now() >= stops) { checkpointMember <- leave() bind stopped := true } else { count += 1 println(`Delivering $piece#$count`) when (checkpointMember <- deliver()) -> { println(`Delivered $piece#$count`) run() } } }) } run() return stopped }   def checkpoint := makeCheckpoint() var waits := [] for piece in 1..5 { waits with= makeWorker(piece, checkpoint) } interp.waitAtTop(promiseAllFulfilled(waits))
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
#Fancy
Fancy
  # creating an empty array and adding values   a = [] # => [] a[0]: 1 # => [1] a[3]: 2 # => [1, nil, nil, 2]   # creating an array with the constructor a = Array new # => []  
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
#Lua
Lua
  function map(f, a, ...) if a then return f(a), map(f, ...) end end function incr(k) return function(a) return k > a and a or a+1 end end function combs(m, n) if m * n == 0 then return {{}} end local ret, old = {}, combs(m-1, n-1) for i = 1, n do for k, v in ipairs(old) do ret[#ret+1] = {i, map(incr(i), unpack(v))} end end return ret end   for k, v in ipairs(combs(3, 5)) do print(unpack(v)) end  
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.
#QB64
QB64
    Print "QB64/Qbasic conditional structures" Dim k As String Menu 1 View Print 13 To 23 Print "A menu example using the many options of IF statement" k = " " 12: While k <> "" k = UCase$(Input$(1)) If k = "O" GoTo O If k = "F" Then 22 If k = "S" Then GoSub S: GoTo 12 If k = "C" Then GoSub 4: GoTo 12 If k = "E" Then GoSub 5: Exit While Wend Cls Print "the same menu example with Select Case" Sleep 2 While k <> "" k = UCase$(Input$(1))   Select Case k Case "O" Print "You choose O" Case "F" Print "You choose F" Case "S" Print "You choose S" Case "C" Print "You choose C" Case "E" Print "You choose Exit" _Delay 1 Exit While Case Else Print "Wrong choice" End Select Wend View Print Cls Menu 2 View Print 13 To 23 Print "menu demonstration using ON value GOTO" k = " " While k <> "" k = Input$(1) On Val(k) GOSUB 1, 2, 3, 4, 5 Wend End   1: Print "Chosen O" Return   2: Print "Chosen F" Return   3: Print "Chosen S" Return   4: Print "Chosen C" Return   5: Print "Chosen E" If k = "5" Then End Return     O: Print "You choose O" GoTo 12   22: Print "You choose F" GoTo 12   S: Print "You choose S" Return       Sub Menu (Kind As Integer) Locate 7, 33: Color 3, 4 Print "Choose the item" Color 7, 0 Locate , 33 If Kind = 1 Then Print "Open a file"; Else Print "1) Open a file"; Color 14, 1 Locate , 33 If Kind = 1 Then Print "O" Else Print "1" Color 7, 0   Locate , 33 If Kind = 1 Then Print "Find a file"; Else Print "2) Find a file"; Color 14, 1 Locate , 33 If Kind = 1 Then Print "F" Else Print "2" Color 7, 0   Locate , 33 If Kind = 1 Then Print "Scan a file"; Else Print "3) Scan a file"; Color 14, 1 Locate , 33 If Kind = 1 Then Print "S" Else Print "3" Color 7, 0   Locate , 33 If Kind = 1 Then Print "Copy a file"; Else Print "4) Copy a file"; Color 14, 1 Locate , 33 If Kind = 1 Then Print "C" Else Print "4" Color 7, 0   Locate , 33 If Kind = 1 Then Print "Exit from Menu"; Else Print "5) Exit from Menu"; Color 14, 1 Locate , 33 If Kind = 1 Then Print "E" Else Print "5" Color 7, 0   End Sub  
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}}} .
#C.23
C#
using System; using System.Linq;   namespace ChineseRemainderTheorem { class Program { static void Main(string[] args) { int[] n = { 3, 5, 7 }; int[] a = { 2, 3, 2 };   int result = ChineseRemainderTheorem.Solve(n, a);   int counter = 0; int maxCount = n.Length - 1; while (counter <= maxCount) { Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})"); counter++; } } }   public static class ChineseRemainderTheorem { public static int Solve(int[] n, int[] a) { int prod = n.Aggregate(1, (i, j) => i * j); int p; int sm = 0; for (int i = 0; i < n.Length; i++) { p = prod / n[i]; sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p; } return sm % prod; }   private static int ModularMultiplicativeInverse(int a, int mod) { int b = a % mod; for (int x = 1; x < mod; x++) { if ((b * x) % mod == 1) { return x; } } return 1; } } }
http://rosettacode.org/wiki/Chernick%27s_Carmichael_numbers
Chernick's Carmichael numbers
In 1939, Jack Chernick proved that, for n ≥ 3 and m ≥ 1: U(n, m) = (6m + 1) * (12m + 1) * Product_{i=1..n-2} (2^i * 9m + 1) is a Carmichael number if all the factors are primes and, for n > 4, m is a multiple of 2^(n-4). Example U(3, m) = (6m + 1) * (12m + 1) * (18m + 1) U(4, m) = U(3, m) * (2^2 * 9m + 1) U(5, m) = U(4, m) * (2^3 * 9m + 1) ... U(n, m) = U(n-1, m) * (2^(n-2) * 9m + 1) The smallest Chernick's Carmichael number with 3 prime factors, is: U(3, 1) = 1729. The smallest Chernick's Carmichael number with 4 prime factors, is: U(4, 1) = 63973. The smallest Chernick's Carmichael number with 5 prime factors, is: U(5, 380) = 26641259752490421121. For n = 5, the smallest number m that satisfy Chernick's conditions, is m = 380, therefore U(5, 380) is the smallest Chernick's Carmichael number with 5 prime factors. U(5, 380) is a Chernick's Carmichael number because m = 380 is a multiple of 2^(n-4), where n = 5, and the factors { (6*380 + 1), (12*380 + 1), (18*380 + 1), (36*380 + 1), (72*380 + 1) } are all prime numbers. Task For n ≥ 3, let a(n) be the smallest Chernick's Carmichael number with n prime factors. Compute a(n) for n = 3..9. Optional: find a(10). Note: it's perfectly acceptable to show the terms in factorized form: a(3) = 7 * 13 * 19 a(4) = 7 * 13 * 19 * 37 a(5) = 2281 * 4561 * 6841 * 13681 * 27361 ... See also Jack Chernick, On Fermat's simple theorem (PDF) OEIS A318646: The least Chernick's "universal form" Carmichael number with n prime factors Related tasks Carmichael 3 strong pseudoprimes
#Prolog
Prolog
  ?- use_module(library(primality)).   u(3, M, A * B * C) :- A is 6*M + 1, B is 12*M + 1, C is 18*M + 1, !. u(N, M, U0 * D) :- succ(Pn, N), u(Pn, M, U0), D is 9*(1 << (N - 2))*M + 1.   prime_factorization(A*B) :- prime(B), prime_factorization(A), !. prime_factorization(A) :- prime(A).   step(N, 1) :- N < 5, !. step(5, 2) :- !. step(N, K) :- K is 5*(1 << (N - 4)).   a(N, Factors) :- % due to backtracking nature of Prolog, a(n) will return all chernick-carmichael numbers. N > 2, !, step(N, I), between(1, infinite, J), M is I * J, u(N, M, Factors), prime_factorization(Factors).   main :- forall( (between(3, 9, K), once(a(K, Factorization)), N is Factorization), format("~w: ~w = ~w~n", [K, Factorization, N])), halt.   ?- main.  
http://rosettacode.org/wiki/Chowla_numbers
Chowla numbers
Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n   is a positive integer The sequence is named after   Sarvadaman D. S. Chowla,   (22 October 1907 ──► 10 December 1995), a London born Indian American mathematician specializing in number theory. German mathematician Carl Friedrich Gauss (1777─1855) said: "Mathematics is the queen of the sciences ─ and number theory is the queen of mathematics". Definitions Chowla numbers can also be expressed as: chowla(n) = sum of divisors of n excluding unity and n chowla(n) = sum( divisors(n)) - 1 - n chowla(n) = sum( properDivisors(n)) - 1 chowla(n) = sum(aliquotDivisors(n)) - 1 chowla(n) = aliquot(n) - 1 chowla(n) = sigma(n) - 1 - n chowla(n) = sigmaProperDivisiors(n) - 1   chowla(a*b) = a + b,   if a and b are distinct primes if chowla(n) = 0,  and n > 1, then n is prime if chowla(n) = n - 1, and n > 1, then n is a perfect number Task   create a   chowla   function that returns the   chowla number   for a positive integer   n   Find and display   (1 per line)   for the 1st   37   integers:   the integer   (the index)   the chowla number for that integer   For finding primes, use the   chowla   function to find values of zero   Find and display the   count   of the primes up to              100   Find and display the   count   of the primes up to           1,000   Find and display the   count   of the primes up to         10,000   Find and display the   count   of the primes up to       100,000   Find and display the   count   of the primes up to    1,000,000   Find and display the   count   of the primes up to  10,000,000   For finding perfect numbers, use the   chowla   function to find values of   n - 1   Find and display all   perfect numbers   up to   35,000,000   use commas within appropriate numbers   show all output here Related tasks   totient function   perfect numbers   Proper divisors   Sieve of Eratosthenes See also   the OEIS entry for   A48050 Chowla's function.
#EasyLang
EasyLang
func chowla n . sum . sum = 0 i = 2 while i * i <= n if n mod i = 0 j = n div i if i = j sum += i else sum += i + j . . i += 1 . . func sieve . c[] . i = 3 while i * 3 < len c[] if c[i] = 0 call chowla i h if h = 0 j = 3 * i while j < len c[] c[j] = 1 j += 2 * i . . . i += 2 . . func commatize n . s$ . s$[] = strchars n s$ = "" l = len s$[] for i range len s$[] if i > 0 and l mod 3 = 0 s$ &= "," . l -= 1 s$ &= s$[i] . . print "chowla number from 1 to 37" for i = 1 to 37 call chowla i h print " " & i & ": " & h . func main . . print "" len c[] 10000000 count = 1 call sieve c[] power = 100 i = 3 while i < len c[] if c[i] = 0 count += 1 . if i = power - 1 call commatize power p$ call commatize count c$ print "There are " & c$ & " primes up to " & p$ power *= 10 . i += 2 . print "" limit = 35000000 count = 0 i = 2 k = 2 kk = 3 repeat p = k * kk until p > limit call chowla p h if h = p - 1 call commatize p s$ print s$ & " is a perfect number" count += 1 . k = kk + 1 kk += k i += 1 . call commatize limit s$ print "There are " & count & " perfect mumbers up to " & s$ . call main
http://rosettacode.org/wiki/Chowla_numbers
Chowla numbers
Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n   is a positive integer The sequence is named after   Sarvadaman D. S. Chowla,   (22 October 1907 ──► 10 December 1995), a London born Indian American mathematician specializing in number theory. German mathematician Carl Friedrich Gauss (1777─1855) said: "Mathematics is the queen of the sciences ─ and number theory is the queen of mathematics". Definitions Chowla numbers can also be expressed as: chowla(n) = sum of divisors of n excluding unity and n chowla(n) = sum( divisors(n)) - 1 - n chowla(n) = sum( properDivisors(n)) - 1 chowla(n) = sum(aliquotDivisors(n)) - 1 chowla(n) = aliquot(n) - 1 chowla(n) = sigma(n) - 1 - n chowla(n) = sigmaProperDivisiors(n) - 1   chowla(a*b) = a + b,   if a and b are distinct primes if chowla(n) = 0,  and n > 1, then n is prime if chowla(n) = n - 1, and n > 1, then n is a perfect number Task   create a   chowla   function that returns the   chowla number   for a positive integer   n   Find and display   (1 per line)   for the 1st   37   integers:   the integer   (the index)   the chowla number for that integer   For finding primes, use the   chowla   function to find values of zero   Find and display the   count   of the primes up to              100   Find and display the   count   of the primes up to           1,000   Find and display the   count   of the primes up to         10,000   Find and display the   count   of the primes up to       100,000   Find and display the   count   of the primes up to    1,000,000   Find and display the   count   of the primes up to  10,000,000   For finding perfect numbers, use the   chowla   function to find values of   n - 1   Find and display all   perfect numbers   up to   35,000,000   use commas within appropriate numbers   show all output here Related tasks   totient function   perfect numbers   Proper divisors   Sieve of Eratosthenes See also   the OEIS entry for   A48050 Chowla's function.
#Factor
Factor
USING: formatting fry grouping.extras io kernel math math.primes.factors math.ranges math.statistics sequences tools.memory.private ; IN: rosetta-code.chowla-numbers   : chowla ( n -- m ) dup 1 = [ 1 - ] [ [ divisors sum ] [ - 1 - ] bi ] if ;   : show-chowla ( n -- ) [1,b] [ dup chowla "chowla(%02d) = %d\n" printf ] each ;   : count-primes ( seq -- ) dup 0 prefix [ [ 1 + ] dip 2 <range> ] 2clump-map [ [ chowla zero? ] count ] map cum-sum [ [ commas ] bi@ "Primes up to %s: %s\n" printf ] 2each ;   : show-perfect ( n -- ) [ 2 3 ] dip '[ 2dup * dup _ > ] [ dup [ chowla ] [ 1 - = ] bi [ commas "%s is perfect\n" printf ] [ drop ] if [ nip 1 + ] [ nip dupd + ] 2bi ] until 3drop ;   : chowla-demo ( -- ) 37 show-chowla nl { 100 1000 10000 100000 1000000 10000000 } count-primes nl 35e7 show-perfect ;   MAIN: chowla-demo
http://rosettacode.org/wiki/Church_numerals
Church numerals
Task In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all. Church one applies its first argument f just once to its second argument x, yielding f(x) Church two applies its first argument f twice to its second argument x, yielding f(f(x)) and each successive Church numeral applies its first argument one additional time to its second argument, f(f(f(x))), f(f(f(f(x)))) ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument. Arithmetic operations on natural numbers can be similarly represented as functions on Church numerals. In your language define: Church Zero, a Church successor function (a function on a Church numeral which returns the next Church numeral in the series), functions for Addition, Multiplication and Exponentiation over Church numerals, a function to convert integers to corresponding Church numerals, and a function to convert Church numerals to corresponding integers. You should: Derive Church numerals three and four in terms of Church zero and a Church successor function. use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4, similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function, convert each result back to an integer, and return it or print it to the console.
#Lua
Lua
  function churchZero() return function(x) return x end end   function churchSucc(c) return function(f) return function(x) return f(c(f)(x)) end end end   function churchAdd(c, d) return function(f) return function(x) return c(f)(d(f)(x)) end end end   function churchMul(c, d) return function(f) return c(d(f)) end end   function churchExp(c, e) return e(c) end   function numToChurch(n) local ret = churchZero for i = 1, n do ret = succ(ret) end return ret end   function churchToNum(c) return c(function(x) return x + 1 end)(0) end   three = churchSucc(churchSucc(churchSucc(churchZero))) four = churchSucc(churchSucc(churchSucc(churchSucc(churchZero))))   print("'three'\t=", churchToNum(three)) print("'four' \t=", churchToNum(four)) print("'three' * 'four' =", churchToNum(churchMul(three, four))) print("'three' + 'four' =", churchToNum(churchAdd(three, four))) print("'three' ^ 'four' =", churchToNum(churchExp(three, four))) print("'four' ^ 'three' =", churchToNum(churchExp(four, three)))
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.
#Eiffel
Eiffel
  class MY_CLASS end  
http://rosettacode.org/wiki/Classes
Classes
In object-oriented programming class is a set (a transitive closure) of types bound by the relation of inheritance. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the root type of the class. A class of types itself, as a type, has the values and operations of its own. The operations of are usually called methods of the root type. Both operations and values are called polymorphic. A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument. The action of choice the type-specific implementation of a polymorphic operation is called dispatch. Correspondingly, polymorphic operations are often called dispatching or virtual. Operations with multiple arguments and/or the results of the class are called multi-methods. A further generalization of is the operation with arguments and/or results from different classes. single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation x.f() is used instead of mathematical f(x). multiple-dispatch languages allow many arguments and/or results to control the dispatch. A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type. This type is sometimes called the most specific type of a [polymorphic] value. The type tag of the value is used in order to resolve the dispatch. The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class. In many OO languages the type of the class of T and T itself are considered equivalent. In some languages they are distinct (like in Ada). When class T and T are equivalent, there is no way to distinguish polymorphic and specific values. Task Create a basic class with a method, a constructor, an instance variable and how to instantiate it.
#Elena
Elena
import extensions;   class MyClass { prop int Variable;   someMethod() { Variable := 1 }   constructor() { } }   public program() { // instantiate the class var instance := new MyClass();   // invoke the method instance.someMethod();   // get the variable console.printLine("Variable=",instance.Variable) }
http://rosettacode.org/wiki/Cistercian_numerals
Cistercian numerals
Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from 0 to 9999. How they work All Cistercian numerals begin with a vertical line segment, which by itself represents the number 0. Then, glyphs representing the digits 1 through 9 are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number: The upper-right quadrant represents the ones place. The upper-left quadrant represents the tens place. The lower-right quadrant represents the hundreds place. The lower-left quadrant represents the thousands place. Please consult the following image for examples of Cistercian numerals showing each glyph: [1] Task Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile). Use the routine to show the following Cistercian numerals: 0 1 20 300 4000 5555 6789 And a number of your choice! Notes Due to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed — especially for text output. See also Numberphile - The Forgotten Number System dcode.fr - Online Cistercian numeral converter
#Wren
Wren
import "/fmt" for Fmt   var n   var init = Fn.new { n = List.filled(15, null) for (i in 0..14) { n[i] = List.filled(11, " ") n[i][5] = "x" } }   var horiz = Fn.new { |c1, c2, r| (c1..c2).each { |c| n[r][c] = "x" } } var verti = Fn.new { |r1, r2, c| (r1..r2).each { |r| n[r][c] = "x" } } var diagd = Fn.new { |c1, c2, r| (c1..c2).each { |c| n[r+c-c1][c] = "x" } } var diagu = Fn.new { |c1, c2, r| (c1..c2).each { |c| n[r-c+c1][c] = "x" } }   var draw // map contains recursive closures draw = { 1: Fn.new { horiz.call(6, 10, 0) }, 2: Fn.new { horiz.call(6, 10, 4) }, 3: Fn.new { diagd.call(6, 10, 0) }, 4: Fn.new { diagu.call(6, 10, 4) }, 5: Fn.new { draw[1].call() draw[4].call() }, 6: Fn.new { verti.call(0, 4, 10) }, 7: Fn.new { draw[1].call() draw[6].call() }, 8: Fn.new { draw[2].call() draw[6].call() }, 9: Fn.new { draw[1].call() draw[8].call() }, 10: Fn.new { horiz.call(0, 4, 0) }, 20: Fn.new { horiz.call(0, 4, 4) }, 30: Fn.new { diagu.call(0, 4, 4) }, 40: Fn.new { diagd.call(0, 4, 0) }, 50: Fn.new { draw[10].call() draw[40].call() }, 60: Fn.new { verti.call(0, 4, 0) }, 70: Fn.new { draw[10].call() draw[60].call() }, 80: Fn.new { draw[20].call() draw[60].call() }, 90: Fn.new { draw[10].call() draw[80].call() }, 100: Fn.new { horiz.call(6, 10, 14) }, 200: Fn.new { horiz.call(6, 10, 10) }, 300: Fn.new { diagu.call(6, 10, 14) }, 400: Fn.new { diagd.call(6, 10, 10) }, 500: Fn.new { draw[100].call() draw[400].call() }, 600: Fn.new { verti.call(10, 14, 10) }, 700: Fn.new { draw[100].call() draw[600].call() }, 800: Fn.new { draw[200].call() draw[600].call() }, 900: Fn.new { draw[100].call() draw[800].call() }, 1000: Fn.new { horiz.call(0, 4, 14) }, 2000: Fn.new { horiz.call(0, 4, 10) }, 3000: Fn.new { diagd.call(0, 4, 10) }, 4000: Fn.new { diagu.call(0, 4, 14) }, 5000: Fn.new { draw[1000].call() draw[4000].call() }, 6000: Fn.new { verti.call(10, 14, 0) }, 7000: Fn.new { draw[1000].call() draw[6000].call() }, 8000: Fn.new { draw[2000].call() draw[6000].call() }, 9000: Fn.new { draw[1000].call() draw[8000].call() } }   var numbers = [0, 1, 20, 300, 4000, 5555, 6789, 9999] for (number in numbers) { init.call() System.print("%(number):") var thousands = (number/1000).floor number = number % 1000 var hundreds = (number/100).floor number = number % 100 var tens = (number/10).floor var ones = number % 10 if (thousands > 0) draw[thousands*1000].call() if (hundreds > 0) draw[hundreds*100].call() if (tens > 0) draw[tens*10].call() if (ones > 0) draw[ones].call() Fmt.mprint(n, 1, 0, "") System.print() }
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)
#Icon_and_Unicon
Icon and Unicon
record point(x,y)   procedure main() minDist := 0 minPair := &null every (points := [],p1 := readPoint()) do { if *points == 1 then minDist := dSquared(p1,points[1]) every minDist >=:= dSquared(p1,p2 := !points) do minPair := [p1,p2] push(points, p1) }   if \minPair then { write("(",minPair[1].x,",",minPair[1].y,") -> ", "(",minPair[2].x,",",minPair[2].y,")") } else write("One or fewer points!") end   procedure readPoint() # Skips lines that don't have two numbers on them suspend !&input ? point(numeric(tab(upto(', '))), numeric((move(1),tab(0)))) end   procedure dSquared(p1,p2) # Compute the square of the distance return (p2.x-p1.x)^2 + (p2.y-p1.y)^2 # (sufficient for closeness) end
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of running any but the last function, to demonstrate that the function indeed remembers its value. Goal Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. In imperative languages, one would generally use a loop with a mutable counter variable. For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run. See also: Multiple distinct objects
#Oforth
Oforth
: newClosure(i) #[ i sq ] ; 10 seq map(#newClosure) at(7) perform .
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of running any but the last function, to demonstrate that the function indeed remembers its value. Goal Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. In imperative languages, one would generally use a loop with a mutable counter variable. For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run. See also: Multiple distinct objects
#PARI.2FGP
PARI/GP
vector(10,i,()->i^2)[5]()
http://rosettacode.org/wiki/Circular_primes
Circular primes
Definitions A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime. For example: 1193 is a circular prime, since 1931, 9311 and 3119 are all also prime. Note that a number which is a cyclic permutation of a smaller circular prime is not considered to be itself a circular prime. So 13 is a circular prime, but 31 is not. A repunit (denoted by R) is a number whose base 10 representation contains only the digit 1. For example: R(2) = 11 and R(5) = 11111 are repunits. Task Find the first 19 circular primes. If your language has access to arbitrary precision integer arithmetic, given that they are all repunits, find the next 4 circular primes. (Stretch) Determine which of the following repunits are probably circular primes: R(5003), R(9887), R(15073), R(25031), R(35317) and R(49081). The larger ones may take a long time to process so just do as many as you reasonably can. See also Wikipedia article - Circular primes. Wikipedia article - Repunit. OEIS sequence A016114 - Circular primes.
#Wren
Wren
import "/math" for Int import "/big" for BigInt import "/str" for Str   var circs = []   var isCircular = Fn.new { |n| var nn = n var pow = 1 // will eventually contain 10 ^ d where d is number of digits in n while (nn > 0) { pow = pow * 10 nn = (nn/10).floor } nn = n while (true) { nn = nn * 10 var f = (nn/pow).floor // first digit nn = nn + f * (1 - pow) if (circs.contains(nn)) return false if (nn == n) break if (!Int.isPrime(nn)) return false } return true }   var repunit = Fn.new { |n| BigInt.new(Str.repeat("1", n)) }   System.print("The first 19 circular primes are:") var digits = [1, 3, 7, 9] var q = [1, 2, 3, 5, 7, 9] // queue the numbers to be examined var fq = [1, 2, 3, 5, 7, 9] // also queue the corresponding first digits var count = 0 while (true) { var f = q[0] // peek first element var fd = fq[0] // peek first digit if (Int.isPrime(f) && isCircular.call(f)) { circs.add(f) count = count + 1 if (count == 19) break } q.removeAt(0) // pop first element fq.removeAt(0) // ditto for first digit queue if (f != 2 && f != 5) { // if digits > 1 can't contain a 2 or 5 // add numbers with one more digit to queue // only numbers whose last digit >= first digit need be added for (d in digits) { if (d >= fd) { q.add(f*10+d) fq.add(fd) } } } } System.print(circs)   System.print("\nThe next 4 circular primes, in repunit format, are:") count = 0 var rus = [] var primes = Int.primeSieve(10000) for (p in primes[3..-1]) { if (repunit.call(p).isProbablePrime(1)) { rus.add("R(%(p))") count = count + 1 if (count == 4) break } } System.print(rus)
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
#C.2B.2B
C++
  #include <iostream> #include <cmath> #include <tuple>   struct point { double x, y; };   bool operator==(const point& lhs, const point& rhs) { return std::tie(lhs.x, lhs.y) == std::tie(rhs.x, rhs.y); }   enum result_category { NONE, ONE_COINCEDENT, ONE_DIAMETER, TWO, INFINITE };   using result_t = std::tuple<result_category, point, point>;   double distance(point l, point r) { return std::hypot(l.x - r.x, l.y - r.y); }   result_t find_circles(point p1, point p2, double r) { point ans1 { 1/0., 1/0.}, ans2 { 1/0., 1/0.}; if (p1 == p2) { if(r == 0.) return std::make_tuple(ONE_COINCEDENT, p1, p2 ); else return std::make_tuple(INFINITE, ans1, ans2); } point center { p1.x/2 + p2.x/2, p1.y/2 + p2.y/2}; double half_distance = distance(center, p1); if(half_distance > r) return std::make_tuple(NONE, ans1, ans2); if(half_distance - r == 0) return std::make_tuple(ONE_DIAMETER, center, ans2); double root = std::hypot(r, half_distance) / distance(p1, p2); ans1.x = center.x + root * (p1.y - p2.y); ans1.y = center.y + root * (p2.x - p1.x); ans2.x = center.x - root * (p1.y - p2.y); ans2.y = center.y - root * (p2.x - p1.x); return std::make_tuple(TWO, ans1, ans2); }   void print(result_t result, std::ostream& out = std::cout) { point r1, r2; result_category res; std::tie(res, r1, r2) = result; switch(res) { case NONE: out << "There are no solutions, points are too far away\n"; break; case ONE_COINCEDENT: case ONE_DIAMETER: out << "Only one solution: " << r1.x << ' ' << r1.y << '\n'; break; case INFINITE: out << "Infinitely many circles can be drawn\n"; break; case TWO: out << "Two solutions: " << r1.x << ' ' << r1.y << " and " << r2.x << ' ' << r2.y << '\n'; break; } }   int main() { constexpr int size = 5; const point points[size*2] = { {0.1234, 0.9876}, {0.8765, 0.2345}, {0.0000, 2.0000}, {0.0000, 0.0000}, {0.1234, 0.9876}, {0.1234, 0.9876}, {0.1234, 0.9876}, {0.8765, 0.2345}, {0.1234, 0.9876}, {0.1234, 0.9876} }; const double radius[size] = {2., 1., 2., .5, 0.};   for(int i = 0; i < size; ++i) print(find_circles(points[i*2], points[i*2 + 1], radius[i])); }
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).
#C
C
#include <math.h> #include <stdio.h>   const char* animals[] = { "Rat","Ox","Tiger","Rabbit","Dragon","Snake","Horse","Goat","Monkey","Rooster","Dog","Pig" }; const char* elements[] = { "Wood","Fire","Earth","Metal","Water" };   const char* getElement(int year) { int element = (int)floor((year - 4) % 10 / 2); return elements[element]; }   const char* getAnimal(int year) { return animals[(year - 4) % 12]; }   const char* getYY(int year) { if (year % 2 == 0) { return "yang"; } else { return "yin"; } }   int main() { int years[] = { 1935, 1938, 1968, 1972, 1976, 2017 }; int i;   //the zodiac cycle didnt start until 4 CE, so years <4 shouldnt be valid for (i = 0; i < 6; ++i) { int year = years[i]; printf("%d is the year of the %s %s (%s).\n", year, getElement(year), getAnimal(year), getYY(year)); }   return 0; }
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
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO;   procedure File_Exists is function Does_File_Exist (Name : String) return Boolean is The_File : Ada.Text_IO.File_Type; begin Open (The_File, In_File, Name); Close (The_File); return True; exception when Name_Error => return False; end Does_File_Exist; begin Put_Line (Boolean'Image (Does_File_Exist ("input.txt" ))); Put_Line (Boolean'Image (Does_File_Exist ("\input.txt"))); end File_Exists;
http://rosettacode.org/wiki/Check_that_file_exists
Check that file exists
Task Verify that a file called     input.txt     and   a directory called     docs     exist. This should be done twice:     once for the current working directory,   and   once for a file and a directory in the filesystem root. Optional criteria (May 2015):   verify it works with:   zero-length files   an unusual filename:   `Abdu'l-Bahá.txt
#Aikido
Aikido
  function exists (filename) { return stat (filename) != null }   exists ("input.txt") exists ("/input.txt") exists ("docs") exists ("/docs")    
http://rosettacode.org/wiki/Check_output_device_is_a_terminal
Check output device is a terminal
Task Demonstrate how to check whether the output device is a terminal or not. Related task   Check input device is a terminal
#J
J
3=nc<'wd'
http://rosettacode.org/wiki/Check_output_device_is_a_terminal
Check output device is a terminal
Task Demonstrate how to check whether the output device is a terminal or not. Related task   Check input device is a terminal
#Javascript.2FNodeJS
Javascript/NodeJS
node -p -e "Boolean(process.stdout.isTTY)" true
http://rosettacode.org/wiki/Check_output_device_is_a_terminal
Check output device is a terminal
Task Demonstrate how to check whether the output device is a terminal or not. Related task   Check input device is a terminal
#Julia
Julia
  if isa(STDOUT, Base.TTY) println("This program sees STDOUT as a TTY.") else println("This program does not see STDOUT as a TTY.") end  
http://rosettacode.org/wiki/Check_output_device_is_a_terminal
Check output device is a terminal
Task Demonstrate how to check whether the output device is a terminal or not. Related task   Check input device is a terminal
#Kotlin
Kotlin
// Kotlin Native version 0.5   import platform.posix.*   fun main(args: Array<String>) { if (isatty(STDOUT_FILENO) != 0) println("stdout is a terminal") else println("stdout is not a terminal") }
http://rosettacode.org/wiki/Check_output_device_is_a_terminal
Check output device is a terminal
Task Demonstrate how to check whether the output device is a terminal or not. Related task   Check input device is a terminal
#Lua
Lua
local function isTTY ( fd ) fd = tonumber( fd ) or 1 local ok, exit, signal = os.execute( string.format( "test -t %d", fd ) ) return (ok and exit == "exit") and signal == 0 or false end   print( "stdin", isTTY( 0 ) ) print( "stdout", isTTY( 1 ) ) print( "stderr", isTTY( 2 ) )
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.
#Common_Lisp
Common Lisp
;; Calculates the Cholesky decomposition matrix L ;; for a positive-definite, symmetric nxn matrix A. (defun chol (A) (let* ((n (car (array-dimensions A))) (L (make-array `(,n ,n) :initial-element 0)))   (do ((k 0 (incf k))) ((> k (- n 1)) nil) ;; First, calculate diagonal elements L_kk. (setf (aref L k k) (sqrt (- (aref A k k) (do* ((j 0 (incf j)) (sum (expt (aref L k j) 2) (incf sum (expt (aref L k j) 2)))) ((> j (- k 1)) sum)))))   ;; Then, all elements below a diagonal element, L_ik, i=k+1..n. (do ((i (+ k 1) (incf i))) ((> i (- n 1)) nil)   (setf (aref L i k) (/ (- (aref A i k) (do* ((j 0 (incf j)) (sum (* (aref L i j) (aref L k j)) (incf sum (* (aref L i j) (aref L k j))))) ((> j (- k 1)) sum))) (aref L k k)))))   ;; Return the calculated matrix L. L))
http://rosettacode.org/wiki/Check_input_device_is_a_terminal
Check input device is a terminal
Task Demonstrate how to check whether the input device is a terminal or not. Related task   Check output device is a terminal
#Kotlin
Kotlin
// Kotlin Native version 0.5   import platform.posix.*   fun main(args: Array<String>) { if (isatty(STDIN_FILENO) != 0) println("stdin is a terminal") else println("stdin is not a terminal") }  
http://rosettacode.org/wiki/Check_input_device_is_a_terminal
Check input device is a terminal
Task Demonstrate how to check whether the input device is a terminal or not. Related task   Check output device is a terminal
#Nemerle
Nemerle
def isTerm = System.Console.IsInputRedirected;
http://rosettacode.org/wiki/Check_input_device_is_a_terminal
Check input device is a terminal
Task Demonstrate how to check whether the input device is a terminal or not. Related task   Check output device is a terminal
#Nim
Nim
import terminal   echo if stdin.isatty: "stdin is a terminal" else: "stdin is not a terminal"
http://rosettacode.org/wiki/Check_input_device_is_a_terminal
Check input device is a terminal
Task Demonstrate how to check whether the input device is a terminal or not. Related task   Check output device is a terminal
#OCaml
OCaml
let () = print_endline ( if Unix.isatty Unix.stdin then "Input comes from tty." else "Input doesn't come from tty." )
http://rosettacode.org/wiki/Check_input_device_is_a_terminal
Check input device is a terminal
Task Demonstrate how to check whether the input device is a terminal or not. Related task   Check output device is a terminal
#Ol
Ol
  (define (isatty? fd) (syscall 16 fd 19)) (print (if (isatty? stdin) "Input comes from tty." "Input doesn't come from tty."))  
http://rosettacode.org/wiki/Check_input_device_is_a_terminal
Check input device is a terminal
Task Demonstrate how to check whether the input device is a terminal or not. Related task   Check output device is a terminal
#Perl
Perl
use strict; use warnings; use 5.010; if (-t) { say "Input comes from tty."; } else { say "Input doesn't come from tty."; }
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
#AWK
AWK
  # syntax: GAWK -f CHERYLS_BIRTHDAY.AWK [-v debug={0|1}] # # sorting: # PROCINFO["sorted_in"] is used by GAWK # SORTTYPE is used by Thompson Automation's TAWK # BEGIN { debug += 0 PROCINFO["sorted_in"] = "@ind_num_asc" ; SORTTYPE = 1 n = split("05/15,05/16,05/19,06/17,06/18,07/14,07/16,08/14,08/15,08/17",arr,",") for (i=1; i<=n; i++) { # move dates to a more friendly structure mmdd_arr[arr[i]] = "" } print("Cheryl offers these ten MM/DD choices:") cb_show_dates() printf("Cheryl then tells Albert her birth 'month' and Bernard her birth 'day'.\n\n") print("1. Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too.") cb_filter1() print("2. Bernard: At first I don't know when Cheryl's birthday is, but I know now.") cb_filter2() print("3. Albert: Then I also know when Cheryl's birthday is.") cb_filter3() exit(0) } function cb_filter1( i,j) { print("deduction: the month cannot have a unique day, leaving:") cb_load_arrays(4) for (j in arr1) { if (arr1[j] == 1) { if (debug) { printf("unique day %s\n",j) } arr3[arr2[j]] = "" } } cb_remove_dates() } function cb_filter2( i,j) { print("deduction: the day must be unique, leaving:") cb_load_arrays(4) for (j in arr1) { if (arr1[j] > 1) { if (debug) { printf("non-unique day %s\n",j) } arr3[j] = "" } } cb_remove_dates("...") } function cb_filter3( i,j) { print("deduction: the month must be unique, leaving:") cb_load_arrays(1) for (j in arr1) { if (arr1[j] > 1) { if (debug) { printf("non-unique month %s\n",j) } arr3[j] = "" } } cb_remove_dates() } function cb_load_arrays(col, i,key) { delete arr1 delete arr2 delete arr3 for (i in mmdd_arr) { key = substr(i,col,2) arr1[key]++ arr2[key] = substr(i,1,2) } } function cb_remove_dates(pattern, i,j) { for (j in arr3) { for (i in mmdd_arr) { if (i ~ ("^" pattern j)) { if (debug) { printf("removing %s\n",i) } delete mmdd_arr[i] } } } cb_show_dates() } function cb_show_dates( i) { if (debug) { printf("%d remaining\n",length(mmdd_arr)) } for (i in mmdd_arr) { printf("%s ",i) } printf("\n\n") }  
http://rosettacode.org/wiki/Checkpoint_synchronization
Checkpoint synchronization
The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before starting another one. Putting details together is the checkpoint at which tasks synchronize themselves before going their paths apart. The task Implement checkpoint synchronization in your language. Make sure that the solution is race condition-free. Note that a straightforward solution based on events is exposed to race condition. Let two tasks A and B need to be synchronized at a checkpoint. Each signals its event (EA and EB correspondingly), then waits for the AND-combination of the events (EA&EB) and resets its event. Consider the following scenario: A signals EA first and gets blocked waiting for EA&EB. Then B signals EB and loses the processor. Then A is released (both events are signaled) and resets EA. Now if B returns and enters waiting for EA&EB, it gets lost. When a worker is ready it shall not continue before others finish. A typical implementation bug is when a worker is counted twice within one working cycle causing its premature completion. This happens when the quickest worker serves its cycle two times while the laziest one is lagging behind. If you can, implement workers joining and leaving.
#Erlang
Erlang
  -module( checkpoint_synchronization ).   -export( [task/0] ).   task() -> Pid = erlang:spawn( fun() -> checkpoint_loop([], []) end ), [erlang:spawn(fun() -> random:seed(X, 1, 0), worker_loop(X, 3, Pid) end) || X <- lists:seq(1, 5)], erlang:exit( Pid, normal ).       checkpoint_loop( Assemblings, Completes ) -> receive {starting, Worker} -> checkpoint_loop( [Worker | Assemblings], Completes ); {done, Worker} -> New_assemblings = lists:delete( Worker, Assemblings ), New_completes = checkpoint_loop_release( New_assemblings, [Worker | Completes] ), checkpoint_loop( New_assemblings, New_completes ) end.   checkpoint_loop_release( [], Completes ) -> [X ! all_complete || X <- Completes], []; checkpoint_loop_release( _Assemblings, Completes ) -> Completes.   worker_loop( _Worker, 0, _Checkpoint ) -> ok; worker_loop( Worker, N, Checkpoint ) -> Checkpoint ! {starting, erlang:self()}, io:fwrite( "Worker ~p ~p~n", [Worker, N] ), timer:sleep( random:uniform(100) ), Checkpoint ! {done, erlang:self()}, receive all_complete -> ok end, worker_loop( Worker, N - 1, Checkpoint ).  
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
#Forth
Forth
include ffl/car.fs   10 car-create ar \ create a dynamic array with initial size 10   2 0 ar car-set \ ar[0] = 2 3 1 ar car-set \ ar[1] = 3 1 0 ar car-insert \ ar[0] = 1 ar[1] = 2 ar[2] = 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
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { Global a$ Document a$ Module Combinations (m as long, n as long){ Module Level (n, s, h) { If n=1 then { while Len(s) { Print h, car(s) ToClipBoard() s=cdr(s) } } Else { While len(s) { call Level n-1, cdr(s), cons(h, car(s)) s=cdr(s) } } Sub ToClipBoard() local m=each(h) Local b$="" While m { b$+=If$(Len(b$)<>0->" ","")+Format$("{0::-10}",Array(m)) } b$+=If$(Len(b$)<>0->" ","")+Format$("{0::-10}",Array(s,0))+{ } a$<=b$ ' assign to global need <= End Sub } If m<1 or n<1 then Error s=(,) for i=0 to n-1 { s=cons(s, (i,)) } Head=(,) Call Level m, s, Head } Clear a$ Combinations 3, 5 ClipBoard a$ } Checkit  
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.
#Quackery
Quackery
/O> say "23 is greater than 42 is " ... 23 42 > not if [ say "not " ] ... say "true." cr ... 23 is greater than 42 is not true. Stack empty. /O> say "23 is less than 42 is " ... 23 42 < not if [ say "not " ] ... say "true." cr ... 23 is less than 42 is true. Stack empty. /O> 23 42 = iff ... [ say "23 is equal to 42." ] ... else ... [ say "23 is different to 42." ] ... cr ... 23 is different to 42. Stack empty. /O> 23 42 != iff ... [ say "23 is not equal to 42." ] ... else ... [ say "23 is the same as 42." ] ... cr ... 23 is not equal to 42. Stack empty.
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}}} .
#C.2B.2B
C++
// Requires C++17 #include <iostream> #include <numeric> #include <vector> #include <execution>   template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) { _Ty b0 = b; _Ty x0 = 0; _Ty x1 = 1;   if (b == 1) { return 1; }   while (a > 1) { _Ty q = a / b; _Ty amb = a % b; a = b; b = amb;   _Ty xqx = x1 - q * x0; x1 = x0; x0 = xqx; }   if (x1 < 0) { x1 += b0; }   return x1; }   template<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) { _Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; });   _Ty sm = 0; for (int i = 0; i < n.size(); i++) { _Ty p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; }   return sm % prod; }   int main() { vector<int> n = { 3, 5, 7 }; vector<int> a = { 2, 3, 2 };   cout << chineseRemainder(n,a) << endl;   return 0; }
http://rosettacode.org/wiki/Chernick%27s_Carmichael_numbers
Chernick's Carmichael numbers
In 1939, Jack Chernick proved that, for n ≥ 3 and m ≥ 1: U(n, m) = (6m + 1) * (12m + 1) * Product_{i=1..n-2} (2^i * 9m + 1) is a Carmichael number if all the factors are primes and, for n > 4, m is a multiple of 2^(n-4). Example U(3, m) = (6m + 1) * (12m + 1) * (18m + 1) U(4, m) = U(3, m) * (2^2 * 9m + 1) U(5, m) = U(4, m) * (2^3 * 9m + 1) ... U(n, m) = U(n-1, m) * (2^(n-2) * 9m + 1) The smallest Chernick's Carmichael number with 3 prime factors, is: U(3, 1) = 1729. The smallest Chernick's Carmichael number with 4 prime factors, is: U(4, 1) = 63973. The smallest Chernick's Carmichael number with 5 prime factors, is: U(5, 380) = 26641259752490421121. For n = 5, the smallest number m that satisfy Chernick's conditions, is m = 380, therefore U(5, 380) is the smallest Chernick's Carmichael number with 5 prime factors. U(5, 380) is a Chernick's Carmichael number because m = 380 is a multiple of 2^(n-4), where n = 5, and the factors { (6*380 + 1), (12*380 + 1), (18*380 + 1), (36*380 + 1), (72*380 + 1) } are all prime numbers. Task For n ≥ 3, let a(n) be the smallest Chernick's Carmichael number with n prime factors. Compute a(n) for n = 3..9. Optional: find a(10). Note: it's perfectly acceptable to show the terms in factorized form: a(3) = 7 * 13 * 19 a(4) = 7 * 13 * 19 * 37 a(5) = 2281 * 4561 * 6841 * 13681 * 27361 ... See also Jack Chernick, On Fermat's simple theorem (PDF) OEIS A318646: The least Chernick's "universal form" Carmichael number with n prime factors Related tasks Carmichael 3 strong pseudoprimes
#Python
Python
  """   Python implementation of http://rosettacode.org/wiki/Chernick%27s_Carmichael_numbers   """   # use sympy for prime test   from sympy import isprime   # based on C version   def primality_pretest(k): if not (k % 3) or not (k % 5) or not (k % 7) or not (k % 11) or not(k % 13) or not (k % 17) or not (k % 19) or not (k % 23): return (k <= 23)   return True   def is_chernick(n, m):   t = 9 * m   if not primality_pretest(6 * m + 1): return False   if not primality_pretest(12 * m + 1): return False   for i in range(1,n-1): if not primality_pretest((t << i) + 1): return False   if not isprime(6 * m + 1): return False   if not isprime(12 * m + 1): return False   for i in range(1,n - 1): if not isprime((t << i) + 1): return False   return True   for n in range(3,10):   if n > 4: multiplier = 1 << (n - 4) else: multiplier = 1   if n > 5: multiplier *= 5     k = 1   while True: m = k * multiplier   if is_chernick(n, m): print("a("+str(n)+") has m = "+str(m)) break   k += 1  
http://rosettacode.org/wiki/Chowla_numbers
Chowla numbers
Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n   is a positive integer The sequence is named after   Sarvadaman D. S. Chowla,   (22 October 1907 ──► 10 December 1995), a London born Indian American mathematician specializing in number theory. German mathematician Carl Friedrich Gauss (1777─1855) said: "Mathematics is the queen of the sciences ─ and number theory is the queen of mathematics". Definitions Chowla numbers can also be expressed as: chowla(n) = sum of divisors of n excluding unity and n chowla(n) = sum( divisors(n)) - 1 - n chowla(n) = sum( properDivisors(n)) - 1 chowla(n) = sum(aliquotDivisors(n)) - 1 chowla(n) = aliquot(n) - 1 chowla(n) = sigma(n) - 1 - n chowla(n) = sigmaProperDivisiors(n) - 1   chowla(a*b) = a + b,   if a and b are distinct primes if chowla(n) = 0,  and n > 1, then n is prime if chowla(n) = n - 1, and n > 1, then n is a perfect number Task   create a   chowla   function that returns the   chowla number   for a positive integer   n   Find and display   (1 per line)   for the 1st   37   integers:   the integer   (the index)   the chowla number for that integer   For finding primes, use the   chowla   function to find values of zero   Find and display the   count   of the primes up to              100   Find and display the   count   of the primes up to           1,000   Find and display the   count   of the primes up to         10,000   Find and display the   count   of the primes up to       100,000   Find and display the   count   of the primes up to    1,000,000   Find and display the   count   of the primes up to  10,000,000   For finding perfect numbers, use the   chowla   function to find values of   n - 1   Find and display all   perfect numbers   up to   35,000,000   use commas within appropriate numbers   show all output here Related tasks   totient function   perfect numbers   Proper divisors   Sieve of Eratosthenes See also   the OEIS entry for   A48050 Chowla's function.
#FreeBASIC
FreeBASIC
  ' Chowla_numbers   #include "string.bi"   Dim Shared As Long limite limite = 10000000 Dim Shared As Boolean c(limite) Dim As Long count, topenumprimo, a count = 1 topenumprimo = 100 Dim As Longint p, k, kk, limitenumperfect limitenumperfect = 35000000 k = 2: kk = 3   Declare Function chowla(Byval n As Longint) As Longint Declare Sub sieve(Byval limite As Long, c() As Boolean)   Function chowla(Byval n As Longint) As Longint Dim As Long i, j, r i = 2 Do While i * i <= n j = n \ i If n Mod i = 0 Then r += i If i <> j Then r += j End If i += 1 Loop chowla = r End Function   Sub sieve(Byval limite As Long, c() As Boolean) Dim As Long i, j Redim As Boolean c(limite - 1) i = 3 Do While i * 3 < limite If Not c(i) Then If chowla(i) = false Then j = 3 * i Do While j < limite c(j) = true j += 2 * i Loop End If End If i += 2 Loop End Sub   Print "Chowla numbers" For a = 1 To 37 Print "chowla(" & Trim(Str(a)) & ") = " & Trim(Str(chowla(a))) Next a   ' Si chowla(n) = falso and n > 1 Entonces n es primo Print: Print "Contando los numeros primos hasta: " sieve(limite, c()) For a = 3 To limite - 1 Step 2 If Not c(a) Then count += 1 If a = topenumprimo - 1 Then Print Using "########## hay"; topenumprimo; Print count topenumprimo *= 10 End If Next a   ' Si chowla(n) = n - 1 and n > 1 Entonces n es un número perfecto Print: Print "Buscando numeros perfectos... " count = 0 Do p = k * kk : If p > limitenumperfect Then Exit Do If chowla(p) = p - 1 Then Print Using "##########,# es un numero perfecto"; p count += 1 End If k = kk + 1 : kk += k Loop Print: Print "Hay " & count & " numeros perfectos <= " & Format(limitenumperfect, "###############################,#")   Print: Print "Pulsa una tecla para salir" Sleep End  
http://rosettacode.org/wiki/Church_numerals
Church numerals
Task In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all. Church one applies its first argument f just once to its second argument x, yielding f(x) Church two applies its first argument f twice to its second argument x, yielding f(f(x)) and each successive Church numeral applies its first argument one additional time to its second argument, f(f(f(x))), f(f(f(f(x)))) ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument. Arithmetic operations on natural numbers can be similarly represented as functions on Church numerals. In your language define: Church Zero, a Church successor function (a function on a Church numeral which returns the next Church numeral in the series), functions for Addition, Multiplication and Exponentiation over Church numerals, a function to convert integers to corresponding Church numerals, and a function to convert Church numerals to corresponding integers. You should: Derive Church numerals three and four in terms of Church zero and a Church successor function. use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4, similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function, convert each result back to an integer, and return it or print it to the console.
#Nim
Nim
import macros, sugar type Fn = proc(p: pointer): pointer{.noSideEffect.} Church = proc(f: Fn): Fn{.noSideEffect.} MetaChurch = proc(c: Church): Church{.noSideEffect.}   #helpers: template λfλx(exp): untyped = (f: Fn){.closure.}=>((x: pointer){.closure.}=>exp) template λcλf(exp): untyped = (c: Church){.closure.}=>((f: Fn){.closure.}=>exp) macro type_erase(body: untyped): untyped = let name = if body[0].kind == nnkPostFix: body[0][1] else: body[0] typ = body[3][0] quote do: `body` proc `name`(p: pointer): pointer = template erased: untyped = cast[ptr `typ`](p)[] erased = erased.`name` p macro type_erased(body: untyped): untyped = let (id1, id2, id3) = (body[0][0][0], body[0][0][1], body[0][1]) quote do: result = `id3` result = cast[ptr typeof(`id3`)]( `id1`(`id2`)(result.addr) )[]   #simple math func zero*(): Church = λfλx: x func succ*(c: Church): Church = λfλx: f (c f)x func `+`*(c, d: Church): Church = λfλx: (c f) (d f)x func `*`*(c, d: Church): Church = λfλx: c(d f)x   #exponentiation func metazero(): MetaChurch = λcλf: f func succ(m: MetaChurch): MetaChurch{.type_erase.} = λcλf: c (m c)f converter toMeta*(c: Church): MetaChurch = type_erased: c(succ)(metazero()) func `^`*(c: Church, d: MetaChurch): Church = d c   #conversions to/from actual numbers func incr(x: int): int{.type_erase.} = x+1 func toInt(c: Church): int = type_erased: c(incr)(0) func toChurch*(x: int): Church = return if x <= 0: zero() else: toChurch(x-1).succ func `$`*(c: Church): string = $c.toInt   when isMainModule: let three = zero().succ.succ.succ let four = 4.toChurch echo [three+four, three*four, three^four, four^three]  
http://rosettacode.org/wiki/Church_numerals
Church numerals
Task In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all. Church one applies its first argument f just once to its second argument x, yielding f(x) Church two applies its first argument f twice to its second argument x, yielding f(f(x)) and each successive Church numeral applies its first argument one additional time to its second argument, f(f(f(x))), f(f(f(f(x)))) ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument. Arithmetic operations on natural numbers can be similarly represented as functions on Church numerals. In your language define: Church Zero, a Church successor function (a function on a Church numeral which returns the next Church numeral in the series), functions for Addition, Multiplication and Exponentiation over Church numerals, a function to convert integers to corresponding Church numerals, and a function to convert Church numerals to corresponding integers. You should: Derive Church numerals three and four in terms of Church zero and a Church successor function. use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4, similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function, convert each result back to an integer, and return it or print it to the console.
#OCaml
OCaml
(* Using type as suggested in https://stackoverflow.com/questions/43426709/does-ocamls-type-system-prevent-it-from-modeling-church-numerals This is an explicitly polymorphic type : it says that f must be of type ('a -> 'a) -> 'a -> 'a for any possible a "at same time". *) type church_num = { f : 'a. ('a -> 'a) -> 'a -> 'a }   (* Zero means apply f 0 times to x, aka return x *) let ch_zero : church_num = { f = fun _ -> fun x -> x }   (* One simplifies to just returning the function *) let ch_one : church_num = { f = fun fn -> fn }   (* The next numeral of a church numeral would apply f one more time *) let ch_succ (c : church_num) : church_num = { f = fun fn x -> fn (c.f fn x) }   (* Adding m and n is applying f m times and then also n times *) let ch_add (m : church_num) (n : church_num) : church_num = { f = fun fn x -> n.f fn (m.f fn x) }   (* Multiplying is repeated addition : add n, m times *) let ch_mul (m : church_num) (n : church_num) : church_num = { f = fun fn x -> m.f (n.f fn) x }   (* Exp is repeated multiplication : multiply by base, exp times. However, Church numeral n is in some sense the n'th power of a function f applied to x So exp base = apply function base to the exp'th power = base^exp. *) let ch_exp (base : church_num) (exp : church_num) : church_num = { f = fun fn x -> (exp.f base.f) fn x }   (* extended Church functions: *)   (* test function for church zero *) let ch_is_zero (c : church_num) : church_num = { f = fun fn x -> c.f (fun _ -> fun _ -> fun xi -> xi) (* when argument is not ch_zero *) (fun fi -> fi) (* when argument is ch_zero *) fn x }   (* church predecessor function; reduces function calls by one unless already church zero *) let ch_pred (c : church_num) : church_num = { f = fun fn x -> c.f (fun g h -> h (g fn)) (fun _ -> x) (fun xi -> xi) }   (* church subtraction function; calls predecessor function second argument times on first *) let ch_sub (m : church_num) (n : church_num) : church_num = n.f ch_pred m   (* church division function; counts number of times divisor can be recursively subtracted from dividend *) let ch_div (dvdnd : church_num) (dvsr : church_num) : church_num = let rec divr n = (fun v -> v.f (fun _ -> (ch_succ (divr v))) ch_zero) (ch_sub n dvsr) in divr (ch_succ dvdnd)   (* conversion functions: *)   (* Convert a number to a church_num via recursion *) let church_of_int (n : int) : church_num = if n < 0 then raise (Invalid_argument (string_of_int n ^ " is not a natural number")) else (* Tail-recursed helper *) let rec helper n acc = if n = 0 then acc else helper (n-1) (ch_succ acc) in helper n ch_zero   (* Convert a church_num to an int is rather easy! Just +1 n times. *) let int_of_church (n : church_num) : int = n.f succ 0   (* Now the tasks at hand: *)   (* Derive Church numerals three, four, eleven, and twelve, in terms of Church zero and a Church successor function *)   let ch_three = church_of_int 3 let ch_four = ch_three |> ch_succ let ch_eleven = church_of_int 11 let ch_twelve = ch_eleven |> ch_succ   (* Use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4 *) let ch_7 = ch_add ch_three ch_four let ch_12 = ch_mul ch_three ch_four   (* Similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function *) let ch_64 = ch_exp ch_four ch_three let ch_81 = ch_exp ch_three ch_four   (* check that ch_is_zero works *) let ch_1 = ch_is_zero ch_zero let ch_0 = ch_is_zero ch_three   (* check church predecessor, subtraction, and division, functions work *) let ch_2 = ch_pred ch_three let ch_8 = ch_sub ch_eleven ch_three let ch_3 = ch_div ch_eleven ch_three let ch_4 = ch_div ch_twelve ch_three   (* Convert each result back to an integer, and return it as a string *) let result = List.map (fun c -> string_of_int(int_of_church c)) [ ch_three; ch_four; ch_7; ch_12; ch_64; ch_81; ch_eleven; ch_twelve; ch_1; ch_0; ch_2; ch_8; ch_3; ch_4 ] |> String.concat "; " |> Printf.sprintf "[ %s ]"   ;;   print_endline result
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.
#ERRE
ERRE
PROGRAM CLASS2_DEMO   CLASS QUADRATO   LOCAL LATO   PROCEDURE GETLATO(L) LATO=L END PROCEDURE   PROCEDURE AREA(->A) A=LATO*LATO END PROCEDURE   PROCEDURE PERIMETRO(->P) P=4*LATO END PROCEDURE   END CLASS   NEW P:QUADRATO,Q:QUADRATO   BEGIN P_GETLATO(10) P_AREA(->AREAP) PRINT(AREAP) Q_GETLATO(20) Q_PERIMETRO(->PERIMETROQ) PRINT(PERIMETROQ) END PROGRAM  
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.
#F.23
F#
type MyClass(init) = // constructor with one argument: init let mutable var = init // a private instance variable member x.Method() = // a simple method var <- var + 1 printfn "%d" var   // create an instance and use it let myObject = new MyClass(42) myObject.Method()
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)
#IS-BASIC
IS-BASIC
100 PROGRAM "Closestp.bas" 110 NUMERIC X(1 TO 10),Y(1 TO 10) 120 FOR I=1 TO 10 130 READ X(I),Y(I) 140 PRINT X(I),Y(I) 150 NEXT 160 LET MN=INF 170 FOR I=1 TO 9 180 FOR J=I+1 TO 10 190 LET DSQ=(X(I)-X(J))^2+(Y(I)-Y(J))^2 200 IF DSQ<MN THEN LET MN=DSQ:LET MINI=I:LET MINJ=J 210 NEXT 220 NEXT 230 PRINT "Closest pair is (";X(MINI);",";Y(MINI);") and (";X(MINJ);",";Y(MINJ);")":PRINT "at distance";SQR(MN) 240 DATA 0.654682,0.925557 250 DATA 0.409382,0.619391 260 DATA 0.891663,0.888594 270 DATA 0.716629,0.996200 280 DATA 0.477721,0.946355 290 DATA 0.925092,0.818220 300 DATA 0.624291,0.142924 310 DATA 0.211332,0.221507 320 DATA 0.293786,0.691701 330 DATA 0.839186,0.728260
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of running any but the last function, to demonstrate that the function indeed remembers its value. Goal Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. In imperative languages, one would generally use a loop with a mutable counter variable. For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run. See also: Multiple distinct objects
#Perl
Perl
my @f = map(sub { $_ * $_ }, 0 .. 9); # @f is an array of subs print $f[$_](), "\n" for (0 .. 8); # call and print all but last
http://rosettacode.org/wiki/Closures/Value_capture
Closures/Value capture
Task Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   i   (you may choose to start   i   from either   0   or   1),   when run, should return the square of the index,   that is,   i 2. Display the result of running any but the last function, to demonstrate that the function indeed remembers its value. Goal Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. In imperative languages, one would generally use a loop with a mutable counter variable. For each function to maintain the correct number, it has to capture the value of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run. See also: Multiple distinct objects
#Phix
Phix
with javascript_semantics -- First some generic handling stuff, handles partial_args -- of any mixture of any length and element types. sequence closures = {} function add_closure(integer rid, sequence partial_args) closures = append(closures,{rid,partial_args}) return length(closures) -- (return an integer id) end function function call_closure(integer id, sequence args) {integer rid, sequence partial_args} = closures[id] return call_func(rid,partial_args&args) end function -- The test routine to be made into a closure, or ten -- Note that all external references/captured variables must -- be passed as arguments, and grouped together on the lhs function square(integer i) return i*i end function -- Create the ten closures as asked for. -- Here, cids is just {1,2,3,4,5,6,7,8,9,10}, however ids would be more -- useful for a mixed bag of closures, possibly stored all over the shop. -- Likewise add_closure could have been a procedure for this demo, but -- you would probably want the function in a real-world application. sequence cids = {} for i=1 to 10 do --for i=11 to 20 do -- alternative test cids &= add_closure(routine_id("square"),{i}) end for -- And finally call em (this loop is blissfully unaware what function -- it is actually calling, and what partial_arguments it is passing) for i=1 to 10 do printf(1," %d",call_closure(cids[i],{})) end for
http://rosettacode.org/wiki/Circular_primes
Circular primes
Definitions A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime. For example: 1193 is a circular prime, since 1931, 9311 and 3119 are all also prime. Note that a number which is a cyclic permutation of a smaller circular prime is not considered to be itself a circular prime. So 13 is a circular prime, but 31 is not. A repunit (denoted by R) is a number whose base 10 representation contains only the digit 1. For example: R(2) = 11 and R(5) = 11111 are repunits. Task Find the first 19 circular primes. If your language has access to arbitrary precision integer arithmetic, given that they are all repunits, find the next 4 circular primes. (Stretch) Determine which of the following repunits are probably circular primes: R(5003), R(9887), R(15073), R(25031), R(35317) and R(49081). The larger ones may take a long time to process so just do as many as you reasonably can. See also Wikipedia article - Circular primes. Wikipedia article - Repunit. OEIS sequence A016114 - Circular primes.
#XPL0
XPL0
func IsPrime(N); \Return 'true' if N > 2 is a prime number int N, I; [if (N&1) = 0 \even number\ then return false; for I:= 3 to sqrt(N) do [if rem(N/I) = 0 then return false; I:= I+1; ]; return true; ];   func CircPrime(N0); \Return 'true' if N0 is a circular prime int N0, N, Digits, Rotation, I, R; [N:= N0; Digits:= 0; \count number of digits in N repeat Digits:= Digits+1; N:= N/10; until N = 0; N:= N0; for Rotation:= 0 to Digits-1 do [if not IsPrime(N) then return false; N:= N/10; \rotate least sig digit into high end R:= rem(0); for I:= 0 to Digits-2 do R:= R*10; N:= N+R; if N0 > N then \reject N0 if it has a smaller prime rotation return false; ]; return true; ];   int Counter, N; [IntOut(0, 2); ChOut(0, ^ ); \show first circular prime Counter:= 1; N:= 3; \remaining primes are odd loop [if CircPrime(N) then [IntOut(0, N); ChOut(0, ^ ); Counter:= Counter+1; if Counter >= 19 then quit; ]; N:= N+2; ]; ]
http://rosettacode.org/wiki/Circular_primes
Circular primes
Definitions A circular prime is a prime number with the property that the number generated at each intermediate step when cyclically permuting its (base 10) digits will also be prime. For example: 1193 is a circular prime, since 1931, 9311 and 3119 are all also prime. Note that a number which is a cyclic permutation of a smaller circular prime is not considered to be itself a circular prime. So 13 is a circular prime, but 31 is not. A repunit (denoted by R) is a number whose base 10 representation contains only the digit 1. For example: R(2) = 11 and R(5) = 11111 are repunits. Task Find the first 19 circular primes. If your language has access to arbitrary precision integer arithmetic, given that they are all repunits, find the next 4 circular primes. (Stretch) Determine which of the following repunits are probably circular primes: R(5003), R(9887), R(15073), R(25031), R(35317) and R(49081). The larger ones may take a long time to process so just do as many as you reasonably can. See also Wikipedia article - Circular primes. Wikipedia article - Repunit. OEIS sequence A016114 - Circular primes.
#Zig
Zig
  const std = @import("std"); const math = std.math; const heap = std.heap; const stdout = std.io.getStdOut().writer();   pub fn main() !void { var arena = heap.ArenaAllocator.init(heap.page_allocator); defer arena.deinit();   var candidates = std.PriorityQueue(u32).init(&arena.allocator, u32cmp); defer candidates.deinit();   try stdout.print("The circular primes are:\n", .{}); try stdout.print("{:10}" ** 4, .{ 2, 3, 5, 7 });   var c: u32 = 4; try candidates.add(0); while (true) { var n = candidates.remove(); if (n > 1_000_000) break; if (n > 10 and circular(n)) { try stdout.print("{:10}", .{n}); c += 1; if (c % 10 == 0) try stdout.print("\n", .{}); } try candidates.add(10 * n + 1); try candidates.add(10 * n + 3); try candidates.add(10 * n + 7); try candidates.add(10 * n + 9); } try stdout.print("\n", .{}); }   fn u32cmp(a: u32, b: u32) math.Order { return math.order(a, b); }   fn circular(n0: u32) bool { if (!isprime(n0)) return false else { var n = n0; var d = @floatToInt(u32, @log10(@intToFloat(f32, n))); return while (d > 0) : (d -= 1) { n = rotate(n); if (n < n0 or !isprime(n)) break false; } else true; } }   fn rotate(n: u32) u32 { if (n == 0) return 0 else { const d = @floatToInt(u32, @log10(@intToFloat(f32, n))); // digit count - 1 const m = math.pow(u32, 10, d); return (n % m) * 10 + n / m; } }   fn isprime(n: u32) bool { if (n < 2) return false;   inline for ([3]u3{ 2, 3, 5 }) |p| { if (n % p == 0) return n == p; }   const wheel235 = [_]u3{ 6, 4, 2, 4, 2, 4, 6, 2, }; var i: u32 = 1; var f: u32 = 7; return while (f * f <= n) { if (n % f == 0) break false; f += wheel235[i]; i = (i + 1) & 0x07; } else true; }  
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
#D
D
import std.stdio, std.typecons, std.math;   class ValueException : Exception { this(string msg_) pure { super(msg_); } }   struct V2 { double x, y; } struct Circle { double x, y, r; }   /**Following explanation at: http://mathforum.org/library/drmath/view/53027.html */ Tuple!(Circle, Circle) circlesFromTwoPointsAndRadius(in V2 p1, in V2 p2, in double r) pure in { assert(r >= 0, "radius can't be negative"); } body { enum nBits = 40;   if (r.abs < (1.0 / (2.0 ^^ nBits))) throw new ValueException("radius of zero");   if (feqrel(p1.x, p2.x) >= nBits && feqrel(p1.y, p2.y) >= nBits) throw new ValueException("coincident points give" ~ " infinite number of Circles");   // Delta between points. immutable d = V2(p2.x - p1.x, p2.y - p1.y);   // Distance between points. immutable q = sqrt(d.x ^^ 2 + d.y ^^ 2); if (q > 2.0 * r) throw new ValueException("separation of points > diameter");   // Halfway point. immutable h = V2((p1.x + p2.x) / 2, (p1.y + p2.y) / 2);   // Distance along the mirror line. immutable dm = sqrt(r ^^ 2 - (q / 2) ^^ 2);   return typeof(return)( Circle(h.x - dm * d.y / q, h.y + dm * d.x / q, r.abs), Circle(h.x + dm * d.y / q, h.y - dm * d.x / q, r.abs)); }   void main() { foreach (immutable t; [ tuple(V2(0.1234, 0.9876), V2(0.8765, 0.2345), 2.0), tuple(V2(0.0000, 2.0000), V2(0.0000, 0.0000), 1.0), tuple(V2(0.1234, 0.9876), V2(0.1234, 0.9876), 2.0), tuple(V2(0.1234, 0.9876), V2(0.8765, 0.2345), 0.5), tuple(V2(0.1234, 0.9876), V2(0.1234, 0.9876), 0.0)]) { writefln("Through points:\n  %s  %s and radius %f\n" ~ "You can construct the following circles:", t[]); try { writefln("  %s\n  %s\n", circlesFromTwoPointsAndRadius(t[])[]); } catch (ValueException v) writefln(" ERROR: %s\n", v.msg); } }
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).
#C.23
C#
using System;   namespace ChineseZodiac { class Program { static string[] animals = { "Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake", "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig" }; static string[] elements = { "Wood", "Fire", "Earth", "Metal", "Water" }; static string[] animalChars = { "子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥" }; static string[,] elementChars = { { "甲", "丙", "戊", "庚", "壬" }, { "乙", "丁", "己", "辛", "癸" } };   static string getYY(int year) { if (year % 2 == 0) { return "yang"; } return "yin"; }   static void Main(string[] args) { Console.OutputEncoding = System.Text.Encoding.UTF8; int[] years = { 1935, 1938, 1968, 1972, 1976, 1984, 1985, 2017 }; for (int i = 0; i < years.Length; i++) { int ei = (int)Math.Floor((years[i] - 4.0) % 10 / 2); int ai = (years[i] - 4) % 12; Console.WriteLine("{0} is the year of the {1} {2} ({3}). {4}{5}", years[i], elements[ei], animals[ai], getYY(years[i]), elementChars[years[i] % 2, ei], animalChars[(years[i] - 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
#ALGOL_68
ALGOL 68
# Check files and directories exist #   # check a file exists by attempting to open it for input # # returns TRUE if the file exists, FALSE otherwise # PROC file exists = ( STRING file name )BOOL: IF FILE f; open( f, file name, stand in channel ) = 0 THEN # file opened OK so must exist # close( f ); TRUE ELSE # file cannot be opened - assume it does not exist # FALSE FI # file exists # ;   # print a suitable messages if the specified file exists # PROC test file exists = ( STRING name )VOID: print( ( "file: " , name , IF file exists( name ) THEN " does" ELSE " does not" FI , " exist" , newline ) ); # print a suitable messages if the specified directory exists # PROC test directory exists = ( STRING name )VOID: print( ( "dir: " , name , IF file is directory( name ) THEN " does" ELSE " does not" FI , " exist" , newline ) );   # test the flies and directories mentioned in the task exist or not # test file exists( "input.txt" ); test file exists( "\input.txt"); test directory exists( "docs" ); test directory exists( "\docs" )
http://rosettacode.org/wiki/Check_output_device_is_a_terminal
Check output device is a terminal
Task Demonstrate how to check whether the output device is a terminal or not. Related task   Check input device is a terminal
#Nemerle
Nemerle
def isTerm = System.Console.IsOutputRedirected;
http://rosettacode.org/wiki/Check_output_device_is_a_terminal
Check output device is a terminal
Task Demonstrate how to check whether the output device is a terminal or not. Related task   Check input device is a terminal
#Nim
Nim
import terminal   stderr.write if stdout.isatty: "stdout is a terminal\n" else: "stdout is not a terminal\n"
http://rosettacode.org/wiki/Check_output_device_is_a_terminal
Check output device is a terminal
Task Demonstrate how to check whether the output device is a terminal or not. Related task   Check input device is a terminal
#OCaml
OCaml
let () = print_endline ( if Unix.isatty Unix.stdout then "Output goes to tty." else "Output doesn't go to tty." )
http://rosettacode.org/wiki/Check_output_device_is_a_terminal
Check output device is a terminal
Task Demonstrate how to check whether the output device is a terminal or not. Related task   Check input device is a terminal
#Ol
Ol
  (define (isatty? fd) (syscall 16 fd 19)) (print (if (isatty? stdout) "stdout is a tty." "stdout is not a tty."))  
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.
#11l
11l
print(‘a’.code) // prints "97" print(Char(code' 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.
#D
D
import std.stdio, std.math, std.numeric;   T[][] cholesky(T)(in T[][] A) pure nothrow /*@safe*/ { auto L = new T[][](A.length, A.length); foreach (immutable r, row; L) row[r + 1 .. $] = 0; foreach (immutable i; 0 .. A.length) foreach (immutable j; 0 .. i + 1) { auto t = dotProduct(L[i][0 .. j], L[j][0 .. j]); L[i][j] = (i == j) ? (A[i][i] - t) ^^ 0.5 : (1.0 / L[j][j] * (A[i][j] - t)); } return L; }   void main() { immutable double[][] m1 = [[25, 15, -5], [15, 18, 0], [-5, 0, 11]]; writefln("%(%(%2.0f %)\n%)\n", m1.cholesky);   immutable double[][] m2 = [[18, 22, 54, 42], [22, 70, 86, 62], [54, 86, 174, 134], [42, 62, 134, 106]]; writefln("%(%(%2.3f %)\n%)", m2.cholesky); }
http://rosettacode.org/wiki/Check_input_device_is_a_terminal
Check input device is a terminal
Task Demonstrate how to check whether the input device is a terminal or not. Related task   Check output device is a terminal
#Phix
Phix
without js -- (no input redirection in a browser!) printf(1,"stdin:%t, stdout:%t, stderr:%t\n",{isatty(0),isatty(1),isatty(2)})
http://rosettacode.org/wiki/Check_input_device_is_a_terminal
Check input device is a terminal
Task Demonstrate how to check whether the input device is a terminal or not. Related task   Check output device is a terminal
#Pike
Pike
void main() { if(Stdio.Terminfo.is_tty()) write("Input comes from tty.\n"); else write("Input doesn't come from tty.\n"); }
http://rosettacode.org/wiki/Check_input_device_is_a_terminal
Check input device is a terminal
Task Demonstrate how to check whether the input device is a terminal or not. Related task   Check output device is a terminal
#Python
Python
from sys import stdin if stdin.isatty(): print("Input comes from tty.") else: print("Input doesn't come from tty.")
http://rosettacode.org/wiki/Check_input_device_is_a_terminal
Check input device is a terminal
Task Demonstrate how to check whether the input device is a terminal or not. Related task   Check output device is a terminal
#Quackery
Quackery
[ $ |from sys import stdin to_stack( 1 if stdin.isatty() else 0)| python ] is ttyin ( --> b )   ttyin if [ say "Looks like a teletype." ] else [ say "Not a teletype." ]
http://rosettacode.org/wiki/Check_input_device_is_a_terminal
Check input device is a terminal
Task Demonstrate how to check whether the input device is a terminal or not. Related task   Check output device is a terminal
#Racket
Racket
  (terminal-port? (current-input-port))  
http://rosettacode.org/wiki/Check_input_device_is_a_terminal
Check input device is a terminal
Task Demonstrate how to check whether the input device is a terminal or not. Related task   Check output device is a terminal
#Raku
Raku
say $*IN.t ?? "Input comes from tty." !! "Input doesn't come from tty.";
http://rosettacode.org/wiki/Check_input_device_is_a_terminal
Check input device is a terminal
Task Demonstrate how to check whether the input device is a terminal or not. Related task   Check output device is a terminal
#REXX
REXX
/*REXX program determines if input comes from terminal or standard input*/   if queued() then say 'input comes from the terminal.' else say 'input comes from the (stacked) terminal queue.'   /*stick a fork in it, we're done.*/  
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
#C
C
#include <stdbool.h> #include <stdio.h>   char *months[] = { "ERR", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };   struct Date { int month, day; bool active; } dates[] = { {5,15,true}, {5,16,true}, {5,19,true}, {6,17,true}, {6,18,true}, {7,14,true}, {7,16,true}, {8,14,true}, {8,15,true}, {8,17,true} }; #define UPPER_BOUND (sizeof(dates) / sizeof(struct Date))   void printRemaining() { int i, c; for (i = 0, c = 0; i < UPPER_BOUND; i++) { if (dates[i].active) { c++; } } printf("%d remaining.\n", c); }   void printAnswer() { int i; for (i = 0; i < UPPER_BOUND; i++) { if (dates[i].active) { printf("%s, %d\n", months[dates[i].month], dates[i].day); } } }   void firstPass() { // the month cannot have a unique day int i, j, c; for (i = 0; i < UPPER_BOUND; i++) { c = 0;   for (j = 0; j < UPPER_BOUND; j++) { if (dates[j].day == dates[i].day) { c++; } }   if (c == 1) { for (j = 0; j < UPPER_BOUND; j++) { if (!dates[j].active) continue; if (dates[j].month == dates[i].month) { dates[j].active = false; } } } } }   void secondPass() { // the day must now be unique int i, j, c; for (i = 0; i < UPPER_BOUND; i++) { if (!dates[i].active) continue; c = 0;   for (j = 0; j < UPPER_BOUND; j++) { if (!dates[j].active) continue; if (dates[j].day == dates[i].day) { c++; } }   if (c > 1) { for (j = 0; j < UPPER_BOUND; j++) { if (!dates[j].active) continue; if (dates[j].day == dates[i].day) { dates[j].active = false; } } } } }   void thirdPass() { // the month must now be unique int i, j, c; for (i = 0; i < UPPER_BOUND; i++) { if (!dates[i].active) continue; c = 0;   for (j = 0; j < UPPER_BOUND; j++) { if (!dates[j].active) continue; if (dates[j].month == dates[i].month) { c++; } }   if (c > 1) { for (j = 0; j < UPPER_BOUND; j++) { if (!dates[j].active) continue; if (dates[j].month == dates[i].month) { dates[j].active = false; } } } } }   int main() { printRemaining(); // the month cannot have a unique day firstPass();   printRemaining(); // the day must now be unique secondPass();   printRemaining(); // the month must now be unique thirdPass();   printAnswer(); return 0; }
http://rosettacode.org/wiki/Checkpoint_synchronization
Checkpoint synchronization
The checkpoint synchronization is a problem of synchronizing multiple tasks. Consider a workshop where several workers (tasks) assembly details of some mechanism. When each of them completes his work they put the details together. There is no store, so a worker who finished its part first must wait for others before starting another one. Putting details together is the checkpoint at which tasks synchronize themselves before going their paths apart. The task Implement checkpoint synchronization in your language. Make sure that the solution is race condition-free. Note that a straightforward solution based on events is exposed to race condition. Let two tasks A and B need to be synchronized at a checkpoint. Each signals its event (EA and EB correspondingly), then waits for the AND-combination of the events (EA&EB) and resets its event. Consider the following scenario: A signals EA first and gets blocked waiting for EA&EB. Then B signals EB and loses the processor. Then A is released (both events are signaled) and resets EA. Now if B returns and enters waiting for EA&EB, it gets lost. When a worker is ready it shall not continue before others finish. A typical implementation bug is when a worker is counted twice within one working cycle causing its premature completion. This happens when the quickest worker serves its cycle two times while the laziest one is lagging behind. If you can, implement workers joining and leaving.
#FreeBASIC
FreeBASIC
#include "ontimer.bi"   Randomize Timer Dim Shared As Uinteger nWorkers = 3 Dim Shared As Uinteger tID(nWorkers) Dim Shared As Integer cnt(nWorkers) Dim Shared As Integer checked = 0   Sub checkpoint() Dim As Boolean sync   If checked = 0 Then sync = False checked += 1 If (sync = False) And (checked = nWorkers) Then sync = True Color 14 : Print "--Sync Point--" checked = 0 End If End Sub   Sub task(worker As Uinteger) Redim Preserve cnt(nWorkers)   Select Case cnt(worker) Case 0 cnt(worker) = Rnd * 3 Color 15 : Print "Worker " & worker & " starting (" & cnt(worker) & " ticks)" Case -1 Exit Select Case Else cnt(worker) -= 1 If cnt(worker) = 0 Then Color 7 : Print "Worker "; worker; " ready and waiting" cnt(worker) = -1 checkpoint cnt(worker) = 0 End If End Select End Sub   Sub worker1 task(1) End Sub Sub worker2 task(2) End Sub Sub worker3 task(3) End Sub   Do OnTimer(500, @worker1, 1) OnTimer(100, @worker2, 1) OnTimer(900, @worker3, 1) Sleep 1000 Loop
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
#Fortran
Fortran
REAL A(36) !Declares a one-dimensional array A(1), A(2), ... A(36) A(1) = 1 !Assigns a value to the first element. A(2) = 3*A(1) + 5 !The second element gets 8.
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
#M4
M4
divert(-1) define(`set',`define(`$1[$2]',`$3')') define(`get',`defn(`$1[$2]')') define(`setrange',`ifelse(`$3',`',$2,`define($1[$2],$3)`'setrange($1, incr($2),shift(shift(shift($@))))')') define(`for', `ifelse($#,0,``$0'', `ifelse(eval($2<=$3),1, `pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),$3,`$4')')')') define(`show', `for(`k',0,decr($1),`get(a,k) ')')   define(`chklim', `ifelse(get(`a',$3),eval($2-($1-$3)), `chklim($1,$2,decr($3))', `set(`a',$3,incr(get(`a',$3)))`'for(`k',incr($3),decr($2), `set(`a',k,incr(get(`a',decr(k))))')`'nextcomb($1,$2)')') define(`nextcomb', `show($1) ifelse(eval(get(`a',0)<$2-$1),1, `chklim($1,$2,decr($1))')') define(`comb', `for(`j',0,decr($1),`set(`a',j,j)')`'nextcomb($1,$2)') divert   comb(3,5)
http://rosettacode.org/wiki/Conditional_structures
Conditional structures
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Task List the conditional structures offered by a programming language. See Wikipedia: conditionals for descriptions. Common conditional structures include if-then-else and switch. Less common are arithmetic if, ternary operator and Hash-based conditionals. Arithmetic if allows tight control over computed gotos, which optimizers have a hard time to figure out.
#R
R
x <- 0 if(x == 0) print("foo") x <- 1 if(x == 0) print("foo") if(x == 0) print("foo") else print("bar")
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}}} .
#Clojure
Clojure
(ns test-p.core (:require [clojure.math.numeric-tower :as math]))   (defn extended-gcd "The extended Euclidean algorithm Returns a list containing the GCD and the Bézout coefficients corresponding to the inputs. " [a b] (cond (zero? a) [(math/abs b) 0 1] (zero? b) [(math/abs a) 1 0] :else (loop [s 0 s0 1 t 1 t0 0 r (math/abs b) r0 (math/abs a)] (if (zero? r) [r0 s0 t0] (let [q (quot r0 r)] (recur (- s0 (* q s)) s (- t0 (* q t)) t (- r0 (* q r)) r))))))   (defn chinese_remainder " Main routine to return the chinese remainder " [n a] (let [prod (apply * n) reducer (fn [sum [n_i a_i]] (let [p (quot prod n_i) ; p = prod / n_i egcd (extended-gcd p n_i) ; Extended gcd inv_p (second egcd)] ; Second item is the inverse (+ sum (* a_i inv_p p)))) sum-prod (reduce reducer 0 (map vector n a))] ; Replaces the Python for loop to sum ; (map vector n a) is same as ;  ; Python's version Zip (n, a) (mod sum-prod prod))) ; Result line   (def n [3 5 7]) (def a [2 3 2])   (println (chinese_remainder n a))  
http://rosettacode.org/wiki/Chernick%27s_Carmichael_numbers
Chernick's Carmichael numbers
In 1939, Jack Chernick proved that, for n ≥ 3 and m ≥ 1: U(n, m) = (6m + 1) * (12m + 1) * Product_{i=1..n-2} (2^i * 9m + 1) is a Carmichael number if all the factors are primes and, for n > 4, m is a multiple of 2^(n-4). Example U(3, m) = (6m + 1) * (12m + 1) * (18m + 1) U(4, m) = U(3, m) * (2^2 * 9m + 1) U(5, m) = U(4, m) * (2^3 * 9m + 1) ... U(n, m) = U(n-1, m) * (2^(n-2) * 9m + 1) The smallest Chernick's Carmichael number with 3 prime factors, is: U(3, 1) = 1729. The smallest Chernick's Carmichael number with 4 prime factors, is: U(4, 1) = 63973. The smallest Chernick's Carmichael number with 5 prime factors, is: U(5, 380) = 26641259752490421121. For n = 5, the smallest number m that satisfy Chernick's conditions, is m = 380, therefore U(5, 380) is the smallest Chernick's Carmichael number with 5 prime factors. U(5, 380) is a Chernick's Carmichael number because m = 380 is a multiple of 2^(n-4), where n = 5, and the factors { (6*380 + 1), (12*380 + 1), (18*380 + 1), (36*380 + 1), (72*380 + 1) } are all prime numbers. Task For n ≥ 3, let a(n) be the smallest Chernick's Carmichael number with n prime factors. Compute a(n) for n = 3..9. Optional: find a(10). Note: it's perfectly acceptable to show the terms in factorized form: a(3) = 7 * 13 * 19 a(4) = 7 * 13 * 19 * 37 a(5) = 2281 * 4561 * 6841 * 13681 * 27361 ... See also Jack Chernick, On Fermat's simple theorem (PDF) OEIS A318646: The least Chernick's "universal form" Carmichael number with n prime factors Related tasks Carmichael 3 strong pseudoprimes
#Raku
Raku
use Inline::Perl5; use ntheory:from<Perl5> <:all>;   sub chernick-factors ($n, $m) { 6×$m + 1, 12×$m + 1, |((1 .. $n-2).map: { (1 +< $_) × 9×$m + 1 } ) }   sub chernick-carmichael-number ($n) {   my $multiplier = 1 +< (($n-4) max 0); my $iterator = $n < 5 ?? (1 .. *) !! (1 .. *).map: * × 5;   $multiplier × $iterator.first: -> $m { [&&] chernick-factors($n, $m × $multiplier).map: { is_prime($_) } }   }   for 3 .. 9 -> $n { my $m = chernick-carmichael-number($n); my @f = chernick-factors($n, $m); say "U($n, $m): {[×] @f} = {@f.join(' ⨉ ')}"; }
http://rosettacode.org/wiki/Chowla_numbers
Chowla numbers
Chowla numbers are also known as:   Chowla's function   chowla numbers   the chowla function   the chowla number   the chowla sequence The chowla number of   n   is   (as defined by Chowla's function):   the sum of the divisors of   n     excluding unity and   n   where   n   is a positive integer The sequence is named after   Sarvadaman D. S. Chowla,   (22 October 1907 ──► 10 December 1995), a London born Indian American mathematician specializing in number theory. German mathematician Carl Friedrich Gauss (1777─1855) said: "Mathematics is the queen of the sciences ─ and number theory is the queen of mathematics". Definitions Chowla numbers can also be expressed as: chowla(n) = sum of divisors of n excluding unity and n chowla(n) = sum( divisors(n)) - 1 - n chowla(n) = sum( properDivisors(n)) - 1 chowla(n) = sum(aliquotDivisors(n)) - 1 chowla(n) = aliquot(n) - 1 chowla(n) = sigma(n) - 1 - n chowla(n) = sigmaProperDivisiors(n) - 1   chowla(a*b) = a + b,   if a and b are distinct primes if chowla(n) = 0,  and n > 1, then n is prime if chowla(n) = n - 1, and n > 1, then n is a perfect number Task   create a   chowla   function that returns the   chowla number   for a positive integer   n   Find and display   (1 per line)   for the 1st   37   integers:   the integer   (the index)   the chowla number for that integer   For finding primes, use the   chowla   function to find values of zero   Find and display the   count   of the primes up to              100   Find and display the   count   of the primes up to           1,000   Find and display the   count   of the primes up to         10,000   Find and display the   count   of the primes up to       100,000   Find and display the   count   of the primes up to    1,000,000   Find and display the   count   of the primes up to  10,000,000   For finding perfect numbers, use the   chowla   function to find values of   n - 1   Find and display all   perfect numbers   up to   35,000,000   use commas within appropriate numbers   show all output here Related tasks   totient function   perfect numbers   Proper divisors   Sieve of Eratosthenes See also   the OEIS entry for   A48050 Chowla's function.
#Go
Go
package main   import "fmt"   func chowla(n int) int { if n < 1 { panic("argument must be a positive integer") } sum := 0 for i := 2; i*i <= n; i++ { if n%i == 0 { j := n / i if i == j { sum += i } else { sum += i + j } } } return sum }   func sieve(limit int) []bool { // True denotes composite, false denotes prime. // Only interested in odd numbers >= 3 c := make([]bool, limit) for i := 3; i*3 < limit; i += 2 { if !c[i] && chowla(i) == 0 { for j := 3 * i; j < limit; j += 2 * i { c[j] = true } } } return c }   func commatize(n int) string { s := fmt.Sprintf("%d", n) le := len(s) for i := le - 3; i >= 1; i -= 3 { s = s[0:i] + "," + s[i:] } return s }   func main() { for i := 1; i <= 37; i++ { fmt.Printf("chowla(%2d) = %d\n", i, chowla(i)) } fmt.Println()   count := 1 limit := int(1e7) c := sieve(limit) power := 100 for i := 3; i < limit; i += 2 { if !c[i] { count++ } if i == power-1 { fmt.Printf("Count of primes up to %-10s = %s\n", commatize(power), commatize(count)) power *= 10 } }   fmt.Println() count = 0 limit = 35000000 for i := uint(2); ; i++ { p := 1 << (i - 1) * (1<<i - 1) // perfect numbers must be of this form if p > limit { break } if chowla(p) == p-1 { fmt.Printf("%s is a perfect number\n", commatize(p)) count++ } } fmt.Println("There are", count, "perfect numbers <= 35,000,000") }
http://rosettacode.org/wiki/Church_numerals
Church numerals
Task In the Church encoding of natural numbers, the number N is encoded by a function that applies its first argument N times to its second argument. Church zero always returns the identity function, regardless of its first argument. In other words, the first argument is not applied to the second argument at all. Church one applies its first argument f just once to its second argument x, yielding f(x) Church two applies its first argument f twice to its second argument x, yielding f(f(x)) and each successive Church numeral applies its first argument one additional time to its second argument, f(f(f(x))), f(f(f(f(x)))) ... The Church numeral 4, for example, returns a quadruple composition of the function supplied as its first argument. Arithmetic operations on natural numbers can be similarly represented as functions on Church numerals. In your language define: Church Zero, a Church successor function (a function on a Church numeral which returns the next Church numeral in the series), functions for Addition, Multiplication and Exponentiation over Church numerals, a function to convert integers to corresponding Church numerals, and a function to convert Church numerals to corresponding integers. You should: Derive Church numerals three and four in terms of Church zero and a Church successor function. use Church numeral arithmetic to obtain the the sum and the product of Church 3 and Church 4, similarly obtain 4^3 and 3^4 in terms of Church numerals, using a Church numeral exponentiation function, convert each result back to an integer, and return it or print it to the console.
#Octave
Octave
  zero = @(f) @(x) x; succ = @(n) @(f) @(x) f(n(f)(x)); add = @(m, n) @(f) @(x) m(f)(n(f)(x)); mul = @(m, n) @(f) @(x) m(n(f))(x); pow = @(b, e) e(b);   % Need a short-circuiting ternary iif = @(varargin) varargin{3 - varargin{1}}();   % Helper for anonymous recursion % The branches are thunked to prevent infinite recursion to_church_ = @(f, i) iif(i == 0, @() zero, @() succ(f(f, i - 1))); to_church = @(i) to_church_(to_church_, i);   to_int = @(c) c(@(n) n + 1)(0);   three = succ(succ(succ(zero))); four = succ(succ(succ(succ(zero))));   cellfun(to_int, { add(three, four), mul(three, four), pow(three, four), pow(four, three)})
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.
#Factor
Factor
TUPLE: my-class foo bar baz ; M: my-class quux foo>> 20 + ; C: <my-class> my-class 10 20 30 <my-class> quux ! result: 30 TUPLE: my-child-class < my-class quxx ; C: <my-child-class> my-child-class M: my-child-class foobar 20 >>quux ; 20 20 30 <my-child-class> foobar quux ! result: 30
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.
#Falcon
Falcon
class class_name[ ( param_list ) ] [ from inh1[, inh2, ..., inhN] ] [ static block ] [ properties declaration ] [init block] [method list] end